text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
I will be referring back to this paper and encourage my readers to at least skim it as well. It may provide more understanding in how it works.
It describes a simple, yet hard to comprehend functional parser. I have attempted to translate this to C++, but first I wrote a more intuitive, less functional one. Just a simple calculator, somewhat close to what's described in the pdf, and it worked like this:
The first stage took the input string and created a list of token type-lexeme pairs. Given the input "1+2*2", it would spit back {(INT,"1"),(OP,"+"),...}. The next stage uses two mutually recursive functions to represent two parse states: that of sums and subtractions and that of numbers, multiplications and divisions. Since addition has the lowest precedence in this mini-language, it's safe to parenthesize the rest of the expression, meaning that if it parsed "1+", it will expect the next number to be a number, and it might want to add one to it, eagerly, but not if fallowed by a "2*2" since multiplication has higher precedence.
These functions convert the vector of tokens to an expression tree that evaluates the arguments."2*2" would parse to a tree with a multiplier at its root and two numbers as its leaves. So, after the first state (sums) had read "1+", it would eagerly construct an addition object with the left argument being 1, and the right argument being the result of the rest of the parse! So it reads "2*2" and builds a tree that becomes the right-side argument for our "1+" tree.
This solution is theoretically consistent with building a language using flex and bison. The source can be found here (gist). But it isn't functional. That's when I stumbled back onto this research paper and decided to give a real go at it.
Functional Parsing.The parser described in this paper does not act in the same way as my parser does. Rather than lexing, tokenizing, and building an expression tree, it cuts straight to the point. A Parser<int> will be a function that accepts a string and produces ints. But, the job may not be done; there may be more to parse. For every int it parses, it will also store the suffix of the parse. So, if p is some parser of type Parse<int>, p("1abc") will return a vector holding one match: the value, 1, and the suffix, "abc".
What does this class look like?
/* A Parser is a function taking a string and returning a vector of matches. */ template< class X > struct Parser { // The value is the target of the parse. (For example "1" may parse to int(1). using value_type = X; // A match consists of a value and the rest of the input to process. using parse_state = std::pair<X,std::string>; // A parse results in a list of matches. using result_type = std::vector< std::pair<X,std::string> >; // A parser is a function that produces matches. using function_type = std::function< result_type( const std::string& ) >; function_type f; Parser( function_type f ) : f(std::move(f)) { } Parser( const Parser<X>& p ) : f(p.f) { } Parser() { } result_type operator () ( const std::string& s ) const { return f( s ); } }; template< class X, class F > Parser<X> parser( F f ) { using G = typename Parser<X>::function_type; return Parser<X>( G(std::move(f)) ); }
I have mentioned in previous articles that one should avoid std::function for efficiency reasons, but it vastly simplifies things here. As you can see, Parser merely wraps itself around std::function. I would encourage the reader to think of it as a type alias--not deserving of being called a new type, but more than a typedef.
This is consistent with how the paper defines this type:
newtype Parser a = Parser (String -> [(a,String)])
If nothing can be parsed, and empty list will be returned. If many things are parsed, a list of each match will be returned.
The Parser Monad.As a reminder, the basic monadic operations are these:
a >> b = b -- Do a, then b.
a >>= f = b -- For each x from a, construct b with f(x).
mreturn x = a -- Construct a monad from a value.
How does this relate to parsing? A parser is basically just a function, so if p and q are both parsers, p >> q must return a new parser, a new function. The simple explanation (do p, then q) is correct. First, p parses and let's say it returns a match, (x,rest). rest is sent to q for parsing and the x is thrown away. It may sound odd to just throw away a value, but it will become more obvious soon.
If p had failed to parse a value, then q would not have been run.
The bind operation, p >>= f, extracts the parsed value, x, from p and creates a new parser from f(x). mreturn x creates a new parser that returns x as its value. It accepts any string, even an empty one. Ideally, x came from the output of another parser.
p >> q -- Run parser p, then q.
p >>= f -- Construct a parser with p's matches.
mreturn x -- Construct a parser that returns x.
We can define it like so:
template< class X > struct Monad< Parser<X> > { using Pair = typename Parser<X>::parse_state; using R = typename Parser<X>::result_type; /* * mreturn x = parser(s){ vector( pair(x,s) ) } * Return a parsed value. Forwards rest of input to the next parser. */ template< class M > static M mreturn( X x ) { return parser<typename M::value_type> ( [x]( const std::string& s ) { return R{ Pair(std::move(x),s) }; } ); } /* a >> b = b */ template< class Y, class Z > template< class Y, class Z > static Parser<Y> mdo( Parser<Z> a, Parser<Y> b ) { return a >>= [b]( const Z& z ) { return b; }; } /* Continue parsing from p into f. */ template< class F, class Y = typename std::result_of<F(X)>::type > static Y mbind( F f, Parser<X> p ) { using Z = typename Y::value_type; return parser<Z> ( [f,p]( const std::string& s ) { // First, extract p's matches. return p(s) >>= [&]( Pair p ) { // Then construct the new parser from the p's output. // Continue parsing with the remaining input with the new parser. return f( std::move(p.first) )( std::move(p.second) ); }; } ); } };
Do not worry if this source is difficult to understand. It is more important to understand how it is used (which is perhaps common with monads). Note that mdo is defined such that for every successful parse of a, b is parsed. If a fails to parse anything, b fails, too.
These monadic operations are the core building blocks from which we can build more complex system, but the paper also discusses MonadZero and MonadPlus. They are both type classes, like Monad, but extend it to do a few interesting things. In C++, one can concatenate two string by using simple addition: s1 + s2 = s12. MonadPlus is generalization of this. MonadZero completes this generalization by supplying the additive identity. For example, we know that zero + x = x. Thus, "" + s = s.
In parsing terms, zero would refer to a parser that matches nothing and adding two parsers, p+q, will produce a third parser that accepts either p's or q's. For example, itentifier+number would create a function that parses either identifiers or numbers.
We can define MonadPlus and MonadZero in the same way we would define Monad.
template< class ... > struct MonadZero; template< class ... > struct MonadPlus; template< class M, class Mo = MonadZero< Cat<M> > > auto mzero() -> decltype( Mo::template mzero<M>() ) { return Mo::template mzero<M>(); } template< class A, class B, class Mo = MonadPlus<Cat<A>> > auto mplus( A&& a, B&& b ) -> decltype( Mo::mplus(std::declval<A>(),std::declval<B>()) ) { return Mo::mplus( std::forward<A>(a), std::forward<B>(b) ); } template< class X, class Y > auto operator + ( X&& x, Y&& y ) -> decltype( mplus(std::declval<X>(),std::declval<Y>()) ) { return mplus( std::forward<X>(x), std::forward<Y>(y) ); }
First, we define these for sequences.
template<> struct MonadZero< sequence_tag > { /* An empty sequence. */ template< class S > S mzero() { return S{}; } }; /* mplus( xs, ys ) = "append xs with ys" */ template<> struct MonadPlus< sequence_tag > { template< class A, class B > static A mplus( A a, const B& b ) { std::copy( b.begin(), b.end(), std::back_inserter(a) ); return a; } };
And then for Parsers.
/* mzero: a parser that matches nothing, no matter the input. */ template< class X > struct MonadZero< Parser<X> > { template< class P > static P mzero() { return parser<X> ( []( const std::string& s ){ return std::vector<std::pair<X,std::string>>(); } ); } }; /* mplus( pa, pb ) = "append the results of pa with the results of pb" */ template< class X > struct MonadPlus< Parser<X> > { using P = Parser<X>; static P mplus( P a, P b ) { return parser<X> ( [=]( const std::string& s ) { return a(s) + b(s); } ); } };
Since we usually only want the first successful parse, the paper define an operator, +++, that does this.
template< class X > Parser<X> mplus_first( const Parser<X>& a, const Parser<X>& b ) { return parser<X> ( [=]( const std::string s ) { using V = std::vector< std::pair< X, std::string > >; V c = (a + b)( s ); return c.size() ? V{ c[0] } : V{}; } ); }
This completes the required building blocks. A parser of significant complexity could be made using only the above functions and types. The paper describes building a notably simple parser, so let's do that instead!
Basic Monadic Parsers.The simplest parser is item, which accepts any char.
std::string tail( const std::string& s ) { return std::string( std::next(s.begin()), s.end() ); } /* * Unconditionally match a char if the string is not empty. * Ex: item("abc") = {('a',"bc")} */ auto item = parser<char> ( []( const std::string& s ) { using Pair = Parser<char>::parse_state; using R = Parser<char>::result_type; return s.size() ? R{ Pair( s[0], tail(s) ) } : R(); } );
To demonstrate its usage, the paper defines a simple parser that takes a string of length three or more and returns the first and third values.
auto p = item >>= []( char c ) { return item >> item >>= [c]( char d ) { return mreturn<Parser>( std::make_pair(c,d) ); }; };
p first runs item to extract c, then runs item again but throws away the value. It runs item a third time to extract d and finally returns as its value (c,d). p("abcd") would return {(('a','c'),"d")}.
The next function creates a parser that is a little more helpful:
/* sat( pred ) = "item, if pred" */ template< class P > Parser<char> sat( P p ) { return item >>= [p]( char c ) { return p(c) ? mreturn<Parser>(c) : mzero<Parser<char>>(); }; }
Given some function that operates on chars, this extracts an item, but then checks the condition without consuming any additional input. If p(c) returns true, then it returns a parser with the value c, otherwise zero, a failed parse. Using this, we can define a parser to accept only a specific char.
Parser<char> pchar( char c ) { return sat( [=](char d){ return c == d; } ); }
And then, a parser that accepts only a specific string.
Parser<std::string> string( const std::string& s ) { if( s.size() == 0 ) return mreturn<Parser>( s ); Parser<char> p = pchar( s[0] ); for( auto it=std::next(s.begin()); it != s.end(); it++ ) p = p >> pchar( *it ); return p >> mreturn<Parser>(s); }
Note: There is no name conflict with std::string because the source does not contain "using namespace std;".
This function does something very odd. For every char in s, it chains together char parsers. For example, string("abc") would return a parser equivalent to pchar('a') >> pchar('b') >> pchar('c') >> mreturn<Parser>("abc"). If any of the char parsers fail down the line, mreturn<Parser>(s) will fail. Since we already know the values of the successful parses, their values are thrown away.
Though faithful to the paper, this may be less efficient than desirable. One could implement string in this way, too:
Parser<std::string> string( const std::string& str ) { return parser<std::string> ( [str]( const std::string& s ) { using R = typename Parser<std::string>::result_type; if( std::equal(str.begin(),str.end(),s.begin()) ) { return R { { str, s.substr( str.size() ) } }; } else { return R(); } } ); }
It can at times be simpler to write out these functions instead of composing them, however, that can be thought of as an optimization.
The next function creates a new parser from a parser, p, that accepts one or zero p's.
template< class X > Parser<std::vector<X>> some( Parser<X> p ) { using V = std::vector<X>; using Pair = std::pair<V,std::string>; using R = std::vector< Pair >; using P = Parser<V>; return mplus_first( parser<V> ( [=]( const std::string& s ) { auto matches = p(s); return matches.size() == 0 ? R{} : R{ Pair( V{std::move(matches[0].first)}, std::move( matches[0].second ) ) }; } ), mreturn<Parser>( V{} ) ); }
It was unfortunately difficult to translate, but does work. (The gist also contains a version called many, which accepts zero or many p's.) some converts a parser of type X to one that produces a vector or X's. It always succeeds, even if it does not successfully parse anything.
To create a parser that consumes whitespace is now trivial.
template< class X > using ManyParser = Parser< std::vector<X> >; ManyParser<char> space = some( sat([](char c){return std::isspace(c);}) );
We require one more function to parse alternating sequences. Like what? A sum, like "1+2+3" is a sort of alternating sequence of numbers and +'s. A product is an alternating sequence of numbers and *'s.
Here's the weird part: what does a parser that accepts a "+" return? What about a parser that accepts a "-"? The value of such a parser, as it turns out, is the binary function that it represents! In the case of the implementation below, this is a function pointer of type int(*)(int,int).
/* * chain(p,op): Parse with p infinitely (until there is no match) folding with op. * * p and op are both parsers, but op returns a binary function, given some * input, and p returns the inputs to that function. For example, if: * input: "4" * p returns: 4 * No operator is read, no operation is performed. But: * input: "4+4" * p returns: 4 * op is then parsed with the function, rest: * input: "+4" * op returns: do_add * input: "4" * p returns: 4 * rest returns: 8 * rest applies the operation parsed by op. It alternates between parsing p and * op until there are no more matches. */ constexpr struct Chainl1 { template< class X, class F > static Parser<X> rest( const Parser<X>& p, const Parser<F>& op, const X& a ) { // Alternate between op and p until input is consumed or a parse fails. auto r = op >>= [=]( const F& f ) { return p >>= [&]( const X& b ) { return rest( p, op, f(a,b) ); }; }; // Return the first successful parse, or a if none. return mplus_first( r, mreturn<Parser>(a) ); } template< class X, class F > Parser<X> operator () ( Parser<X> p, Parser<F> op ) const { return p >>= closet( rest<X,F>, std::move(p), std::move(op) ); } } chainl1{};
Adding the final touches.The paper describes a few generally useful functions for constructing parsers based off the above function. space (defined above) consumes whitespace. token consumes any trailing whitespace after parsing p.
constexpr struct Token { template< class X > Parser<X> operator () ( Parser<X> p ) const { return p >>= []( X x ) { return space >> mreturn<Parser>(std::move(x)); }; } } token{};
symb converts a string to a token.
auto symb = compose( token, string ); // symb(s) = token( string(s) )
apply consumes any leading whitespace.
constexpr struct Apply { template< class X > Parser<X> operator () ( Parser<X> p ) const { return space >> std::move(p); } } apply{};
The big idea is that we never want to manually write a function that returns a list of successful parses. It's hard! It's much easier to compose such functions from smaller, more comprehensible ones and use those to build reasonable complex, but more simple to reason about, parsers.
The parser itself.Now, using all of the tools provided, we can create a parser much more trivially than otherwise--though that is perhaps true of any time one has a new set of tools. First, we define a parser that accepts digits.
constexpr bool is_num( char c ) { return c >= '0' and c <= '9'; } /* Parse one digit. */ Parser<int> digit = token( sat(is_num) ) >>= []( char i ) { return mreturn<Parser>(i-'0'); };
Now, digit("2") returns 2, but (digit >> digit)("22") returns 2 as well! Why? Because the first run of digit extracts the first 2, but throws that value away and the second run of digit extracts the second 2. To parse a two-digit number, we need something like this:
Parser<int> twoDigit = digit >>= []( int x ) { return digit >>= [x]( int y ) { return mreturn<Parser>( x*10 + y ); }; };
It extracts the first then the second digit and returns the original number, converted from a string to an int! To parse arbitrarily long numbers (diverging from the paper's version), we can define a chain operation!
int consDigit( int accum, int digit ) { return accum*10 + digit; } Parser<int> num = chainl1( digit, mreturn<Parser>(consDigit) );
For every two digits parse, num calls consDigit to fold the values together. As mentioned earlier, chainl1 works by alternating between its two parsers. Since the second argument is a parser which consumes no input, num only accepts digits.
Next, we can define the parsers for binary operations.
// Binary operations of type int(*)(int,int). int do_add( int x, int y ) { return x + y; } int do_sub( int x, int y ) { return x - y; } int do_mult( int x, int y ) { return x * y; } int do_div( int x, int y ) { return x / y; } auto addop = mplus ( pchar('+') >> mreturn<Parser>(do_add), pchar('-') >> mreturn<Parser>(do_sub) ); auto mulop = mplus ( pchar('*') >> mreturn<Parser>(do_mult), pchar('/') >> mreturn<Parser>(do_div) );
addop parses either a "+" or "-" and returns either do_add or do_sub, respectively. Because the parsers must return functions of the same types, std::plus and std::minus could not be used.
With this, we can define a term as an alternating sequence of numbers and multiplications and divisions; and an expr(ession) as an alternating sequence of terms, +'s and -'s.
/* * Parse terms: series of numbers, multiplications and divisions. * Ex: "1*3*2" -> (3,"*2") -> 6 */ Parser<int> term = chainl1( num, mulop ); /* * Parse expressions: series of terms, additions and subtractions. * Ex: "1+7*9-1" -> (1."+7*9-1") -> (63,"-1") -> 62 */ Parser<int> expr = chainl1( term, addop );
And we're done! We have just built a calculator! It can evaluate any expression of additions, subtractions, multiplications, divisions, and it is whitespace agnostic. While implementing Parser itself took a considerable amount of work, using it does not.
int main() { using std::cin; using std::cout; using std::endl; cout << "Welcome to the calculator!\n" << "Press ctrl+d or ctrl+c to exit.\n" << "Type in an equation and press enter to solve it!\n" << endl; std::string input; while( cout << "Solve : " and std::getline(std::cin,input) ) { auto ans = apply(expr)(input); if( ans.size() and ans[0].second.size() == 0 ) cout << " = " << ans[0].first; else cout << "No answer."; cout << endl; } }
I highly encourage anyone reading this to attempt to compile and modify the source code.
See the gist at github for the source in full:
And for the original parser I wrote: | http://yapb-soc.blogspot.com/2012/11/monadic-parsing-in-c.html | CC-MAIN-2016-44 | refinedweb | 3,218 | 63.39 |
#include <SensSchurData.hpp>
Definition at line 18 of file SensSchurData.hpp.
This interface serves as a reference point for multiple classes that need to use SchurData (PCalculator, SchurDriver).
It declares as little as possible, so that SchurData implementations can be very special and fast.
I have not decided yet if there are certain ways I want to impose that SchurData can be set. I will figure this out as soon as I write the upstream classes that need to do that
Nomenclature in this program is based on Victor Zavalas thesis.
Definition at line 33 of file SensSchurData.hpp.
Definition at line 36 of file SensSchurData.hpp.
Functions to set the Schurdata.
At least one must be overloaded Set Data to one for given indices. Size of vector is ipopt_x_<full_x_
Implemented in Ipopt::IndexSchurData.
Set Data to corresponing Number.
Implemented in Ipopt::IndexSchurData.
Returns number of rows/columns in schur matrix.
Reimplemented in Ipopt::IndexSchurData.
Definition at line 57 of file SensSchurData.hpp.
Definition at line 62 of file SensSchurData.hpp.
Returns the i-th column vector of the matrix.
Implemented in Ipopt::IndexSchurData.
Returns two vectors that are needed for matrix-vector multiplication of B and P.
The index is the row, the first vector are the indices of non-zero components, in this row of B, the second vector gives the numbers in B(row,indices)
Implemented in Ipopt::IndexSchurData.
Computes B*v with B in R(mxn).
Implemented in Ipopt::IndexSchurData.
Computes A*u with A in R(nxm), KKT in R(n,n).
Implemented in Ipopt::IndexSchurData.
Definition at line 91 of file SensSchurData.hpp.
Definition at line 103 of file SensSchurData.hpp.
Definition at line 117 of file SensSchurData.hpp.
Definition at line 122 of file SensSchurData.hpp.
Makes sure that data is not set twice accidentially.
Definition at line 130 of file SensSchurData.hpp.
Number of columns/rows of corresponding Schur Matrix.
Definition at line 133 of file SensSchurData.hpp. | http://www.coin-or.org/Doxygen/Ipopt/class_ipopt_1_1_schur_data.html | crawl-003 | refinedweb | 327 | 53.68 |
2008-11-25 16:48:47 8 Comments
How do I setup a class that represents an interface? Is this just an abstract base class?
Related Questions
Sponsored Content
23 Answered Questions
[SOLVED] What is the "-->" operator in C++?
- 2009-10-29 06:57:45
- GManNickG
- 752020 View
- 8598 Score
- 23 Answer
- Tags: c++ operators code-formatting standards-compliance
29 Answered Questions
[SOLVED] How should I have explained the difference between an Interface and an Abstract class?
- 2013-09-13 03:50:40
- Thinker
- 425228 View
- 456 Score
- 29 Answer
- Tags: java oop inheritance interface abstract-class
26 Answered Questions
[SOLVED] Why is processing a sorted array faster than processing an unsorted array?
- 2012-06-27 13:51:36
- GManNickG
- 1427731 View
- 23681 Score
- 26 Answer
- Tags: java c++ performance optimization branch-prediction
37 Answered Questions
[SOLVED] What are the differences between a pointer variable and a reference variable in C++?
34 Answered Questions
[SOLVED] What is the difference between an interface and abstract class?
- 2009-12-16 08:15:15
- Sarfraz
- 1234324 View
- 1708 Score
- 34 Answer
- Tags: oop interface abstract-class
1 Answered Questions
[SOLVED] The Definitive C++ Book Guide and List
7 Answered Questions
[SOLVED] Difference between abstract class and interface in Python
- 2008-12-16 17:32:27
- gizmo
- 389674 View
- 531 Score
- 7 Answer
- Tags: python interface abstract-class
34 Answered Questions
[SOLVED] Interface vs Abstract Class (general OO)
- 2009-04-17 16:42:38
- Houman
- 689170 View
- 1375 Score
- 34 Answer
- Tags: oop interface abstract-class
10 Answered Questions
[SOLVED] Calling the base constructor in C#
- 2008-08-15 07:39:23
- lomaxx
- 980050 View
- 1402 Score
- 10 Answer
- Tags: c# inheritance constructor
@Joel Coehoorn 2008-11-25 17:01:06.
@Ha11owed 2012-08-01 06:05:30
It would still be nice to be able to create interfaces, to save us from typing so much (virtual , =0, virtual destructor). Also multiple inheritance seems like a really bad idea to me and I've never seen it used in practice, but interfaces are needed all the time. To bad the C++ comity won't introduce interfaces just because I want them.
@Miles Rout 2013-01-01 06:51:44
Ha11owed: It has interfaces. They're called classes with pure virtual methods and no method implementations.
@doc 2014-10-15 16:50:08
@Ha11owed There are some quirks in Java caused by lack of multiple inheritance. Take a look at
java.lang.Threadclass and
java.lang.Runnableinterface, which exists just because you can not extend
Threadalong with another base. From documentation it may seem that it's provided for your choice, but I was once forced to use
Runnablebecause of lack of multiple inheritance.
@Ha11owed 2014-11-28 15:04:28
@MilesRout: I know, but still, why force me write so much boilerplate code? Also it would be clear that you are looking at an interface without having to scan all methods and check that they are all pure virtual.
@Ha11owed 2014-11-28 15:05:53
@doc: java.lang.Thread has methods and constants that you probably don't want to have in your object. What should the compiler do if you extend from Thread, and another class with the public method checkAccess()? Would you really prefer to use strongly named base pointers like in C++? This seems like bad design, you usually need composition where you think that you need multiple inheritance.
@doc 2014-11-28 15:21:17
@Ha11owed it was long time ago so I don't remember details, but it had methods and contants that I wanted to have in my class and more importantly I wanted my derived class object to be a
Threadinstance. Multiple inheritance can be bad design as well as composition. It all depends on case.
@Joel Coehoorn 2014-11-30 03:49:05
@Ha11owed +1 for "you usually need composition where you think that you need multiple inheritance"
@Don Larynx 2015-03-24 04:19:04
There is no
abstractkeyword in C++.
@Dave 2015-12-16 05:53:48
"The whole reason you have a special Interface type-category in addition to abstract base classes in C#/Java is because C#/Java do not support multiple inheritance." - The assertion that this is the reason is completely false. Interfaces exist in Java so as not to conflate the concepts of conformation to a contract and shared implementation. This is a common misconception among C++ developers attempting to disparage what is arguably a design more consistent with pure OO languages.
@Dave 2015-12-16 05:55:57
Objective-C also supports this via Protocols and goes a step further (confusingly at first) by making Protocol method implementation optional. This has provided Objective-C with much of what C++ will soon get via Concepts.
@Deduplicator 2016-01-07 18:32:10
@Dave: Really? Objective-C has compile-time evaluation, and templates?
@Dave 2016-01-23 10:18:45
@Deduplicator - I'm referring to the key property of concepts being that they allow a callee (in your case a template) to specify constraints on the API that an argument must/should support where those constraints are expressed within the declaration or definition of the callee rather than within the class hierarchy of the argument. No Objective-C doesn't have templates. Templates in this discussion are the things being improved by a "concept" similar in some respects to Objective-C's protocols. But I'm sure you already knew that.
@fdsfdsfdsfds 2018-03-29 17:18:18
then give an example of what you call multiple inheritance, becos so far it seems java can do it but not c++, java can implment many interface
@Joel Coehoorn 2018-03-29 17:23:39
c++ can directly inherit from many classes. java can only directly inherit from one class.
@陳 力 2017-11-07 01:22:20
Here is the definition of
abstract classin c++ standard
n4687
13.4.2
@Dima 2008-11-25 17:27:01.
@OscarRyz 2008-11-25 17:32:33
More than "lack of multiple inheritance" I would say, to replace multiple inheritance. Java was designed like this from the beginning because multiple inheritance create more problems than what it solves. Good answer
@Dima 2008-11-25 17:40:31
Oscar, that depends on whether you are a C++ programmer who learned Java or vice versa. :) IMHO, if used judiciously, like almost anything in C++, multiple inheritance solves problems. An "interface" abstract base class is an example of a very judicious use of multiple inheritance.
@curiousguy 2012-08-16 03:24:52
@OscarRyz Wrong. MI only creates problem when misused. Most alleged problems with MI would also come up with alternate designs (without MI). When people have a problem with their design with MI, it's the fault of MI; if they have a design problem with SI, it's their own fault. "Diamond of death" (repeated inheritance) is a prime example. MI bashing is not pure hypocrisy, but close.
@Marek Stanley 2015-03-25 17:22:14
Semantically, interfaces are different from abstract classes, so Java's interfaces are not just a technical workaround. The choice between defining an interface or an abstract class is driven by semantics, not technical considerations. Let's imagine some interface "HasEngine": that's an aspect, a feature, and it can be applied to / implemented by very different types (whether classes or abstract classes), so we'll define an interface for that, not an abstract class.
@Dima 2015-03-25 17:28:48
@MarekStanley, you may be right, but I wish you'd picked a better example. I like to think of it in terms of inheriting an interface vs. inheriting an implementation. In C++ you can either inherit both interface and implementation together (public inheritance) or you can inherit only the implementation (private inheritance). In Java you have the option of inheriting just the interface, without an implementation.
@Justin Time 2 Reinstate Monica 2016-04-08 18:53:27
@curiousguy That sums it up pretty well. Generally speaking, it's more difficult to use multiple inheritance properly than it is to use single inheritance properly, but merely being more difficult doesn't mean it's impossible. An example would be something like this:
class Button; class Image; class ClickableIcon : public Button, public Image {};. If they're designed properly, Image will supply the graphics functionality and Button will supply the interactive functionality, with no overlap that could cause issues, while ClickableIcon itself handles the functionality the button is for.
@Justin Time 2 Reinstate Monica 2016-04-08 19:32:16
...I could've worded that example much better.
Buttonprovides the interactive code,
Imageprovides the graphics code, and
ClickableIconprovides code specific to itself, as well as any code needed to weld the two parent classes together. As long as the two classes are designed properly, and have no overlapping member names, the class should be entirely viable, and easier to implement than if one or both was an interface.
@Mark Ingram 2009-10-13 19:53:38
If you're using Microsoft's C++ compiler, then you could do the following:.
@Flexo 2011-09-17 13:09:57
I don't quite see why you used
novtableover standard
virtual void Bar() = 0;
@Mark Ingram 2011-09-20 14:44:43
It's in addition to (I've just noticed the missing
= 0;which I've added). Read the documentation if you don't understand it.
@Flexo 2011-09-20 14:47:33
I read it without the
= 0;and assumed it was just a non-standard way of doing exactly the same.
@bradtgmurray 2008-11-25 16:53:31
Make a class with pure virtual methods. Use the interface by creating another class that overrides those virtual methods.
A pure virtual method is a class method that is defined as virtual and assigned to 0.
@Evan Teran 2008-11-26 08:33:13
you should have a do nothing destructor in IDemo so that it is defined behavior to do: IDemo *p = new Child; /*whatever */ delete p;
@Cemre 2012-01-31 22:26:06
Why is the OverrideMe method in Child class is virtual ? Is that necessary ?
@PowerApp101 2012-02-12 11:15:18
@Cemre - no it's not necessary, but it doesn't hurt either.
@Kevin 2014-10-03 20:47:24
It is generally a good idea to keep the keyword 'virtual' whenever overriding a virtual method. Though not required, it can make the code clearer - otherwise, you have no indication that that method could be used polymorphically, or even exists in the base class.
@keyser 2014-11-26 21:34:18
@Kevin Except with
overridein C++11
@Phylliida 2015-10-14 16:40:38
Don't forget the semicolons at the end of the class declarations.
@Justin Time 2 Reinstate Monica 2019-07-28 16:41:44
It's not necessary to declare
Child::OverrideMe()as
virtual, @Cemre, because
IDemo::OverrideMe()makes
Child::OverrideMe()implicitly
virtual. Having an indication that it's a virtual function (such as
virtual, or better yet,
overridein C++11 or later) will serve as a reminder for programmers, with
overridein particular also helping the compiler check that it does indeed override something.
@lorro 2016-07-26 15:29:25
While it's true that
virtualis the de-facto standard to define an interface, let's not forget about the classic C-like pattern, which comes with a constructor in C++:
This has the advantage that you can re-bind events runtime without having to construct your class again (as C++ does not have a syntax for changing polymorphic types, this is a workaround for chameleon classes).
Tips:
clickin your descendant's constructor.
protectedmember and have a
publicreference and/or getter.
ifs vs. state changes in your code, this might be faster than
switch()es or
ifs (turnaround is expected around 3-4
ifs, but always measure first.).
@Yeo 2015-09-27 18:27:29
I'm still new in C++ development. I started with Visual Studio (VS).
Yet, no one seems to mentioned the
__interfacein VS (.NET). I am not very sure if this is a good way to declare an interface. But it seems to provide an additional enforcement (mentioned in the documents). Such that you don't have to explicitly specify the
virtual TYPE Method() = 0;, since it will be automatically converted.
If anyone do have anything interesting about it, please share. :-)
Thanks.
@Mark Ransom 2008-11-25 17:11:33.
You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.
@xan 2008-11-25 17:52:38
Virtual desctuctor++! This is very important. You may also want to include pure virtual declarations of the operator= and copy constructor definitions to prevent the compiler auto-generating those for you.
@Fred Larson 2008-11-25 19:06:00
An alternative to a virtual destructor is a protected destructor. This disables polymorphic destruction, which may be more appropriate in some circumstances. Look for "Guideline #4" in gotw.ca/publications/mill18.htm.
@bradtgmurray 2009-07-17 14:28:52
If you know you're not going to delete the class through a base class, you don't need the virtual destructor. However, it's never really harmful to make the destructor virtual anyway (except for one vtable lookup, oh no!).
@Pavel Minaev 2009-12-31 09:04:51
One other option is to define a pure virtual (
=0) destructor with a body. The advantage here is that the compiler can, theoretically, see that vtable has no valid members now, and discard it altogether. With a virtual destructor with a body, said destructor can be called (virtually) e.g. in the middle of construction via
thispointer (when constructed object is still of
Parenttype), and therefore the compiler has to provide a valid vtable. So if you don't explicitly call virtual destructors via
thisduring construction :) you can save on code size.
@Lumi 2012-03-10 21:40:33
Forty moons ago, but anyway - @Mark Ransom, you wrote: "This allows you to pass pointer ownership to another party without exposing the base class." Did you mean "sub class"? Because then in your comment you wrote: "If you know you're not going to delete the class through a base class, you don't need the virtual destructor." - Sorry if my remark doesn't make sense - I'm a C++ noob and trying to learn from these questions and answers.
@Mark Ransom 2012-03-10 22:42:04
@Lumi, now that I think about it you're absolutely correct. The interface is a base class because the concrete class derives from it and implements the methods. I should fix this. Give yourself a gold star for being the first to notice, I'm sure this answer has been viewed a thousand times.
@Lumi 2012-03-10 22:49:17
@MarkRansom, thanks for the virtual gold star. :) Meanwhile, I figured out you must have meant what I surmised you had meant because I got to the bottom of the page where Carlos' answer makes the point clear with a code sample. Thanks for your feedback after such a long time! -- Best, Michael
@curiousguy 2012-08-16 03:26:55
@PavelMinaev "With a virtual destructor with a body, said destructor can be called (virtually) e.g. in the middle of construction" seriously?
@Mark Ransom 2012-08-16 03:31:36
@curiousguy, yes you can call a destructor in the middle of construction when you
throwfrom the constructor of a derived class.
@curiousguy 2012-08-16 03:49:19
But virtually?!!
@Pavel Minaev 2012-08-16 18:24:12
Consider an inheritance hierarchy:
Base<-
Derived<-
MostDerived. You are in Derived ctor. You call a global function that takes a
Base*argument, passing it
this. That function can explicitly invoke the destructor via the pointer, and it has to be dispatched virtually.
@Mark Ransom 2012-08-16 19:18:33
@PavelMinaev, wouldn't it be UB to destroy an object explicitly before it's finished constructing? I can see the
MostDerivedconstructor getting very unhappy. At least with destroying via
throwthe remainder of the construction is bypassed.
@Pavel Minaev 2012-08-17 00:01:37
It would certainly be UB by the time it gets to the ctor of
MostDerived, but I don't see anything that would make e.g.
this->~Foo()in a ctor UB all by itself. Consider the case where you destruct it, and then never return to the ctor (e.g. just sit there in an infinite loop, taking and processing input). Inside that loop, your behavior would be well-defined, so far as I can see.
@Tim 2012-08-24 22:49:02
How typical of a C++ answer that the top answer doesn't directly answer the question (though obviously the code is perfect), instead it optimizes the simple answer.
@Sean 2013-01-15 03:19:07
Don't forget that in C++11 you can specify the
overridekeyword to allow for compile-time argument and return value type checking. For example, in the declaration of Child
virtual void OverrideMe() override;
@Mark Ransom 2013-01-15 03:42:13
@Sean, this answer predates C++11 by a few years, but you make a good point - thanks!
@Maxim Egorushkin 2013-01-16 07:29:34
I agree with @PavelMinaev, there is little if any reason for the destructor to be non-pure virtual.
@Chris 2013-05-22 04:29:20
Also note that GCC cannot handle pure-virtual destructors and you need to define them: stackoverflow.com/a/3065223/447490
@Griddo 2014-03-12 08:43:52
@Chris I'm a little bit confused now regarding Mark Ransoms note on compiler optimization and your comment. Sounds like the former suggests using pure virtual destructors while the latter forbids it. Did I misunderstand something? If not, is there a general solution for this or is it compiler dependent?
@Chris 2014-03-12 09:57:33
@Griddo No, you understand quite right. Mark Ransom suggests not defining the virtual destructor while GCC requires you to do so. I don't really think there is a general solution for this other than clutter your code with #ifdef and compiler checks but in this case I'd rather just go with defining it and maybe lose some optimization benefits on some compilers.
@Zachary Kraus 2014-12-09 22:49:19
@xan Can you please explain the reasoning behind wanting to make the assignment operator and copy constructor pure virtual in the IDemo class.
@Mark Ransom 2014-12-10 00:01:48
@ZacharyKraus an interface should be a very small subset of the class that actually implements the interface; in particular it won't have any data members. That almost guarantees that the compiler-generated copy and assignment operators will do the wrong thing. If you want to implement them yourself then knock yourself out, but it's usually not necessary - you access an interface via a pointer, and copies of the pointer are OK as long as you've handled ownership.
@xan 2014-12-10 16:57:14
@ZacharyKraus: What MarkRansom said. If you are declaring an interface in this way, it's highly unlikely that the compiler's auto-generated attempts at these would be correct. Thus, it's safer to explicitly declare them pure virtual yourself and make sure that you can't accidental fall into the trap of using them.
@Zachary Kraus 2014-12-17 00:28:06
@MarkRansom I now understand the reasoning but I still have 2 questions that I just don't understand. The first is does the compiler automatically create the assignment and copy constructor for ever class even if you never use them in your code. Second, can you accidentally trigger either assignment or copy constructor when the object is a pointer?
@Mark Ransom 2014-12-17 02:23:48
@ZacharyKraus their presence or absence isn't detectable unless you call them, so by the "as-if" rule it could go either way - I suspect most compilers don't. You can generate a call with e.g.
*a = *bbut I grant you it's not common.
@Deduplicator 2016-01-07 19:28:37
Also, it simply daoesn't actually matter, as assinging / copying the interface doesn't do anything.
@Sparker0i 2018-08-10 18:57:17
Inside
Child, is it still necessary to write
OverrideMe()as
virtual void?
@Mark Ransom 2018-08-10 20:18:27
@Sparker0i
virtualis not necessary since the base class declaration already made it virtual, but it's good practice to be consistent.
voidis still necessary.
@L. F. 2019-06-15 13:15:14
It would be nice if you mention that the destructor can be made pure virtual if no other function is available.
@Glinka 2019-06-26 14:40:45
What one should do with the warning that IDemo "has no out-of-line virtual method definitions"?
@gnzlbg 2013-06-25 13:51:08
In C++11 you can easily avoid inheritance altogether:
In this case, an Interface has reference semantics, i.e. you have to make sure that the object outlives the interface (it is also possible to make interfaces with value semantics).
These type of interfaces have their pros and cons:interface:
In your application, you do the same with different shapes using the
YourShapeinterface:
Now say you want to use some of the shapes that I've developed in your application. Conceptually, our shapes have the same interface, but to make my shapes work in your application you would need to extend my shapes as follows:
First, modifying my shapes might not be possible at all. Furthermore, multiple inheritance leads the road to spaghetti code (imagine a third project comes in that is using the
TheirShapeinterface... what happens if they also call their draw function
my_draw?).
Update: There are a couple of new references about non-inheritance based polymorphism:
@doc 2014-10-15 17:28:08
TBH inheritance is far more clear than that C++11 thing, which pretends to be an interface, but is rather a glue to bind some inconsistent designs. Shapes example is detached from reality and
Circleclass is a poor design. You should use
Adapterpattern in such cases. Sorry if it will sound a little bit harsh, but try to use some real life library like
Qtbefore making judgements about inheritance. Inheritance makes life much easier.
@gnzlbg 2014-10-15 17:42:58
It doesn't sound harsh at all. How is the shape example detached from reality? Could you give an example (maybe on ideone) of fixing Circle using the
Adapterpattern? I'm interested to see its advantages.
@doc 2014-10-15 18:18:51
O.K. I will try to fit in this tiny box. First of all, you usually choose libraries like "MyShape" before you start writing your own application, to safe your work. Otherwise how could you know
Squareisn't already there? Foreknowledge? That's why it is detached from reality. And in reality if you choose to rely on "MyShape" library you can adopt to its interface from the very beginning. In shapes example there are many nonsenses (one of which is that you have two
Circlestructs), but adapter would look something like that -> ideone.com/UogjWk
@doc 2014-10-15 20:22:51
As I mentioned Qt. Check this example -> qt-project.org/doc/qt-5/qtwidgets-widgets-scribble-example.html to see how robust inheritance altogether with virtual methods is. And with banned inheritance and that C++11 "interface" thing instead, am I supposed to implement every time ALL virtual methods that QWidget has? Would I need to delegate each call to check for example my custom widget position? On the other hand Qt must had become header only library, because of "interface" thing required to invoke my implementations.
@gnzlbg 2014-10-15 21:56:32
It is not detached from reality then. When company A buys company B and wants to integrate company B's codebase into A's, you have two completely independent code bases. Imagine each has a Shape hierarchy of different types. You cannot combine them easily with inheritance, and add company C and you have a huge mess. I think you should watch this talk: youtube.com/watch?v=0I0FD3N5cgM My answer is older, but you'll see the similarities. You don't have to reimplement everything all the time,you can provide an implementation in the interface, and choose a member function if available.
@gnzlbg 2014-10-15 22:16:29
There are also a couple of talks by Sean Parent about concept-based polymorphism that might be interesting to you.
@doc 2014-10-16 01:51:33
Mentioned Qt was owned by 3 companies (Trolltech, Nokia, Digia) but none of them did the thing you say. It is detached from reality. Give me an example of real world software where such code merging took place. Even if so you should use
Adapterpattern. Providing implementation in interface like one in your answer means that I have to provide all virtual methods, which otherwise could be simply inherited.
@doc 2014-10-16 02:19:54
I've watched part of video and this is totally wrong. I never use dynamic_cast except for debugging purposes. Dynamic cast means theres something wrong with your design and designs in this video are wrong by design :). Guy even mentions Qt, but even here he is wrong - QLayout does not inherit from QWidget nor the other way around!
@gnzlbg 2014-10-16 09:15:50
I've updated the answer with reference in case you are interested into learning more about this. Those three companies you mention were all working using the same library. Inheritance becomes a huge problem when this is not the case. Examples of companies are shown in the Sean Parent talk about concept-based polymorphism.The links provided have more information than I can provide here.
@doc 2014-10-16 16:21:03
I've watched video on concept-based polymorphism. While the technique is interesting and may find some applications this can't replace inheritance based polymorphism (and this concept-based polymorphism still uses inheritance only hidden in private model structs). Polymorphism is not only for your internals, but also to provide a way application can interact with a library. Photoshop is not a library so it wasn't even considered in the video. I can't see any practical features in conecpt-based polymorphism that couldn't be achieved with IMO much cleaner inheritance.
@gnzlbg 2014-10-16 19:06:00
I agree that inheritance based polymorphism is very easy to use in C++ (this feature has full language support). In C for example it is very hard to do it. In Haskell, Rust, Scala.. you have traits and typeclasses which are kind of like language support for non-inheritance based polymorphism. I've used it in an app and was pretty happy with it. Mostly due to the performance boost it gave me (I can have vectors of each type, and a vector of interfaces, so I only use polymorphism where i really need it). We'll see how this evolves in C++, people have started talking about it fairly recently...
@doc 2014-10-17 02:58:52
Right. The problem is I can't see why inheritance is "the root of all evil". Such statement is ridiculous.
@gnzlbg 2014-10-18 08:39:33
Well the statement is more like "inheritance-based polymorphism is the root of all evil". After thinking a bit more about the solution you provided using the Adaptor pattern, the advantage I see about using a type-erased interface instead (like the one sean parent uses) is that your interface is in a single place, and you can extend its behavior and provide defaults via non-member non-friend functions. The interface is, however, way more complex to implement. The extension mechanism... its ADL vs not-ADL. If you go for ADL you are basically "stealing" function names from your users namespaces.
@doc 2014-10-18 15:06:31
And that's IMO bad, because you want to divide complex software into small logical pieces and inheritance helps you accomplish it. Having all kinds of objects (models in this specific case) degenerated to a single class is not convincing to me. How am I supposed to extend such concept-based interface if I don't have access to
object_tinternals nor I can't inherit after it? From what I see, I have to implement
draw()function from scratch on my own and I am not binded to
concept_tinterface. Also, with virtual methods I can have default implementations, which I can override or not.
@doc 2014-10-18 15:59:55
Term "interface" comes from Java world. What Java doc has to say: ." (docs.oracle.com/javase/tutorial/java/concepts/interface.html) Thing you are presenting is like world upside down.
@gnzlbg 2014-10-18 16:37:40
Exactly, and I think that it is the correct thing to do: "write your class first, make it model an interface later". It completely decouples your class implementation from modeling a given interface, and allows you to use your class in context you couldn't had thought of at the moment of writing it. C++ concepts, haskell typeclasses, rust/scala traits, and the Adaptor pattern you showed work this way. This same reasoning is behind the NVI idiom, but these other solutions decouple the design even more, since a class is not an interface anymore (in the "is a" sense of inheritance).
@doc 2014-10-18 16:58:02
This is a road to pure mess. Adapter pattern exists to bind incompatible interfaces, if necessary, but interfaces which already exist. I don't know why even use classes with approach "write your class first". This asks to come back to pure C. On what premise are you building your class if you don't know how it will interact with outer world? Say you used your own implementation of
gnzlbg::vectorin your class and I provide interface with my custom
doc::vectorand you have to convert input and output to your internals. Where's our code re-use and efficiency if you need to convert them?
@gnzlbg 2014-10-19 09:38:57
Note first, that an interface can wrap a type either by value, unique reference, or shared reference. Second, this problem with vector already exist since allocator is in the std::vector type. The solution is either to convert (which involves copy: expensive), or provide an iterator interface instead using e.g. Boost.Iterator.any_iterator (which uses the type-erasure described here, and is slow). Why do you say it asks to come back to pure C? The interfaces are type-safe, and can be very thin. I build my classes knowing that my knowledge about my problem (and my needs) will change with time.
@gnzlbg 2014-10-19 09:46:46
What would be the inheritance based solution if you cannot modify my code? The best I can come up with is: have a pure virtual base class vector, make yours inherit from it (always pay vtable), make your vectors function virtual (always pay this price), and use Adaptor pattern for my vector. The alternative would be, create a vector interface that adapts your vector and my vector. And use the interface when you need to polymorphically access your vector and my vector, but only in those places. And here when I say interface I mean mine, or one based on the adaptor pattern.
@gnzlbg 2014-10-19 10:06:08
Let us continue this discussion in chat.
@doc 2014-10-19 14:14:01
Wrapping type will not prevent you from reimplementing same functionality and doing very expensive conversion between vector types. Problem with vector does not exist if we both use either
doc::vectoror
gnzlbg::vectoron interface premise. You should learn how to properly use inheritance, because what you are saying now, does not make any sense!
@hims 2013-12-19 15:45:41
Result: Rectangle area: 35 Triangle area: 17
We have seen how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.
@guitarflow 2014-03-26 10:55:26
This is not what is considered an interface! That's just an abstract base class with one method that needs to be overridden! Interfaces are typically objects that contain only method definitions - a "contract" other classes have to fulfill when they implement the interface.
@Carlos C Soto 2012-03-05 17:53:12
As far I could test, it is very important to add the virtual destructor. I'm using objects created with
newand destroyed with
delete.
If you do not add the virtual destructor in the interface, then the destructor of the inherited class is not called.
If you run the previous code without
virtual ~IBase() {};, you will see that the destructor
Tester::~Tester()is never called.
@Lumi 2012-03-10 22:43:39
Best answer on this page as it makes the point by supplying a practical, compilable example. Cheers!
@Alessandro L. 2013-01-17 14:01:03
Testet::~Tester() runs only when the obj is "Declared with Tester".
@Chris Reid 2017-05-26 07:46:57
Actually, the string privatename's destructor will be called, and in memory, that is all there will be allocated for. As far as the runtime is concerned, when all the concrete members of a class are destroyed, so is the class instance. I tried a similar experiment with a Line class that had two Point structs and found both the structs were destructed (Ha!) upon a delete call or return from the encompassing function. valgrind confirmed 0 leak.
@Rexxar 2008-11-25 18:48:00:
Use the interface by creating another class that overrides those virtual methods.
Or
And
@Robocide 2011-07-03 07:22:00
there is no need for virtual inheritance as you do not have any data members in an interface.
@Knarf Navillus 2012-08-01 00:22:57
Virtual inheritance is important for methods as well. Without it, you will run into ambiguities with OverrideMe(), even if one of the 'instances' of it is pure virtual (just tried this myself).
@curiousguy 2012-08-16 03:25:24
@Avishay_ "there is no need for virtual inheritance as you do not have any data members in an interface." Wrong.
@mMontu 2012-09-19 17:55:50
Notice that virtual inheritance may not work on some gcc versions, as version 4.3.3 which is shipped with WinAVR 2010: gcc.gnu.org/bugzilla/show_bug.cgi?id=35067
@Wolf 2014-03-14 11:06:41
-1 for having a non-virtual protected destructor, sorry
@Luc Hermitte 2008-11-25 17:49:00
You can also consider contract classes implemented with the NVI (Non Virtual Interface Pattern). For instance:
@user2067021 2011-11-01 00:39:13
For other readers, this Dr Dobbs article "Conversations: Virtually Yours" by Jim Hyslop and Herb Sutter elaborates a bit more on why one might want to use the NVI.
@user2067021 2011-11-01 01:15:11
And also this article "Virtuality" by Herb Sutter.
@Rodyland 2008-11-25 22:02:19
All good answers above. One extra thing you should keep in mind - you can also have a pure virtual destructor. The only difference is that you still need to implement it.
Confused?.
@Johann Gerell 2008-11-26 07:57:32
Why, oh why, would anyone want to make the dtor in this case pure virtual? What would be the gain of that? You'd just force something onto the derived classes that they likely have no need to include - a dtor.
@Rodyland 2008-12-02 20:27:42
Updated my answer to answer your question. Pure virtual destructor is a valid way to achieve (the only way to achieve?) an interface class where all methods have default implementations.
@Uri 2008-11-25 17:35:34
A little addition to what's written up there:
First, make sure your destructor is also pure virtual
Second, you may want to inherit virtually (rather than normally) when you do implement, just for good measures.
@Tim 2008-11-25 18:51:54
Why inherit virtually?
@Uri 2008-11-25 19:09:51
I like virtual inheritance because conceptually it means that there is only one instance of the inherited class. Admittedly, the class here does not have any space requirement so it may be superfluous. I haven't done MI in C++ for a while, but wouldn't nonvirtual inheritance complicate upcasting?
@Johann Gerell 2008-11-26 07:55:38
Why, oh why, would anyone want to make the dtor in this case pure virtual? What would be the gain of that? You'd just force something onto the derived classes that they likely have no need to include - a dtor.
@Uri 2008-11-26 09:14:50
If there is a situation that an object would be destroyed through a pointer to the interface, you should make sure that the destructor is virtual...
@Rodyland 2008-12-05 03:24:31
There is nothing wrong with a pure virtual destructor. It's not necessary, but there's nothing wrong with it. Implementing a destructor in a derived class is hardly a huge burden on the implementor of that class. See my answer below for why you'd do this.
@doc 2014-10-17 12:33:51
+1 for virtual inheritance, because with interfaces it is more likely that class will derive interface from two or more paths. I opt for protected destructors in interfaces tho.
@Justin Time 2 Reinstate Monica 2016-04-08 20:14:51
@JohannGerell I believe the intention behind pure virtual destructors is to prevent a vtable from being generated unless a class that inherits from your interface class is itself inherited from. If this is the intention, though, the destructor should be both declared pure virtual and defined, as so:
class Base { public: ~Base() = 0; }; Base::~Base() {}, to allow the compiler to generate default constructors for derived classes | https://tutel.me/c/programming/questions/318064/how+do+you+declare+an+interface+in+c | CC-MAIN-2019-51 | refinedweb | 6,386 | 62.48 |
HackerRank is a site where you can supercharge your Python programming skills, master data structures and algorithms, and stand out to prospective employers by solving challenges alongside programmers from all around the world. It is also used by recruiters to evaluate prospective employees’ abilities.
If you are learning Python, which is the main focus of this blog, you will find a huge amount of material to help you develop your skills. However Python is by no means the only language available. For example you can use HackerRank to practice
- C, C++, Java, C#, Python, PHP, Ruby, Go, and Swift
- databases/SQL
- machine learning
- regex
- rest APIs
and more.
There is a something of a Marmite thing going on around whether people love or hate HackerRank. (If you don’t live in the UK you might not get that reference – Marmite is a salty yeast extract which some people find delicious but which turns others’ stomachs.)
Here’s some of the reason people love or hate HackerRank:
Reasons people love HackerRank
- It gives objective feedback about your skill level at solving a particular types of problem
- It gives an opportunity to develop your skill in several areas of programming
- Community and discussion of different approaches and insights into the problems
- Structured learning with progressively harder challenges
- Develop you problem solving skills
- Sets of challenges are available for focusing specific skills
Reasons people hate HackerRank
- The challenges can be hard to solve
- The descriptions are sometimes unclear or overcomplicated
- The types of challenges may well not reflect the kinds tasks you will be doing in a development job
- The UI can be confusing
- Best practices are often not used e.g. naming of function arguments
The rest of this article is for people who want to give HackerRank a try. In it I will help to demystify the site and help you to get started with solving the challenges.
How to Solve a Python HackerRank Challenge
Let’s take a look at a challenge from the Interview Preparation Kit Warm-up Challenges: Repeated String. A big part of solving theses challenges is being able to decipher what you are supposed to do based on the problem description. This is by no means always easy, and you will probably need to complete a few challenges to get to the point where the problem descriptions don’t make your brain hurt. Here’s a screen grab of the Repeated String Challenge. Don’t be disheartened if it looks confusing – I will explain it next.
OK, that might look like gobbledegook, so allow me to simplify things for you. The idea is that, given a string, like
abc, you need to work out how many times the letter
a would appear in the string if it were repeated until it were of the given length.
Confused?
Say you have the string
abc, and the length given is
10. The full string would become
abcabcabca, (repeating
abc until we have
10 characters), and the number of
as in the resulting string is
4.
One thing to note is that the initial template provide by HackerRank may contain some very confusing code along with the blank function definition. What you should understand is that this code is needed by the platform to test your code. You don’t actually need to understand how it works, but instead should simply focus on competing the function definition. By which I mean, ignore this bit:
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() n = int(input()) result = repeatedString(s, n) fptr.write(str(result) + '\n') fptr.close()
How Tests Work in HackerRank Challenges
A fundamental concept you need to understand when attempting HackerRank challenges is tests. When you submit your code it will be run with number of different inputs and the results compared with expected (correct) results. You code will need to pass all the test in order for you to successfully complete the challenge.
Sometimes your code will pass some of the tests but not all of them. You then have the option of “purchasing” access to the failed tests using “Hakos” – these are virtual credits earned by solving challenges.
You can run the code with your own input using the form shown below.
One useful tip is when you think you have a working solution, to paste in the sample input given in the problem description to see if your solution gives the expected result. This will give you an initial indication of whether your code is “in the right ball park”.
You may get a error message, which is helpful in debugging you code, and you can also use
Initial Attempt at HackerRank Repeated String challenge – Memory Issue
Spoiler alert: Try the problem for yourself before reading on to get the most learning from this article.
If you are very new to programming, you might need to spend a bit of time elsewhere getting past beginner level. One thing that makes the challenges on HackerRank well, challenging, is that it is often not enough to simply write a correct solution. In addition there may well be constraints in terms of speed of execution and memory requirements. This is where your knowledge of algorithmic efficiency comes in, or if you don’t have that knowledge, where you get the opportunity to dive into that fascinating topic.
Here is my initial attempt at solving the HackerRank Repeated String challenge.
def repeatedString(s, n): long_string = s * (n // len(s)) num_extra_chars = n - len(long_string) long_string += s[:num_extra_chars] return long_string.count("a")
Note:
s[:num_extra_chars] means “slice the string from the beginning to the position of
num_extra_chars.
Can you see what my thinking was? I created the full version of the repeated string in hopes of then counting the number of
as. Unfortunately, some of the tests involved a very large value for
n which meant that there was insufficient memory available. I had to rethink my approach.
Repeated String Warm-up Challenge
Here is my working solution to the Repeated String Warm-up HackerRank Challenge in Python
def repeatedString(s, n): repeating_section_length = len(s) full_repetitions = n // repeating_section_length partial_result = s.count("a") * full_repetitions num_extra_chars = s[: n % repeating_section_length].count("a") return partial_result + num_extra_chars
The key here was to avoid actually creating the full string of length
n, but instead to use powerful modulo operator (
%) to perform the calculation instead.
In this article we have explored what HackerRank is and how to approach the programming challenges available there. I hope you have found it helpful. Please feel free to comment below and share your experience with HackerRank.
Happy computing! | https://compucademy.net/introduction-to-hackerrank-for-python-programmers/ | CC-MAIN-2022-27 | refinedweb | 1,099 | 58.72 |
I recently wrote: > So, it looks like: > > fixIO m = let x = unsafePerformIO (m x) in return x > > will do a better job. But of course, I forgot to make my point before sending the message! The non-strict version is not good either, because it won't do the effects! Consider the definition: fixIO m = let x = unsafePerformIO (m x) in return x and the expression: do { fixIO (\x -> do {putStr "hello"; return (x+1)}); return 2 } We want this to first print hello and then return 2. The non-strict version will return the 2, but will not print the "hello". And the strict version will print the "hello" but won't return the 2. We want both. Hence neither definition is sufficient. -Levent. | http://www.haskell.org/pipermail/haskell/2001-February/006726.html | CC-MAIN-2014-15 | refinedweb | 125 | 73.17 |
Initialization¶
In the Neural Networks section we played fast and loose with setting up our networks. In particular we did the following things that shouldn’t work:
We defined the network architecture with no regard to the input dimensionality.
We added layers without regard to the output dimension of the previous layer.
We even ‘initialized’ these parameters without knowing how many parameters we were going to initialize.
All of those things sound impossible and indeed, they are. After all, there. The ability to determine parameter dimensionality during run-time rather than at coding time greatly simplifies the process of doing deep learning.
Instantiating a Network¶
Let’s see what happens when we instantiate a network. We start by defining a multi-layer perceptron.
[ ]:
from mxnet import init, nd from mxnet.gluon import nn def getnet(): net = nn.Sequential() net.add(nn.Dense(256, activation='relu')) net.add(nn.Dense(10)) return net net = getnet()
At this point the network doesn’t really know yet what the dimensionalities of the various parameters should be. All one could tell at this point is that each layer needs weights and bias, albeit of unspecified dimensionality. If we try accessing the parameters, that’s exactly what happens.
[ ]:
print(net.collect_params()) resolve all the dimensions as they become available. Once this is known, we can proceed by initializing parameters. This is the solution to the three problems outlined above..
Forced Initialization¶
Deferred initialization does not occur if the system knows the shape of all parameters when calling the
initialize function. This can occur in two cases:
We’ve already seen some data and we just want to reset the parameters.
We specified all input and output dimensions of the network or layer when defining it.
The first case works just fine, as illustrated below.
[ ]:
net.initialize(init=MyInit(), force_reinit=True). | https://mxnet.apache.org/versions/1.6/api/python/docs/tutorials/packages/gluon/blocks/init.html | CC-MAIN-2020-34 | refinedweb | 305 | 50.02 |
0
Hello. This is my first time programming in any language so please excuse my ignorance. I am trying write a program that asks the user to enter any number 3 times . I have assigned a function that takes the number and outputs an answer . After the 3rd number has been entered , the user is asked to guess what function was used to achieve that answer. The user is given 3 attempts to guess this answer , at which time I wan to move on to the next question. I am having trouble with the counter aspect of this program. Thanks for any assistance.
import javax.swing.*; public class GuessingGameRevised { public static void main (String [] arguments) { String guess1, guess2, guess3, selection; String function1 = "2x + 5"; double answer1,answer2,answer3, userselection; int counter = 1 ; guess1 = JOptionPane.showInputDialog(null, " Please select a number " ); guess2 = JOptionPane.showInputDialog(null, " Please select a second number " ); guess3 = JOptionPane.showInputDialog(null, " Please select a third number " ); answer1 = Double.parseDouble(guess1); answer2 = Double.parseDouble(guess2); answer3 = Double.parseDouble(guess3); selection = JOptionPane.showInputDialog(null, " You chose " + answer1 + "\nand when inserted into the function equals :\n" + function(answer1) + " \n\nYou chose " + answer2 + "\nand when inserted into the function equals:\n" + function(answer2)+ " \n\nYou chose " + answer3 + "\nand when inserted into the function equals:\n" + function(answer3) + "\n\nNow, can you determine what the function is?"); while(!function1.equals(selection)) { JOptionPane.showInputDialog(null, selection + " is not the correct function.\n\nSorry please try again"); counter++; System.exit(0); } JOptionPane.showMessageDialog(null, "Wow your smarter than Dr. Nii!"); System.exit(0); } public static double function(double f) { double func; func = (2*f) + 5; return func; } }
Edited 3 Years Ago by Dani: Formatting fixed | https://www.daniweb.com/programming/software-development/threads/113242/while-loop | CC-MAIN-2016-50 | refinedweb | 280 | 50.23 |
On Tue, Apr 25, 2006 at 07:27:21AM +0200, Heiko Carstens wrote:> > > @@ -485(). Also> rcu_batch_in_work() would be a more descriptive name for rcu_pending() as far> as I can tell.> Actually I was hoping for a better solution from the rcu experts, since I> don't like this too, but couldn't find something better.OK, got a look at your patch.You are using this internally, as part of the RCU -implementation-.You are determining whether this CPU will still be needed by RCU,or whether it can be turned off. So how 'bout calling the (internal)API something like rcu_needs_cpu()?int rcu_needs_cpu(int cpu){ struct rcu_data *rdp = &per_cpu(rcu_data, cpu); struct rcu_data *rdp_bh = &per_cpu(rcu_bh_data, cpu); return (!!rdp->curlist || !!rdp_bh->curlist || rcu_pending(cpu));}Then you can drop the rcu_pending() check from your 390 patch.Seem reasonable?The meaning of rcu_pending() is "Does RCU have some work pending onthis CPU, so that there is a need to invoke rcu_check_callbacks() onthis CPU?" Thanx, Paul-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2006/4/25/128 | CC-MAIN-2016-44 | refinedweb | 192 | 65.73 |
26 June 2012 10:11 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The company’s net revenue in the first quarter fell 74% year on year to $200m, and saw a first-quarter gross loss of $131m, it said in a statement.
“Industry-wide overcapacity continued and drove price declines across the entire solar supply chain, which significantly reduced our revenue and negatively impacted our margins,” said Xiaofeng Peng, Chairman and CEO of LDK Solar.
LDK Solar estimates its revenue to range from $220m to $270m for the second quarter of fiscal 2012, the statement added.
“While we expect to see continued challenging conditions in the solar industry in the near-term, we anticipate that some markets such | http://www.icis.com/Articles/2012/06/26/9572540/chinas-ldk-solar-swings-to-185m-q1-loss-on-difficult-conditions.html | CC-MAIN-2014-41 | refinedweb | 118 | 57.4 |
Hi all,
I worked with OpenHab 2 for some time and now started to migrate to OH3. Since I struggled updating my existing stuff because of mixing file and UI configs I started porting to a fresh install.
However in my openhab2 setup I have a group for all the smart-sockets in my apartment which is also shown in the sitemap. Since I own some Shelly / SonOff / Tasmota plugs that might get offline because it is currently not used I setup a rule to dynamically add or remove items to the group if the online state changes:
import org.openhab.core.model.script.ScriptServiceUtil
val logName=“sockets.rules”
rule "Add / Remove sockets to group" when System started or Member of Sockets_Online changed then Sockets_Online.members.forEach[ s | val String plug_name = s.name.substring(0, s.name.lastIndexOf('_')) val plug_item = ScriptServiceUtil.getItemRegistry.getItem(plug_name) logInfo(logName, "Plug name: "+plug_name+", State: "+s.state.toString) if (s.state == ON) { logInfo(logName, "Adding "+plug_name+" to Sockets group") Sockets.addMember(plug_item) } else { logInfo(logName, "Removing "+plug_name+" from Sockets group") Sockets.removeMember(plug_item) } ] end
Now after migrating to OH3 I’d also like to use the same for the MainUI with semantic-model. So only the sockets that are online should be shown under Equipment->PowerOutlet.
Is there a possibility in OH3 to dynamically add/remove the equipment tag?
Thanks in advance
Regards,
Christian | https://community.openhab.org/t/oh3-dynamically-change-semantic-model/114911 | CC-MAIN-2022-40 | refinedweb | 230 | 50.53 |
A. An app domain acts like a process but uses fewer resources.
App domains can be independently started and halted. They are secure, lightweight, and versatile. An app domain can provide fault tolerance; if you start an object in a second app domain and it crashes, it will bring down the app domain but not your entire program. You can imagine that web servers might use app domains for running users' code; if the code has a problem, the web server can maintain operations.
An app domain is encapsulated by an instance of the AppDomain class, which offers a number of methods and properties. A few of the most important are listed in Table 19-1.
App domains also support a variety of eventsincluding AssemblyLoad, AssemblyResolve, ProcessExit, and ResourceResolvethat are fired as assemblies are found, loaded, run, and unloaded.
Every process has an initial app domain, and can have additional app domains as you create them. Each app domain exists in exactly one process. Until now, all the programs in this book have been in a single app domain: the default app domain. Each process has its own default app domain. In many, perhaps in most of the programs you write, the default app domain will be all that you'll need.
However, there are times when a single domain is insufficient. You might create a second app domain if you need to run a library written by another programmer. Perhaps you don't trust the library, and want to isolate it in its own domain so that if a method in the library crashes the program, only the isolated domain will be affected. If you were the author of Internet Information Server (IIS, Microsoft's web hosting software), you might spin up a new app domain for each plug-in application or each virtual directory you host. This would provide fault tolerance, so that if one web application crashed, it would not bring down the web server.
It is also possible that the other library might require a different security environment; creating a second app domain allows the two security environments to co-exist. Each app domain has its own security, and the app domain serves as a security boundary.
App domains are not threads and should be distinguished from threads. A thread exists in one app domain at a time, and a thread can access (and report) which app domain it is executing in. App domains are used to isolate applications; within an app domain there might be multiple threads operating at any given moment (see Chapter 20).
To see how app domains work, let's set up an example. Suppose you wish your program to instantiate a Shape class, but in a second app domain.
Normally, you'd load the Shape class from a separate assembly, but to keep this example simple, you'll just put the definition of the Shape class into the same source file as all the other code in this example (see Chapter 17). Further, in a production environment, you might run the Shape class methods in a separate thread, but for simplicity, you'll ignore threading for now. (Threading is covered in detail in Chapter 20.) By sidestepping these ancillary issues, you can keep the example straightforward and focus on the details of creating and using application domains and marshaling objects across app domain boundaries.
Create a new app domain by calling the static method CreateDomain( ) on the AppDomain class:
AppDomain ad2 = AppDomain.CreateDomain("Shape Domain");
This creates a new app domain with the friendly name Shape Domain. The friendly name is a convenience to the programmer; it is a way to interact with the domain programmatically without knowing the internal representation of the domain. You can check the friendly name of the domain you're working in with the property System.AppDomain.CurrentDomain.FriendlyName.
Once you have instantiated an AppDomain object, you can create instances of classes, interfaces, and so forth using its CreateInstance( ) method. Here's the signature:
public ObjectHandle CreateInstance( string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes );
And here's how to use it:
ObjectHandle oh = ad2.CreateInstance( "ProgCSharp", // the assembly name "ProgCSharp.Shape", // the type name with namespace false, // ignore case System.Reflection.BindingFlags.CreateInstance, // flag null, // binder new object[] {3, 5}, // args null, // culture null, // activation attributes null ); // security attributes
The first parameter (ProgCSharp) is the name of the assembly, and the second (ProgCSharp.Shape) is the name of the class. The class name must be fully qualified by namespaces.
A binder is an object that enables dynamic binding of an assembly at runtime. Its job is to allow you to pass in information about the object you want to create, to create that object for you, and to bind your reference to that object. In the vast majority of cases, including this example, you'll use the default binder, which is accomplished by passing in null.
It is possible, of course, to write your own binder that might, for example, check your ID against special permissions in a database and reroute the binding to a different object, based on your identity or your privileges.
Binding flags help the binder fine tune its behavior at binding time. In this example, use the BindingFlags enumeration value CreateInstance. The default binder normally only looks at public classes for binding, but you can add flags to have it look at private classes if you have the right permissions.
When you bind an assembly at runtime, do not specify the assembly to load at compile time; rather, determine which assembly you want programmatically, and bind your variable to that assembly when the program is running.
The constructor you're calling takes two integers, which must be put into an object array (new object[] {3, 5} ). You can send null for the culture because you'll use the default (en) culture and won't specify activation attributes or security attributes.
You get back an object handle, which is a type that is used to pass an object (in a wrapped state) between multiple app domains without loading the metadata for the wrapped object in each object through which the ObjectHandle travels. You can get the actual object itself by calling Unwrap( ) on the object handle, and casting the resulting object to the actual typein this case, Shape.
The CreateInstance( ) method provides an opportunity to create the object in a new app domain. If you were to create the object with new, it would be created in the current app domain.
You've created a Shape object in the Shape domain, but you're accessing it through a Shape object in the original domain. To access the shape object in another domain, you must marshal the object across the domain boundary.
Marshaling is the process of preparing an object to move across a boundary; once again, like Captain Kirk teleporting to the planet's surface. Marshaling is accomplished in two ways: by value or by reference. When an object is marshaled by value, a copy is made. It is as if I called you on the phone and asked you to send me your calculator, and you called up the hardware store and had them send me one that is identical to yours. I can use the copy just as I would the original, but entering numbers on my copy has no effect on your original.
Marshaling by reference is almost like sending me your own calculator. Here's how it works. You do not actually give me the original, but instead keep it in your house. You do send me a proxy. The proxy is very smart: when I press a button on my proxy calculator, it sends a signal to your original calculator, and the number appears over there. Pressing buttons on the proxy looks and feels to me just like I reached through the telephone wire between us and touched your original calculator.
The Captain Kirk and hardware analogies are fine as far as analogies go, but what actually happens when you marshal by reference? The Common Language Runtime (CLR) provides your calling object with a transparent proxy (TP).
The job of the TP is to take everything known about your method call (the return value, the parameters, etc.) off of the stack and stuff it into an object that implements the IMessage interface. That IMessage is passed to a RealProxy object.
RealProxy is an abstract base class from which all proxies derive. You can implement your own real proxy, or any of the other objects in this process except for the transparent proxy. The default real proxy will hand the IMessage to a series of sink objects.
Any number of sinks can be used depending on the number of policies you wish to enforce, but the last sink in a chain will put the IMessage into a channel. Channels are split into client-side and server-side channels, and their job is to move the message across the boundary. Channels are responsible for understanding the transport protocol. The actual format of a message as it moves across the boundary is managed by a formatter. The .NET Framework provides two formatters: a Simple Object Access Protocol (SOAP) formatter, which is the default for HTTP channels, and a Binary formatter, which is the default for TCP/IP channels. You are free to create your own formatters and, if you are truly a glutton for punishment, your own channels.
Once a message is passed across a boundary, it is received by the server-side channel and formatter, which reconstitute the IMessage and pass it to one or more sinks on the server side. The final sink in a sink chain is the StackBuilder, whose job is to take the IMessage and turn it back into a stack frame so that it appears to be a function call to the server.
To illustrate the distinction between marshaling by value and marshaling by reference, in the next example you'll tell the Shape object to marshal by reference but give it a member variable of type Point, which you'll specify as marshal by value.
Note that each time you create an object that might be used across a boundary, you must choose how it will be marshaled. Normally, objects cannot be marshaled at all; you must take action to indicate that an object can be marshaled, either by value or by reference.
The easiest way to make an object marshal by value is to mark it with the Serializable attribute:
[Serializable] public class Point
When an object is serialized, its internal state is written out to a stream, either for marshaling or for storage. The details of serialization are covered in Chapter 21.
The easiest way to make an object marshal by reference is to derive its class from MarshalByRefObject:
public class Shape : MarshalByRefObject
The Shape class will have just one member variable, upperLeft. This variable will be a Point object, which will hold the coordinates of the upper-left corner of the shape.
The constructor for Shape will initialize its Point member:
public Shape(int upperLeftX, int upperLeftY) { Console.WriteLine( "[{0}] Event{1}", System.AppDomain.CurrentDomain.FriendlyName, "Shape constructor"); upperLeft = new Point(upperLeftX, upperLeftY); }
Provide Shape with a method for displaying its position:
public void ShowUpperLeft( ) { Console.WriteLine( "[{0}] Upper left: {1},{2}", System.AppDomain.CurrentDomain.FriendlyName, upperLeft.X, upperLeft.Y); }
Also provide a second method for returning its upperLeft member variable:
public Point GetUpperLeft( ) { return upperLeft; }
The Point class is very simple as well. It has a constructor that initializes its two member variables and accessors to get their value.
Once you create the Shape, ask it for its coordinates:
s1.ShowUpperLeft( ); // ask the object to display
Then ask it to return its upperLeft coordinate as a Point object that you'll change:
Point localPoint = s1.GetUpperLeft( ); localPoint.X = 500; localPoint.Y = 600;
Ask that Point to print its coordinates, and then ask the Shape to print its coordinates. So, will the change to the local Point object be reflected in the Shape? That will depend on how the Point object is marshaled. If it is marshaled by value, the localPoint object will be a copy, and the Shape object will be unaffected by changing the localPoint variables' values. If, on the other hand, you change the Point object to marshal by reference, you'll have a proxy to the actual upperLeft variable, and changing that will change the Shape. Example 19-1 illustrates. Make sure you build Example 19-1 in a project named ProgCSharp. When Main( ) instantiates the Shape object, the method is looking for ProgCSharp.exe.
using System; using System.Runtime.Remoting; using System.Reflection; namespace ProgCSharp { // for marshal by reference comment out // the attribute and uncomment the base class [Serializable] public class Point // : MarshalByRefObject { private int x; private int y; public Point (int x, int y) { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Point constructor"); this.x = x; this.y = y; } public int X { get { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Point x.get"); return this.x; } set { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Point x.set"); this.x = value; } } public int Y { get { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Point y.get"); return this.y; } set { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Point y.set"); this.y = value; } } } // the shape class marshals by reference public class Shape : MarshalByRefObject { private Point upperLeft; public Shape(int upperLeftX, int upperLeftY) { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Shape constructor"); upperLeft = new Point(upperLeftX, upperLeftY); } public Point GetUpperLeft( ) { return upperLeft; } public void ShowUpperLeft( ) { Console.WriteLine( "[{0}] Upper left: {1},{2}", System.AppDomain.CurrentDomain.FriendlyName, upperLeft.X, upperLeft.Y); } } public class Tester { public static void Main( ) { Console.WriteLine( "[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Entered Main"); // create the new app domain AppDomain ad2 = AppDomain.CreateDomain("Shape Domain"); // Assembly a = Assembly.LoadFrom("ProgCSharp.exe"); // Object theShape = a.CreateInstance("Shape"); // instantiate a Shape object ObjectHandle oh = ad2.CreateInstance( "ProgCSharp", "ProgCSharp.Shape", false, System.Reflection.BindingFlags.CreateInstance, null, new object[] {3, 5}, null, null, null ); Shape s1 = (Shape) oh.Unwrap( ); s1.ShowUpperLeft( ); // ask the object to display // get a local copy? proxy? Point localPoint = s1.GetUpperLeft( ); // assign new values localPoint.X = 500; localPoint.Y = 600; // display the value of the local Point object Console.WriteLine( "[{0}] localPoint: {1}, {2}", System.AppDomain.CurrentDomain.FriendlyName, localPoint.X, localPoint.Y); s1.ShowUpperLeft( ); // show the value once more } } } Output: [Programming CSharp.exe] Entered Main [Shape Domain] Shape constructor [Shape Domain] Point constructor [Shape Domain] Point x.get [Shape Domain] Point y.get [Shape Domain] Upper left: 3,5 [Programming CSharp.exe] Point x.set [Programming CSharp.exe] Point y.set [Programming CSharp.exe] Point x.get [Programming CSharp.exe] Point y.get [Programming CSharp.exe] localPoint: 500, 600 [Shape Domain] Point x.get [Shape Domain] Point y.get [Shape Domain] Upper left: 3,5
Read through the code, or better yet, put it in your debugger and step through it. The output reveals that the Shape and Point constructors run in the Shape domain, as does the access of the values of the Point object in the Shape.
The property is set in the original app domain, setting the local copy of the Point object to 500 and 600. Because Point is marshaled by value, however, you are setting a copy of the Point object. When you ask the Shape to display its upperLeft member variable, it is unchanged.
To complete the experiment, comment out the attribute at the top of the Point declaration and uncomment the base class:
// [serializable] public class Point : MarshalByRefObject
Now run the program again. The output is quite different:
[Programming CSharp.exe] Entered Main [Shape Domain] Shape constructor [Shape Domain] Point constructor [Shape Domain] Point x.get [Shape Domain] Point y.get [Shape Domain] Upper left: 3,5 [Shape Domain] Point x.set [Shape Domain] Point y.set [Shape Domain] Point x.get [Shape Domain] Point y.get [Programming CSharp.exe] localPoint: 500, 600 [Shape Domain] Point x.get [Shape Domain] Point y.get [Shape Domain] Upper left: 500,600
This time you get a proxy for the Point object and the properties are set through the proxy on the original Point member variable. Thus, the changes are reflected within the Shape itself. | http://etutorials.org/Programming/Programming+C.Sharp/Part+III+The+CLR+and+the+.NET+Framework/Chapter+19.+Marshaling+and+Remoting/19.1+Application+Domains/ | CC-MAIN-2017-13 | refinedweb | 2,731 | 56.86 |
I have the following code segment in a function, and that function is
called often. I have the value of SDLK_LEFT stored as an SDLKey in the
"keys" structure. As a test, whenever the left arrow key is pressed, I
have it print “rotating left!”. This is constantly being called in a
loop, yet if I press and hold the left arrow key down, it only prints
"rotating left!" once. What’s wrong below? (I’d like it to constantly
print “rotating left!”)
SDL_Event event; SDL_keysym keysym; SDL_PollEvent(&event); switch(event.type) { case SDL_QUIT: return (0); break; case SDL_KEYDOWN: keysym = event.key.keysym; if (keysym.sym == SDLK_ESCAPE) { return (0); } if (keysym.sym == keys.rotate_left) { fprintf(stdout, "rotating left!\n"); fprintf(stdout, "keysym.sym = %d\n", keysym.sym); fprintf(stdout, "keys.rotate_left = %d\n", keys.rotate_left); break; } break; default: break; } return (1);
– chris (@Christopher_Thielen) | https://discourse.libsdl.org/t/sdl-input-basic-question/7118 | CC-MAIN-2022-21 | refinedweb | 143 | 80.58 |
Automatic transformation of XML namespaces/Recursive downloading the information
When we speak about downloading next RDF file we mean downloading the next RDF file in the depth-first or breadth-first order (as specified by user options). The order of edges which point to the next URL for the downloading algorithms are: first “see also”, “sources”, “targets” (in the order specified by the user options) and then the order of their start nodes in the RDF file.
Upon reading an RDF file, the list of the namespaces, the list of transformations, and the list of relations between precedences should be updated, accordingly the grammar described above.
Implementation note: If our task is validation, updating the list of transformations and precedences is not necessary. If our task is transformation, updating the list of namespaces is not necessary.
Note: Retrieving some existing documents designated by namespace URLs gets an RDF Scheme. Examples: and. In this case :namespaceInfo in the RDFS points to a namespace information which should be downloaded instead.
As an other alternative, the RDF file pointed by the namespace URL may contain namespace and transformer info.
Several namespaces may refer to one RDF due using # in URLs.
Backward compatible feature: If at the URL we download from there is an RDDL document, download the RDF specified as an RDDL resource with xlink:role="". (This is not done recursively, that it an RDDL document linked from an other RDDL document is not downloaded.)
If a valid RDF document was not retrieved from a URL (say because of a 404 HTTP error or because invalid XML code), it should not be retrieved again. However it is not forbidden to repeat failed because of timeout HTTP attempts.
Recursive retrieval may be limited to certain URLs. For example, it may be limited only to file:// URLs. | https://en.wikiversity.org/wiki/Automatic_transformation_of_XML_namespaces/Recursive_downloading_the_information | CC-MAIN-2017-17 | refinedweb | 302 | 51.28 |
Date: Tue, 31 Dec 1996 12:04:35 -0500 (EST) From: "william c. rinehuls" <rinehuls@access.digex.net> To: sc22docs@dkuug.dk Subject: SC22 N2369 - WG21 Minutes of November 1996 Meeting _______________________beginning of title page ____________________ ISO/IEC JTC 1/SC22 Programming languages, their environments and system software interfaces Secretariat: U.S.A. (ANSI) ISO/IEC JTC 1/SC22 N2369 January 1997 TITLE: Minutes of SC22/WG21 (C++) Meeting on November 10- 15, 1996 in Kona, Hawaii, USA SOURCE: Secretariat, ISO/IEC JTC 1/SC22 WORK ITEM: N/A STATUS: N/A CROSS REFERENCE: N/A DOCUMENT TYPE: WG21 Meeting Minutes _________________ Document Number: WG21/N1041 X3J16/96-0223 Date: 3 December 1996 Project: Programming Language C++ Reply to: Sean A. Corfield sean@ocsltd.com WG21 Meeting No. 17 10 - 15 November 1996 The Royal Waikoloan Hotel Kona, HI USA 1. Opening activities Clamage convened the meeting as chair at 8:37 HST on Monday, 10 November 1996. Miller was vice-chair, and Corfield was the secretary. Plum Hall (represented by Plum) hosted the meeting. 1.1 Opening comments Clamage noted there were fewer members than we might have expected for a North American meeting but that there were some new members at this meeting. 1.2 Introductions Clamage announced that Corfield was taking over secretarial duties from Saks and the committee thanked Saks for all his hard work over the last seven years. Applause. Corfield circulated an attendance list each day, which is attached as Appendix A of these minutes. Miller circulated a copy of the membership list (SD-2 = 96-0001) for members to make corrections. 1.3 Membership, voting rights, and procedures for the meeting Clamage reminded the attendees that this is a co-located meeting of WG21 and X3J16. (The joint membership is denoted WG21+X3J16 in these minutes.) Clamage explained the voting rules: In straw votes, all WG21 technical experts may vote, even those who haven't attended previous WG21 meetings. An X3J16 attendee may vote only if he/she is the voting representative of a member organization that has met the X3's meeting attendance requirements. (The voting representative is the principal member, or an alternate if the principal is not present.) A WG21 technical expert who is also an X3J16 voting member still casts only one vote in a straw vote. In WG21 formal votes, only the head of each national delegation may vote. In X3J16 formal votes, only one representative from each X3J16 member organization may vote, and only then if the organization meets the attendance requirements. Plum explained the facilities provided (and warned about the dangers of the sun). Plum noted that authors of proposals would have to copy their own documents at this meeting. This should reduce the number of proposals. Laughter. He explained that a Sparcstation is available but since it will be used to typeset the WP at this meeting it should not be used without permission from Koenig. Koenig noted that he can produce printed copies at any point during the week. Miller explained the procedure for document number allocation at this meeting. Miller asked that electronic copy of all documents produced at the meeting be provided to him before the end of the meeting. Diskettes have been provided for this purpose. 1.4 Distribution of position papers, WG progress reports, WG work plans for the week, and other documents that were not distributed before the meeting There were no position papers or progress reports. Work plans will be covered by item 1.6 below. 1.5 Approval of the minutes of the previous meeting Saks said that he had not received any corrections to the previous minutes. Motion by Rumsby/Lajoie: Move we approve N0952 = 96-0134 as the minutes of the previous meeting. Motion passed X3J16: lots yes, 0 no. 1.6 Agenda review and approval Clamage deferred this item until after discussion of the organisation of subgroups below. 1.7 Report on the WG21 Sunday meeting Plum summarised WG21's discussion about prioritising issues: if the consensus is that we are entitled to fix something, we can actually apply a fix, regardless of the resolution at Stockholm in support of a feature freeze. He noted that we should not search for editorial problems just for their own sake because fixing them might cause ripple effects and be destabilising. We should concentrate on locating and fixing what are deemed by consensus to be bugs. He reported that all NBs present were strongly in favour of ensuring we ship CD2 at the end of this week. 1.8 Liaison reports Benito presented the WG14 liaison report. long long has been officially adopted. Clamage asked what WG14's position is on removing implicit int. Benito replied that WG14 was in favour of removing implicit int and expected an affirmative vote at the next WG14 meeting. Benito noted that WG14 has adopted the general position not to accept any further language extensions in order to expedite the issue of C9X. He said that the translation limits concerning external names had been relaxed so that case is now significant and that the first 31 characters of names are significant. Brck asked about the sign of the remainder in division. Benito believes the resolution has been incorporated to adopt the FORTRAN approach. No other liaisons were present. 1.9 New business requiring actions by the committee There was no new business. 2. Working Paper for Draft Proposed Standard Koenig said he normally gives the Editorial report in General session but was happy to give it today. 2.1 Changes in the Working Paper Koenig said there were a large number of editorial volunteers who continued to work on the WP after the pre-Hawaii mailing. He said the numbers of changes are reducing so it looks like we are approaching closure. Koenig thanked everyone who helped with the editing. He noted that only a few "bold changes" were made this time and they were all in lib-iostreams. The relevant box numbers were 42(27.2), 45(27.3), 47(27.4.1), 49(27.4.5.1), 53(27.6.1.3), 55(27.7.1.3), 58, 60(27.8.1.4). Koenig said he will tighten up the tracking of changes to resolutions from this meeting onwards as it becomes more important to ensure no inadvertent changes get made. Plum confirmed that during this week only a limited number of hands-on editors will actually touch the document. Koenig encouraged those who could do so to review the WP in electronic form (PDF) rather than on paper "to conserve trees". Schwarz asked if we have a version of the WP as it is now rather than as it was in the mailing. Koenig said no, but he can easily produce such a version. Rumsby and Koenig agreed to liaise to produce PDF from the PostScript for distribution to those at the meeting who need it. Stanchfield asked for a plain ASCII text version to work from. Koenig said this may be possible but is very time-consuming. Motion by Lajoie/Dawes: Move we approve N0996 = 96-0178 as the current Working Paper. Motion passed X3J16: lots yes, 0 no. Motion passed WG21: 5 yes, 0 no, 0 abstain. 3. Organise subgroups, chapter editors, and chapter reviewers. Establish working procedures Clamage reiterated our intention to approve the current draft for submission as the second Committee Draft. The intent is to have two votes at the end of this meeting: * approve the modified draft prepared at this meeting as the current Working Paper, and * submit that Working Paper as the second Committee Draft. Dawes named the editors for the library clauses: Schwarz for iostreams, Rumsby and Dawes for the rest. Clamage said that Plum has the master list of editorial volunteers and asked that potential volunteers check with Plum. Clamage explained that nominated reviewers will examine each clause to ensure that the resolutions have been correctly incorporated and that no other substantive changes are made by accident. Lajoie said there would be three core groups at this meeting. They would meet separately on Monday and jointly on Tuesday. Dawes said that four library issues overlap with core group work but otherwise the library groups will work together. Clamage announced a technical session on allocators. Dawes will use the feedback from the technical session to direct the WG's discussion. Comeau asked Lajoie to explain the topics covered by each core group. Lajoie listed what each Core WG would be covering. Clamage noted that Benito would chair the C Compatibility WG in conjunction with the Core WGs. Lajoie said the C Compatibility issues are mainly to do with Annex C. Gafter asked whether there would be a Syntax WG. Lajoie said this would be handled by Core since there is only one outstanding issue. 3.1 Agenda review and approval Motion by Glassborow/Lajoie: Move we approve N1002 = 96-0184 (with agenda approval as item 3.1 instead of 1.6) as the agenda for this meeting. Allison asked for clarification prior to the vote. Clamage read out the agenda items because not everyone had a paper copy. Anderson asked if we would have straw votes at this meeting. Clamage said the process was intended not to need straw votes. He said two of the issues that might need further discussion are allocators and export/extern. Unruh suggested that we have straw votes on demand for potentially controversial issues in General session I. There was general agreement on this suggestion. Miller noted a change to X3J16 voting procedures. It is now permissible to abstain on technical and procedural votes. He noted that votes on motions such as affirming document transmittal still require no abstentions and a two-thirds plus one majority. Motion passed X3J16: lots yes, 0 no. Motion passed WG21: 5 yes, 0 no, 0 abstain. The committee recessed to WGs at 9:55 on Monday. 4. WG sessions 5. WG sessions The committee reconvened at 8:23 on Wednesday. 6. General session I Clamage explained that subgroup chairs will present briefly the issues to be incorporated and take questions. After each group of issues, we will vote on the whole group of proposals. Straw votes can be conducted on demand. Formal votes will be taken for each group of issues presented. C Compatibility (Benito) Benito said there were 11 editorial issues, three of which concerned Annex C. Benito said the Annex needs to be updated but the WG have not done so because the text is non-normative. Gafter asked whether we should vote on keeping versus removing the Annex. Benito said we have no volunteers to update the Annex. Benito noted that there was a UK NB comment that part of Annex subclause C.1 should be removed. Clamage asked if the WG made any changes. Benito said they have produced two documents listing changes made: N1035 = 96-0217 which lists the editorial core issues closed and N1036 = 96-0218 which documents the changes made to clause 16 (mainly changing the use of "shall"). Miller asked for clarification of some of the changes. Nelson said the WG clarified that #undef __STD__ is implementation-defined (because it is implementation-defined whether or not __STDC__ is actually predefined). Benito said no issues needed a committee vote. Library I (Dawes) Dawes presented the motions in N1020 = 96-0202. Dawes noted the following corrections to the distributed copy: In item 1, delete the two lines beginning: os.putc() in turn for... In item 2, the correct document number is N1018 = 96-0200. In item 4, the correct document number is N1017 = 96-0199. Dawes then discussed each item in turn. Item 1. He said the issues closed with no action (21-090, 21-095 and 21-111 from N1006 = 96-0188) were made moot by io-related issues closed in Stockholm. He said the proposed resolutions for 21-113, 21-115 and 21-116 corrected a typo, clarified the interaction of ios::width with strings and added a clear() member function. Corfield noted an error in the proposed resolution for operator<< effects: str.iterator should be: basic_string< ... >::iterator Item 2. Clarify that the exception string is required to have the same spelling but not necessarily to point to the same data. Item 3. Add a specific definition of "equivalence" relationship for EqualityComparable requirements and resolve several issues concerning utilies. Koenig asked for an explanation of the resolutions concerning auto_ptr<> because of the controversy on the reflector. Dawes said the issue of conversions was resolved by using "implicitly converted" which is a well-defined term in the WP. The second issue clarified the behaviour of repeated assignment. Colvin said the WP was contradictory in this area. The resolution is to clarify that repeated assignment of one auto_ptr<> object to another causes a dangling pointer. The third issue is the destructor: the resolution is to require that delete get() is a well-formed expression in order to instantiate the template. Dawes then explained the resolutions covering explicit declarations of copy constructors and assignment operators. Corfield asked for clarification as to why the default complex copy constructor and assignment operator are necessary. No one seemed to know. Myers commented that this motion adds a member (auto_ptr<>::operator=) that another motion proposes deleting. The motion was left unchanged. Item 4. Clarify which names are in namespace std and resolve some exception issues. Gafter asked for clarification of "library entities" mentioned in regard to names in namespace std. Dawes said this is defined in the previous paragraph. Unruh noted that the name std itself must be in the global namespace and that we should be clear that other nested namespaces are allowed (instead of just rel_ops). Corfield asked whether it would be clear that new & delete would be in the global namespace. Dawes said yes. The clarifications on exception handlers were non-controversial. Item 5. Remove wording inherited from C dealing with external linkage names in the library (since it is not necessary because the names live in namespace std). Unruh noted that an extern "C" linkage function in a namespace may affect the use of the name somewhere else (in the user program). We have no wording to cover this. Spicer asked whether the issue of extern "C" versus extern "C++" linkage for C library functions had been discussed. Dawes felt there was a lot of concern about this proposal and maybe he should withdraw it. Austern said the concerns expressed covered other clauses than those affected by this motion. Dawes wanted to drop item 5 from his motions. Spicer asked his question again. Dawes said there are no open issues regarding this unspecified linkage. Spicer explained that this means it is impossible to write a portable program using, e.g., qsort since we do not know the linkage of the pointer to function argument. Item 6. Clarify which namespaces are not extensible. Myers asked if we have specified what can be specialised. Dawes said yes. Item 7. Clarify intent of default argument specification on template member functions in the library. Ball noted that explicit should not be on all three constructors in the example. Plum said we expect this issue to be revisited during the CD2 ballot process. Corfield asked about the wording elsewhere concerning default constructible types in containers. Plum said this would also be revisited. Motion by Dawes/Rumsby: Move we modify the WP as specified in N1020 = 96-0202, items 1-4, 6, 7 (with the corrections noted above). Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Core I (Lajoie) Lajoie presented the motions in N1031 = 96-0213. Item 1. Resolve Core issue 666 and clarify that a namespace name does not hide a class name used as a base class or in an elaborated-type-specifier. This was non-controversial. Item 2. Resolve Core issue 727 and clarify which namespace block extern declarations refer to. O'Riordan asked what "have linkage" means. Miller explained that it meant the declaration will not have "no linkage" and this is made clear by the following text. Item 3. Clarify semantics of friend declarations in local classes. Gafter felt this was a complicated proposal solving a minor problem and would prefer to deprecate or remove friends in local classes. Lajoie said this motion clarified the pre-Stockholm intent. Gafter asked for a straw vote on a friendly amendment to deprecate friends in local classes. Lajoie said no. Plum reiterated our charter for this meeting and said that Gafter's suggestion was outside that charter despite being a reasonable one. Item 4. Resolve Core issue 674 and clarify class name lookup and ambiguity in the presence of using-declarations. This was non-controversial. Item 5. Resolve issue 675 and clarify the definition of final overrider in the presence of using-declarations. Ball was surprised that the resolution was different to what had been agreed in the Core WG (to make the proposed usage ill-formed). Gafter said some members of the WG later decided this was too strict and so the proposal just clarifies that using-declarations cannot affect final overriding. Lajoie said we could vote on this separately if the committee wants. Ball expressed concern about this change from the WG's resolution. Glassborow said the WG making the usage ill-formed would break a lot of code since this style of using-declaration should be a standard idiom to bring in names from base classes. Plum asked whether this was a NB issue. Lajoie said no, it was a core issue. She said the WG identified this as a bug in the WP. Anderson said he shared Ball's concern but felt we should accept the clarification because it matches the behaviour of final overriders with access declarations. Lajoie asked for a straw vote for incorporating this change in the motions but keeping it on the issues list. The straw vote passed: 17 in favour / 5 opposed / 5 none. Item 6. Resolve Core issue 700 and indicate that a diagnostic is not required when a function or object is used but not defined. Corfield asked why no diagnostic was required. Unruh said that a use in dead code should not require a diagnostic. Brck asked if the WP is clear but said he felt this is a desirable change anyway. Lajoie said yes the WP was clear but considered by the Core WG to be unworkable. Miller clarified that it restores the pre-Stockholm intent for virtual functions. We do not want to require definitions for unused virtual functions. Koenig asked for confirmation that "undefined behavior" was considered an improvement. Plum believes there are a dozen instances where the WP expects the linker to diagnose problems so this change makes very little difference. He also said that this change would help just-in-time development environments or interpreted systems. Plum asked if we should consider requiring that a diagnostic appears "at some time" prior to calling the undefined function but was not sure what approach we should take. Gafter said this muddles the phases of translation. Anderson felt the wording in the proposal should refer to wording for inline functions. Lajoie agreed that the wording could be improved. Lajoie said that we will be revisiting conformance issues during the CD2 ballot process (since it is a long-standing NB issue) so the issue of diagnostics will come up again. Glassborow was unhappy that we seemed to be pushing more fixes into the CD2 ballot period. Item 7. To only require a static member to be defined if it is used. Lajoie explained that this helps templates because static data members do not need to be instantiated. Glassborow objected that this removes a way of providing constraints on templates. Ball said this was taking advantage of an implementation quirk. Gibbons said the status quo effectively requires that unnecessary instantiations and attendant side effects take place and we should remove this requirement (i.e., accept the proposal). Item 8. Resolve Core issue 728 and clarify how linkage-specifications affect object declarations and definitions. Lajoie said this follows the ARM. Corfield asked for clarification that the proposed wording really did match the WG resolution. Miller and Lajoie confirmed that it did. Unruh suggested a better example be provided in the WP text. Item 9. Resolve Core issues 635 and 725, render recursive local static initialisation undefined and allow early initialisation. Unruh asked for clarification that this matches the rules for names in namespace scope. Gafter said yes. Item 10. To clarify when an implementation may create temporaries. Lajoie explained the the motion clarifies precisely when temporaries may be created and when their lifetimes are longer than the full expression. In response to O'Riordan's earlier comment, Miller noted that the omission of the external linkage specification on item 2 above was an editorial slip on his part. Motion by Anderson/Lajoie: Move we amend the WP as specified in N1031 = 96-0213. Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Lajoie presented another motion from an unnumbered paper distributed at the meeting. The motion proposes that a program be ill-formed if an unambiguous, accessible delete operator cannot be found using the usual lookup rules at the point of definition of the destructor. Corfield asked for clarification that the proposal breaks a useful idiom concerning declaring operator delete() private in a base class in order to restrict dynamically allocated uses of a class. Lajoie said yes. Motion by Lajoie/Hartinger: Move we amend the WP to clarify accessibility and name lookup of operator delete(). Motion passed X3J16: 18 yes, 3 no, 9 abstain. Motion passed WG21: 3 yes, 1 no, 1 abstain. Core II (Adamczyk) Adamczyk presented the motions in N1033 = 96-0215. The first few issues covered small corrections to the handling of cv-qualification. Adamczyk explained that these mainly covered incorrect handling of void* and multi-level pointer cases by introducing the term "cv-qualification signature". Schwarz asked if this made pointer comparisons more compatible with C. Adamczyk said yes. Adamczyk explained the proposed clarification that no lvalue-to-rvalue conversion occurred for void expressions because of extra cases where C++ produces lvalues. In some of these extra cases, such conversions are undesirable. This introduces a minor difference from C for volatile variables: volatile int i; i; /* fetched in C */ // not fetched in C++ Adamczyk then clarified that (void)x; is same as the implicit case x;. Koenig asked for clarification of the following: struct x; x& f1(); x f2(); f1(); // OK, value not used f2(); // ill-formed (still) Adamczyk said yes this is the proposed behaviour. The next item is a clarification that cv-qualification is significant on member function calls when constructing the candidate set. The last item adds a pseudo-prototype for ->*. Unruh expressed concern about overload resolution being correct for this prototype. Gafter said that there will (still) be ambiguous cases but this is probably a better formulation. Adamczyk said that Core II left the pseudo-prototype for ?: broken but these cases will be revisited during the ballot process. Corfield asked for confirmation that the delayed issues will be put forward through public comment / NB comment channels. Adamczyk said that was his intent. Unruh said he is unconvinced that the current ->* prototype is wrong. Adamczyk dropped that motion. Schwarz expressed concern over the amount of churn in pseudo-prototypes and asked whether we should just leave them alone. Adamczyk basically agreed but said the WG is trying to fix only those problems that are genuinely considered to be broken. Schwarz asked how broken something has to be. Adamczyk said if it broke a "simple" example it was considered broken enough. Brck said we don't have time to discuss what is broken but only what can be fixed. Motion by Welch/Lajoie: Move we amend the WP as specified in N1033 = 96-0215 (without the motion concerning the pseudo-prototype for ->*). Motion passed X3J16: lots yes, 0 no, 2 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Core III (Gibbons) Gibbons presented the motions in N1032 = 96-0214. Item 1. Clarify the semantics of uncaught_exception(). Welch asked for clarification that uncaught_exception() remains true when there are nested exceptions active even when the top exception is caught. Gibbons said yes. Hartinger asked for clarification that this only applies to implicit calls. Gibbons said yes, because the library already specifies that user calls have different semantics. Stanchfield asked for clarification that user calls to terminate() do not affect the result uncaught_exception(). Gibbons said yes. Item 2. Clarify the semantics of dynamic_cast<>(). Ball made a correction to the motion by inserting "public" before "unambiguous base class". Gibbons explained the intent of the motion was simply to fix a bug in the WP. Item 3. Clarify the semantics of throwing an array or function type. Gibbons explained that the motion clarifies that array to pointer and function to pointer-to-function conversions occur at the point of the throw. Gafter asked why the existing wording for conversions was not used. Gibbons said this was editorial. Brck asked whether catch of an array type could catch a pointer thrown by a throw. Gibbons said yes, just like a function parameter declared as an array can accept a pointer. Spicer said this was existing practice (because you have to do the decay on the throw expression anyway). Gafter corrected the motion by deleting "pointer to" from the return type of the result of converting the function type. Item 4. Clarify when templates are instantiated during a trial parse. Unruh said the proposed wording was contradictory. Gibbons agreed that the wording was imprecise. Unruh said semantic analysis is required during trial parse. Gibbons agreed and said the wording needing revising. Item 5. Clarify the interaction of using-declarations and default arguments. Gibbons used the following example to illustrate the resolution: namespace A { void f(int); } using A::f; namespace A { void f(int = 0); } void g() { f(); // proposed to be valid } A previous unintentional change had made this ill-formed because it did not take any subsequent declaration's default argument into account. Item 6. Clarify when overload resolution causes class template instantiation. Corfield asked why the WG left it unspecified. Gibbons said that in the general case it is not guaranteed that overload resolution can determine this in any reasonable time-it is a tradeoff. Hartinger asked if this was a portability problem. Ball said the same function is always selected but whether or not an ill-formed instantiation is attempted is implementation-defined (so a program may compile on one system but not on another). Item 7. Clarify the set of names considered for dependent lookup. Miller thought that namespace of an enumerator should be added in to the set. Gibbons said the WG felt this was unnecessary complexity for a corner case. Unruh wanted clarification of when no namespaces are considered. Gibbons agreed this is editorial. Item 8. Clarify exception type matching. This was non-controversial. Item 9. Clarify that member templates do not suppress the implicit copy constructor and assignment operator. Corfield asked for confirmation that this was the resolution of the WG in Stockholm that had not been adopted into the WP. Gibbons said yes. Item 10. Specify additional contexts where a dependent qualified name is assumed to be a type. Gibbons showed the following example: template<class T> struct A { struct B { B(int); }; } template<class T> struct C : A<T>::B { // typename not allowed here C(); }; Gibbons explained that the grammar does not allow typename here but the context requires a type. The resolution is to assume it is a type. Similarly for base class mem-initialisers since these are also known to be types by context although typename is not allowed by the grammar. Gafter asked what happens if something assumed to be a class type turns out to be a namespace. Gibbons said that such names cannot appear in dependent qualified names. Item 11. Clarify that friend class T; not permitted. This was non-controversial. Item 12. Clarify that "reference to function" and "pointer to member" types can have exception specifications. Gibbons said this was a simple omission and should be considered editorial. Item 13. Clarify that dereferencing a pointer to member requires a complete class type. This was non-controversial. Item 14. Clarify that types in exception specifications must be complete. Ball noted that this was already fixed in the November WP. Item 15. Add "export" to list of keywords. Gibbons said he would discuss this decision in more detail later. Item 16. Correct the grammar specification involving templates. Lajoie asked about where template is allowed in qualified names. Gibbons said the proposed changes to the grammar were not substantive so if that isn't specified, this proposal would not fix that. Lajoie said she would investigate further. Motion by Ball/Spicer: Move we amend the WP as specified in N1032 = 96-0214 (with the corrections noted above). Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Gibbons said the issue of export versus extern did not need a vote. At Stockholm we agreed to adopt export and revisit the issue in Kona. Gibbons explained that the WG discussed the choice of keyword at length and felt that extern is too confusing. The WG agreed that export might break code. Gibbons noted that this may come up again in a NB comment so he will provide a document in the post-Kona mailing N1034 = 96-0216 detailing the discussions of the WG. Myers expressed his dissatisfaction with the subtle difference between export and extern. Library - allocators (Austern) Austern presented N1027 = 96-0209 which is a motion to adopt the changes proposed in N1021R1 = 96-0203R1 (not N1008 as stated in the version of N1027 initially presented). Austern said there are several small non-controversial changes. Corfield noted that at least one member of the committee (not present in Kona) feels the restrictions on reference and const_reference are controversial. Austern explained the proposed restrictions placed on allocators by the standard containers. Brck feels that it is not clear which problems in N1011 = 96-0193 are solved by this proposal and asked that Austern write a document clarifying this. Austern agreed that this was a good idea. Brck was concerned that the specification "pointer to T" was not clear however he feels that the proposal is an improvement over the WP. Dawes asked whether the small WG involved in writing the proposal was in agreement. Austern said yes but Corfield disagreed. Corfield felt the proposal was too restrictive but there was an agreement that Austern and Corfield would work on specifying the requirements on pointer and const_pointer with a view to submitting comments through NB channels during the CD2 ballot process. Clamage observed that everyone involved agreed that they can live with the compromise. Dawes asked Plauger for his opinion on the proposal. Plauger said he was pleased with the progress made and he is in favour of the proposal. Brck noted that the proposal does not satisfy his requirements. General acknowledgement of Koenig's role in helping establish consensus on this issue. Rumsby called a caucus of the UK delegation to discuss the proposal prior to the vote. Motion by Allison/Corfield: Move we amend the WP as specified in N1021R1 = 96-0203R1. Motion passed X3J16: lots yes, 0 no, 2 abstain. Motion passed WG21: 3 yes, 1 no, 1 abstain. Library II (Becker) Becker presented the motions in N1023 = 96-0205. Becker explained that the motions were mostly editorial and minor bug fixes. Motion 1. Close some issues from N1014 without taking action. Motion 2, Item 1. Clarify that containers copy their comparison object. Item 2.. Clarify that pointers to functions may be used where comparison objects are mentioned. Schwarz asked whether an object with a conversion to function type would work. Becker said no, conversions are not performed for () operations. Item 3. Correct the Returns section for operator<< on bitset. Item 4. Clarify the semantics of the bitset constructor taking a string. Myers noted that the bitset constructor needs to be a template member constructor. Becker agreed to revisit this later. Item 5. Clarify the semantics of capacity(). Item 6. Clarify vector<>::assign() description by renaming the template parameter. Item 7. Make the value comparison operators on map and multimap into const member functions. Item 8. Correct a typo in the Effects section of resize() in several places. Item 9. Correct a typo in the declaration of the reverse_iterator member typedef in several places. Item 10. Systematically replace the remaining uses of distance_type with difference_type. Austern asked when the decision was made to use difference_type instead of distance_type. Becker said people felt it was more important to have a consistent name. Schwarz asked why we were making an essentially aesthetic change at this stage. Myers obtained clarification that iterators used distance_type and everything else used difference_type. Plauger disagreed and said the use of the two type names was not that clear cut. Brck asked specifically whether there was a reason to keep them distinct. The answer appeared to be no. Becker called a straw vote on changing distance_type to difference_type: Straw vote passed: 23 yes, 2 no. Becker said the change to the bitset constructor will be dropped from the motion (issue 23-068). Motion by Rumsby/Colvin: Move we amend the WP as described in N1023 = 96-0205 without the resolution to issue 23-068. Motion passed X3J16: lots yes, 0 no, 0 abstain, Motion passed WG21: 5 yes, 0 no, 0 abstain. Becker presented the motions in N1024 = 96-0206. Motion 1. Close issue 24-021 from N1015 = 96-0197 without action. Myers asked for clarification of 24-021. Becker said that stream iterators would remain in the header <iterator>. Corfield asked why. Becker said the WP is not broken and moving types between headers might break something. Motion 2, Item 1. Clarify intent of proxy class. Becker noted that 24-038 has a revised resolution compared to the paper. Instead of removing the proxy class altogether, the concept of a proxy class remains but the name is no longer specified (i.e., it does not have to be called proxy). Item 2. Clarify that insert_iterator and ostream_iterator post-increment operators must return a reference rather than a value. Plauger noted that this was necessary in order to make the operators implementable. Item 3. Resolve issue 24-044 by adding typedefs to the iterator traits. Becker explained that this makes reverse iterators easier to implement. Item 4. Resolve issue 24-045 by adding semantics for istream_iterator and ostream_iterator. Item 5. Specify the missing semantics in Table 86, 24.1.5 [lib.random.access.iterators]. Motion by Rumsby/Glassborow: Move we amend the WP as specified in N1024 = 96-0206 (with the amended resolution to 24-038). Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Becker presented the motion in N1025 = 96-0207. Becker said this was a decision to retain the status quo by not moving some algorithms into utilities and closes issues 25-015, 25-016 and 25-017 from N1016 = 96-0198. Motion by Colvin/Rumsby: Move we retain status quo on the location of these algorithms. Motion passed X3J16: lots yes, 0 no, 1 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Becker presented the motions in N1026 = 96-0208. Becker said these are mostly editorial changes to numerics. Item 1. Clarify the description of the valarray destructor. Koenig said we could encourage implementations to return memory by using "should". There was no general support for this. Saks suggested the wording "may invoke a deallocation function". Brck asked that we not wordsmith in full committee. Item 2. Remove free(). Item 3. Change signature of resize() to have a value parameter instead of a reference parameter. Corfield asked whether this affects any other resize() members. Becker said all the others have value parameters already. Item 4. Close issue 26-055 by correcting the description of shift and rotate operations. Motion by Rumsby/Dawes: Move we amend the WP as described in N1026 = 96-0208. Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Library III (Schwarz) Corfield noted the document numbers said 95- instead of 96-. Schwarz will correct these for the mailing. Schwarz presented the motions in N1029 = 96-0211. Item 1. Add Allocator parameter to use of basic_string. Ward corrected the declaration of the template to: template<class charT, class Traits, class Allocator> bool operator()(const basic_string<charT,Traits,Allocator>& s1, const basic_string<charT,Traits,Allocator>& s2) Item 2. Clarify the widen/narrow operations on basic source character set. Item 3. Add unshift() member function to codecvt. Schwarz mentioned the impact on seek() (in a later proposal). Plauger felt that seek() did not need this change. Schwarz said there was otherwise no way to write the "magic" (i.e., unshifting) characters out at the right place. Myers argued that writes on seek() already happen (when a buffer is flushed) and this is very similar. Plauger argued that this change is a very bad idea-seeking and writing over a multibyte file is "asking for trouble". Motion by Schwarz/Brck: Move we amend the WP as described in N1029 = 96-0211. Motion passed X3J16: lots yes, 0 no, 1 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Schwarz presented the motions in N1028 = 96-0210. Item 1. Fix typedef of iostream. Item 2. Add typedef for wiostream. Item 3. Ensure initialisation of predefined streams. Schwarz noted that a footnote will be added encouraging implementors to initialise the streams "as early as possible". Item 4. Eliminate requirement that predefined streams be unbuffered. Schwarz explained that the phrase "unbuffered" should be removed from several locations because it misleads users. Plauger asked for confirmation that the streams are still synchronised. Myers said yes. Item 5. Add #include <iosfwd> to <ios> and remove the forward declarations. Item 6. Describe failure of iword and pword. Make iword and pword set badbit on failure. Schwarz noted that even if these functions fail, the WG agreed that they should return valid references (this is not reflected in the proposed WP changes). Myers noted that the returned reference must refer to zero-initialised memory. Schwarz agreed to correct the motion. Item 7. Fix definition of ios destructor. Item 8. Remove use of traits::newline and change get to avoid default argment. Item 9. Fix reference to failbit. Item 10. Fix a typo. Item 11. Replace traits::newline with widen('\n'). Item 12. Fix argument of setfill to match Stockholm resolution. Item 13. Correct template arguments in uses of basic_string. Item 14. Add declaration of fstream and wfstream typedefs. Item 15. close() should flush and use unshift(). Item 16. filebuf::seekoff should understand codecvt. Item 17. Change semantics of seek() for variable encodings. Schwarz withdrew the change to seek() that would have called unshift(). Myers asked where the wording was to ensure seek() flushed the buffer. Schwarz agreed to add it. Item 18. Specify filebuf::sync and add precondition for filebuf::imbue. Historically this is for throwing away lookahead characters but it doesn't really work so the semantics of sync() now make that clear. Schwarz noted that there was a missing phrase in the WP text proposed. Motion by Schwarz/Stanchfield: Move we amend the WP as described in N1028 = 96-0210 (without the change to the semantics of seek()). Motion passed X3J16: lots in yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Schwarz presented the motion in N1030 = 96-0212 that fixes a typo in Annex D. Motion by Schwarz/Brck: Move we amend the WP as specified in N1030 = 96-0212. Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. Library II (Becker) Becker presented a motion with the revised bitset constructor declaration. He noted the detailed text in the WP is correct but the synopsis is wrong. This motion corrects the synopsis. Motion by Allison/Brck: Move we amend the WP to correct the constructor synopsis for bitset. Motion passed X3J16: lots yes, 0 no, 0 abstain. Motion passed WG21: 5 yes, 0 no, 0 abstain. 7. Preparation of the new DWP Dawes asked Library I and II to meet and work on editorial and review actions for the WP. Lajoie asked that Core get together as well. Koenig described the review procedure he wants to have actioned. He will provide a baseline against which each editor should produce diffs. He described exactly the procedure he wants everyone to follow. He noted that differences on printed copies will be against the 7 November version made available at this meeting but in the post-Kona mailing-IF WE PRODUCE ONE-will be against the pre-Kona version. Plum clarified that we will produce review copies of the modified WP in PDF form on diskettes. Rumsby, Clamage and Koenig will deal with this translation. Allison asked that a paper copy be made available in the "office". There was a lot of discussion about the process at this meeting in terms of ensuring that what we end up voting on as the WP reflects the resolutions we have voted on today. Plum explained that we will exercise due diligence but ultimately we will be voting on one document which we must assume (or have checked) matches the resolutions. Corfield confirmed that all the resolutions will be documented in the minutes. Dawes asked who will edit the Annex clauses. Schwarz will edit Annex D. Benito will edit Annex C. The committees recessed at 17:00 on Wednesday. X3J16 reconvened at 9:20 on Thursday. Review public comments Clamage asked for a show of hands to count voting members of X3J16. 24 hands were raised. Clamage explained that the purpose of this session was to review and confirm the response to the public comments. Motion by Miller/Lajoie: Move we accept N1003 = 96-0185 as the response to public comments. Clamage asked for discussion and corrections. Motion to amend by Gafter/Welch: Move we amend N1003 = 96-0185 as described in in N1009 = 96-0191. The amendment passed X3J16: lots yes, 0 no. Gafter noted that one of the responses is no longer correct because of changes made to the working paper recently. The response concerns C Linkage (page 4, right hand column, item 4). Gafter suggested that it should read: "Rejected. All conforming C++ implementations are required to support extern "C" as defined by the standard, however an implementation is not required to support a C implementation that interoperates with it." Plum felt we should not attempt to go beyond what is necessary for our stated procedure. There is no normative requirement that the responses be correct. He noted that we may yet find more errors in our responses but we should not spend too much time on this. Koenig asked if we can provide a cover letter indicating that the response was to CD1 comments and that events since may have changed the status of the responses. There was agreement on this. Motion by Gafter/Koenig: Move we amend N1003 = 96-0185 as described above. The amendment passed X3J16: 17 yes, 1 no, 6 abstain. The formal vote on the amended motion was then taken. The amended motion passed X3J16: 27 yes, 0 no, 0 abstain. X3J16 recessed at 10:30 on Thursday. WG21+X3J16 reconvened at 9:15 on Friday. 9. Review of the meeting Clamage expressed his pleasure at how well the meeting has progressed. Applause. 9.1 Formal motions Plum clarified that the motions are advisory and therefore do not require the two-thirds plus one vote for X3J16. Koenig asked reviewers to sign the diff documents. Plum suggested that the minutes record the editor and reviewers for each clause. Koenig agreed to provide that information to the secretary. Plum said the intent is to show we followed due diligence. Koenig confirmed that he received edits from the nominated editors and that each clause was reviewed by one or more reviewers. Clause Editor Reviewer(s) intro Miller Nelson lex Miller Nelson basic Lajoie Unruh and others conv Adamczyk Miller expr Adamczyk Miller stmt Adamczyk Miller dcl Lajoie Unruh decl Adamczyk Miller class Lajoie Unruh derived Lajoie Unruh access Adamczyk Miller special Lajoie Unruh over Adamczyk Miller template Gibbons Unruh except Gibbons Brck cpp Plum Benito lib-intro Rumsby review group lib-support Rumsby review group lib-diagnostics Rumsby review group lib-utilities Rumsby review group lib-strings Rumsby review group lib-locales Schwarz Myers lib-containers Rumsby review group lib-iterators Rumsby review group lib-algorithms Rumsby review group lib-numerics Rumsby review group lib-iostreams Schwarz Myers gram automatic limits unchanged diff Plum Benito future Schwarz Myers extendid unchanged The "review group" was: Austern, Becker, Clamage, Colvin, Dawes, Henricson, Myers, Ward. Clamage asked Corfield to perform a roll call from the attendance list. Corfield confirmed there were 32 voting members of X3J16 and 5 WG21 delegations present. 1) Motion (to accept the WP) by Becker/Rumsby: Move we accept N1037 = 96-0219 as the current WP. Wilcox asked what we should do about typos, specifically that export is missing from the keyword list. Koenig said if we make changes we need to reissue the document or we can leave the changes until we correct other problems with the CD. Clamage said we should treat the WP as "the best we can do so far". Motion passed X3J16: 32 yes, 0 no. Motion passed WG21: 5 yes, 0 no. 2) Motion (to authorise convenor to submit the Committee Draft) by Brck/Lajoie: Move we authorise the WG21 convenor to submit the WP to SC22 for registration as a Committee Draft and for subsequent CD Ballot. Motion passed X3J16: 32 yes, 0 no. Motion passed WG21: 4 yes, 1 no. 3) Motion (to thank the host) by Corfield/Clamage: Move we thank Plum and Plum Hall for hosting the meeting Motion passed WG21+X3J16 by acclamation. 9.2 Review of action items, decisions made, and documents approved by the committee Clamage opened the committee of the whole. There were no action items. The committee approved N1037 = 96-0219 and decided to submit that as the second Committee Draft. 9.3 Issues delayed until Friday There were no items delayed until Friday. 10. Plans for the future 10.1 Next meeting The next meeting will be 9-14 March '97, Nashua, NH, hosted by Digital Equipment Corporation. Clamage noted that X3J16 will review public comments and determine its response by the end of that meeting in order to determine its position for the ISO ballot which closes shortly after the meeting. Plum said that WG21 is allowed to review the NB comments but not to make decisions at that point (because the ballot is still open). He said the agenda is very aggressive and there will need to be a US TAG meeting during the Nashua meeting. Welch suggested that a pre-meeting X3J16 get together would be useful to start reviewing the public review comments. Miller asked whether we knew if the CD would be available for the public review in electronic form. Plum said we had clear guidance for CD1 to distribute electronically however there is some uncertainty as to the status of this form of distribution. He said we don't know the answer. Clamage will follow this up with X3. Hartinger asked whether NBs can distribute copies within their committees. Clamage said yes. Plum noted that Rumsby's web and ftp site is within ISO guidelines because it is password protected and the password is restricted to members of the ISO/ANSI working groups. 10.2 Mailings Plum said X3J16 members are covered by X3 document distribution. He said there are about 14 or 15 WG21 members for whom he provides distribution as convenor. Plum noted that Ireland has joined SC22 as a P member. Miller said that a few documents distributed at this meeting are still missing from his collection. He noted the deadline for the post-meeting mailing is 29 November. Koenig asked what format the Working Paper should take in the post-meeting mailing. Clamage said that budgetary constraints mean that the WP cannot go in the post-Kona mailing and must go in the pre-Nashua mailing. Koenig asked whether that WP should be 1-up, 2-up or 4-up. Glassborow suggested the electronic copies be in all three formats. Miller noted that a 4-up copy might not photocopy as well as 2-up. Plum said the preference expressed at the last SC22 plenary was that large documents cease to be distributed on paper at some point. Plum said perhaps we should not distribute a paper copy of the WP since we already have to produce a paper copy of the CD. Lajoie said a few committee members do not have email or 'net access. Plum said the message from ISO appears to be that without web and ftp access, people will find it hard to participate in standardisation. Dawes wanted clarification that Rumsby can place the WP on the web site even when it is not part of a mailing. Unruh asked that both the CD without editorial boxes and the WP with editorial boxes be made available electronically. Rumsby said this would happen. Corfield asked Plum to clarify margins etc for A4/US Letter documents. Plum said authors should ensure their margins are wide enough to be printable on both forms of paper. There was a long discussion about document formats. Brck asked that the discussion be taken offline so we can get on with committee business. Lajoie asked about the procedure for handling public comments. Clamage said we have not decided on procedures yet. 10.3 Following meetings The following meetings are planned: 13-18 July '97, Guildford, UK, hosted by Programming Research Ltd 9-14 November '97, somewhere near Murray Hill, NJ, hosted by AT&T 8-13 March '98, Sophia Antipolis, France, Ilog 5-10 or 12-17 July '98, Rochester, NY, Xerox 8-13 November '98, somewhere near Menlo Park, CA, Sun Koenig said there were three alternatives for the November '97 meeting: Morristown (or a similar small town) New York (more interesting but more expensive) a location somewhere in the country Many members expressed opinons that the meeting should not be in New York. Clamage closed the committee of the whole. Motion by Brck/Charney: Move we adjourn. Motion passed WG21+X3J16: lots yes, 0 no. The committees adjourned at 10:10 on Friday. Appendix A - Attendance Name Affiliation M T W Th F Dawes, Beman Self V V V V V Henricson, Mats Self A A A A Myers, Nathan Self A A A A A O'Riordan, Martin Self A A A A A Koenig, Andrew AT&T Research V V V V V Becker, Pete Borland V V V V V Tooke, Simon Canada A A A A Charney, Reg Charney & Day V V V V V Comeau, Greg Comeau Computing A A A A A Ward, Judy Digital Equipment Corporation V V V V V Plauger, P.J. Dinkumware Ltd A A A A A Brck, Dag Dynasim AB V V V V V Andrews, Graham Edinburgh Portable Compilers V V V V Adamczyk, Steve Edison Design Group V V V V V Anderson, Mike Edison Design Group A A A A A Spicer, John Edison Design Group A A A A A Jonsson, Fredrik Ericsson V V V V V Gibbons, Bill Hewlett Packard V V V V V Lajoie, Josee IBM V V V V V Colvin, Greg IMR V V V V V Nelson, Clark Intel V V V V V Suto, Gyuszi Intel A A A A A Schwarz, Jerry Intrinsa V V V V V Andersson, Per Ipso Object Software V V V V V Stuessel, Marc IST GmbH V V Allison, Chuck LDS Church V V V V V Munch, Max Lex Hack & Associates A A A A A Stanchfield, Scott Metaware Inc V V V V Corfield, Sean Object Consultancy Services V V V V V Benito, John Perennial V V V V V Plum, Tom Plum Hall V V V V V Wilcox, Thomas R. Rational Software V V V V V Glassborow, Francis Richfords V V V V V le Moul, Philippe Rogue Wave Software A A A Smithey, Randy Rogue Wave Software V V V V Saks, Dan Saks & Associates V V V V V Wengler, Christian SET Software Consulting GmbH V V V Hartinger, Roland Siemens Nixdorf V V V V V Unruh, Erwin Siemens Nixdorf A A A A A Austern, Matthew Silicon Graphics V V V V V Miller, William M. Software Emancipation Tech V V V V V Ball, Mike Sun Microsystems V V V V Clamage, Steve Sun Microsystems A A A A A Gafter, Neal Sun Microsystems A A A V Rumsby, Steve UK A A A A A Baisley, Donald E. Unisys V V V V V Welch, Jim Watcom V V V V V Total attendance 44 44 46 38 44 Total votes 31 30 32 27 32 ___________________ end of document SC22 N2369 _________________________ | http://www.open-std.org/jtc1/sc22/open/n2369.htm | CC-MAIN-2018-26 | refinedweb | 8,936 | 65.22 |
I would like to use a weighted MSELoss function for image-to-image training. I want to specify a weight for each pixel in the target. Is there a quick/hacky way to do this, or do I need to write my own MSE loss function from scratch?
you can do this:
def weighted_mse_loss(input, target, weights):
out = input - target
out = out * weights.expand_as(out)
# expand_as because weights are prob not defined for mini-batch
loss = out.sum(0) # or sum over whatever dimensions
return loss
Oh, I see. There's no magic to the loss functions. You just calculate whatever loss you want using predefined Torch functions and then call backward on the loss. That's super easy. Thanks!
what if I want L2 Loss ?
just do it like this?
def weighted_mse_loss(input,target,weights):
out = (input-target)**2
out = out * weights.expand_as(out)
loss = out.sum(0) # or sum over whatever dimensions
return loss
right ?
@liygcheng yes. that's correct.
So long as all the computations are done on Variables, which will ensure the gradients can be computed.
Variables
Should the “weights” also be wrapped as a Variable in order for auto-grad to work?
Variable
Same question, what is your thoughts now ?
yes, the “weights” should also be wrapped as a Variable
Thanks. Actually, variablization must be done if we need them operate at gpu(s). | https://discuss.pytorch.org/t/pixelwise-weights-for-mseloss/1254 | CC-MAIN-2017-39 | refinedweb | 229 | 77.43 |
Based on a couple of fields in the ActiveRecord I need to do a series of calculations which will result in displaying a table (in the View) with around 10 columns and 15 rows.
I don't want to do these calculation in the View so I thought about creating a 2D Array to store the rows in the Model and then just access this array in the View to build a table to show.
However it seems I cannot store an Array in a Model's instance variable so am looking for suggestions on how to best handle this situation?
If there is a way to pass an Array from the Model to the View this would solve my problem.
Tried something like this but didnt work due to attr_accessor not handling arrays?
Model xxx
attr_accessor :row_hash
after_initialize do
makeTable
end
def makeTable
row_hash = Array.new
for i in 1..15 do
row_hash.push(i)
end
end
<% @xxx.row_hash.each do |r| %>
<%= r %>
<% end %>
I think you can make it work by adding
self to
row_hash
attr_accessor :row_hash after_initialize do makeTable end def makeTable self.row_hash = Array.new for i in 1..15 do self.row_hash.push(i) end end
Initializing
row_hash = Array.new will create a local variable called
row_hash so you need to call
self.row_hash= in order to access the instance attribute writer.
However, this is still a little odd to do in a model so there might be a better way to handle this overall. | https://codedump.io/share/Ul1ioEVgBVbi/1/where-best-to-calculate-and-create-a-large-table-to-be-shown-in-view | CC-MAIN-2021-25 | refinedweb | 250 | 73.58 |
Do you want to Converting Temperature Celsius Into Fahrenheit using the C++ Program? If yes then read this article to convert it successfully. Let’s start the conversion process below.
C++ Program For Converting Temperature Celsius Into Fahrenheit
Program Code
#include<iostream> using namespace std; int main() { //Ghanendra Yadav float cel, fah; cout<<"nEnter Temp in Celsius : "; cin>>cel; fah = (1.8 * cel) + 32; cout<<"nTemperature in Fahrenheit : "<< fah; return (0); }
Final Words
I hope this article about “C++ Program For Converting Temperature Celsius Into Fahrenheit” will be beneficial to you. If you having any issues during the program execution please let us know via the comment section. We will help you at any time. Please give a valuable feedback to encourage us. | https://codingdiksha.com/cpp-program-for-converting-temperature-celsius-into-fahrenheit/ | CC-MAIN-2022-05 | refinedweb | 123 | 56.66 |
Today,.
For example, let's assume that you've implemented a messaging application that allows users of your system to send messages to each other. Now, when user A sends a message to user B, you want to notify user B in real time. You may display a popup or an alert box that informs user B about the new message!
It's the perfect use-case to walk through the concept of broadcasting in Laravel, and that's what we'll implement in this article.
If you are wondering how the server could send notifications to the client, it's using sockets under the hood to accomplish it. Let's understand the basic flow of sockets before we dive deeper into the actual implementation.
Don't worry if it looks like too much in a single go; you will get the hang of it as we move through this article.
Next, let's have a look at the default broadcast configuration file at
config/broadcasting.php.
<', 'log'), /* |-------------------------------------------------------------------------- |'), ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ];
By default, Laravel supports multiple broadcast adapters in the core itself.
In this article, we are going to use the
Pusher broadcast adapter. For debugging purposes, you could also use the log adapter. Of course, if you're using the
log adapter, the client won't receive any event notifications, and it'll only be logged to the
laravel.log file.
From the next section onward, we'll right away dive into the actual implementation of the aforementioned use-case.
In broadcasting, there are different types of channels—public, private, and presence. When you want to broadcast your events publicly, it's the public channel that you are supposed to use. Conversely, the private channel is used when you want to restrict event notifications to certain private channels.
In our use-case, we want to notify users when they get a new message. And to be eligible to receive broadcast notifications, the user must be logged in. Thus, we'll need to use the private channel in our case.
Firstly, you need to enable the default Laravel authentication system so that features like registration, login and the like work out of the box. If you're not sure how to do that, the official documentation provides a quick insight into that.
As we're going to use the
Pusher third-party service as our web-socket server, you need to create an account with it and make sure you have the necessary API credentials with your post registration. If you're facing any trouble creating it, don't hesitate to ask me in the comment section.
Next, we need to install the Pusher PHP SDK so that our Laravel application can send broadcast notifications to the Pusher web-socket server.
In your Laravel application root, run the following command to install it as a composer package.
$composer require pusher/pusher-php-server "~3.0"
Now, let's change the broadcast configuration file to enable the Pusher adapter as our default broadcast driver.
<', 'pusher'), /* |-------------------------------------------------------------------------- |'), 'options' => [ 'cluster' => 'ap2', 'encrypted' => true ], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ];
As you can see, we've changed the default broadcast driver to Pusher. We've also added cluster and encrypted configuration options that you should have got from the Pusher account in the first place.
Also, it's fetching values from environment variables. So let's make sure that we do set the following variables in the
.env file properly.
BROADCAST_DRIVER=pusher PUSHER_APP_ID={YOUR_APP_ID} PUSHER_APP_KEY={YOUR_APP_KEY} PUSHER_APP_SECRET={YOUR_APP_SECRET}
Next, I had to make a few changes in a couple of core Laravel files in order to make it compatible with the latest Pusher SDK. Of course, I don't recommend making any changes in the core framework, but I'll just highlight what needs to be done.
Go ahead and open the
vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php file. Just replace the snippet
use Pusher; with
use Pusher\Pusher;.
Next, let's open the
vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastManager.php file and make a similar change in the following snippet.
return new PusherBroadcaster( new \Pusher\Pusher($config['key'], $config['secret'], $config['app_id'], Arr::get($config, 'options', [])) );
Finally, let's enable the broadcast service in
config/app.php by removing the comment in the following line.
App\Providers\BroadcastServiceProvider::class,
So far, we've installed server-specific libraries. In the next section, we'll go through client libraries that need to be installed as well.
In broadcasting, the responsibility of the client side is to subscribe to channels and listen for desired events. Under the hood, it accomplishes it by opening a new connection to the web-socket server.
Luckily, we don't have to implement any complex JavaScript stuff to achieve it as Laravel already provides a useful client library, Laravel Echo, that helps us deal with sockets on the client side. Also, it supports the Pusher service that we're going to use in this article.
You can install Laravel Echo using the NPM package manager. Of course, you need to install node and npm in the first place if you don't have them already. The rest is pretty simple, as shown in the following snippet.
$npm install laravel-echo
What we're interested in is the
node_modules/laravel-echo/dist/echo.js file that you should copy to
public/echo.js.
Yes, I understand, it's a bit of overkill to just get a single JavaScript file. If you don't want to go through this exercise, you can download the
echo.js file from my GitHub.
And with that, we're done with our client libraries setup.
Recall that we were talking about setting up an application that allows users of our application to send messages to each other. On the other hand, we'll send broadcast notifications to users that are logged in when they receive a new message from other users.
In this section, we'll create the our
Whenever you want to raise a custom event in Laravel, you should create a class for that event. Based on the type of event, Laravel reacts accordingly and takes the necessary actions.
If the event is a normal event, Laravel calls the associated listener classes. On the other hand, if the event is of broadcast type, Laravel sends that event to the web-socket server that's configured in the
config/broadcasting.php file.
As we're using the Pusher service in our example, Laravel will send events to the Pusher server.
Let's use the following artisan command to create a custom event class—
NewMessageNotification.
$php artisan make:event NewMessageNotification
That should create the
app/Events/NewMessageNotification.php class. Let's replace the contents of that file with the following.
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; use App\Message; class NewMessageNotification implements ShouldBroadcastNow { use SerializesModels; public $message; /** * Create a new event instance. * * @return void */ public function __construct(Message $message) { $this->message = $message; } /** * Get the channels the event should broadcast on. * * @return Channel|array */ public function broadcastOn() { return new PrivateChannel('user.'.$this->message->to); } }
The important thing to note is that the
NewMessageNotification class implements the
ShouldBroadcastNow interface. Thus, when we raise an event, Laravel knows that this event should be broadcast.
In fact, you could also implement the
ShouldBroadcast interface, and Laravel adds an event into the event queue. It'll be processed by the event queue worker when it gets a chance to do so. In our case, we want to broadcast it right away, and that's why we've used the
ShouldBroadcastNow interface.
In our case, we want to display a message the user has received, and thus we've passed the
Message model in the constructor argument. In this way, the data will be passed along with the event.
Next, there is the
broadcastOn method that defines the name of the channel on which the event will be broadcast. In our case, we've used the private channel as we want to restrict the event broadcast to logged-in users.
The
$this->message->to variable refers to the ID of the user to which the event will be broadcast. Thus, it effectively makes the channel name like
user.{USER_ID}.
In the case of private channels, the client must authenticate itself before establishing a connection with the web-socket server. It makes sure that events that are broadcast on private channels are sent to authenticated clients only. In our case, it means that only logged-in users will be able to subscribe to our channel
user.{USER_ID}.
If you're using the Laravel Echo client library for channel subscription, you're in luck! It automatically takes care of the authentication part, and you just need to define the channel routes.
Let's go ahead and add a route for our private channel in the
routes/channels.php file.
<?php /* |-------------------------------------------------------------------------- | Broadcast Channels |-------------------------------------------------------------------------- | | Here you may register all of the event broadcasting channels that your | application supports. The given channel authorization callbacks are | used to check if an authenticated user can listen to the channel. | */ Broadcast::channel('App.User.{id}', function ($user, $id) { return (int) $user->id === (int) $id; }); Broadcast::channel('user.{toUserId}', function ($user, $toUserId) { return $user->id == $toUserId; });
As you can see, we've defined the
user.{toUserId} route for our private channel.
The second argument of the channel method should be a closure function. Laravel automatically passes the currently logged-in user as the first argument of the closure function, and the second argument is usually fetched from the channel name.
When the client tries to subscribe to the private channel
user.{USER_ID}, the Laravel Echo library does the necessary authentication in the background using the XMLHttpRequest object, or more commonly known as XHR.
So far, we've finished with the setup, so let's go ahead and test it.
In this section, we'll create the files that are required to test our use-case.
Let's go ahead and create a controller file at
app/Http/Controllers/MessageController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Message; use App\Events\NewMessageNotification; use Illuminate\Support\Facades\Auth; class MessageController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $user_id = Auth::user()->id; $data = array('user_id' => $user_id); return view('broadcast', $data); } the
index method, we're using the
broadcast view, so let's create the
resources/views/broadcast.blade.php view file as well.
<>Test</title> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <div id="app"> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <!-- Collapsed Hamburger --> <button type="button" class="navbar-toggle collapsed" data- <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Branding Image --> <a class="navbar-brand123" href="{{ url('/') }}"> Test </a> </div> <div class="collapse navbar-collapse" id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul class="nav navbar-nav"> </ul> <!-- Right Side Of Navbar --> <ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @if (Auth::guest()) <li><a href="{{ route('login') }}">Login</a></li> <li><a href="{{ route('register') }}">Register</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data- {{ Auth::user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> </ul> </li> @endif </ul> </div> </div> </nav> <div class="content"> <div class="m-b-md"> New notification will be alerted realtime! </div> </div> </div> <!-- --> </body> </html>
And, of course, we need to add routes as well in the
routes/web.php file.
Route::get('message/index', 'MessageController@index'); Route::get('message/send', 'MessageController@send');
In the constructor method of the controller class, you can see that we've used the
auth middleware to make sure that controller methods are only accessed by logged-in users.
Next, there's the
index method that renders the
broadcast view. Let's pull in the most important code in the view file.
<!-- -->
Firstly, we load the necessary client libraries, Laravel Echo and Pusher, allowing us to open the web-socket connection to the Pusher web-socket server.
Next, we create the instance of Echo by providing Pusher as our broadcast adapter and other necessary Pusher-related information.
Moving further, we use the private method of Echo to subscribe to the private channel
user.{USER_ID}. As we discussed earlier, the client must authenticate itself before subscribing to the private channel. Thus the
Echo object performs the necessary authentication by sending the XHR in the background with necessary parameters. Finally, Laravel tries to find the
user.{USER_ID} route, and it should match the route that we've defined in the
routes/channels.php file.
If everything goes fine, you should have a web-socket connection open with the Pusher web-socket server, and it's listing events on the
user.{USER_ID} channel! From now on, we'll be able to receive all incoming events on this channel.
In our case, we want to listen for the
NewMessageNotification event and thus we've used the
listen method of the
Echo object to achieve it. To keep things simple, we'll just alert the message that we've received from the Pusher server.
So that was the setup for receiving events from the web-sockets server. Next, we'll go through the
send method in the controller file that raises the broadcast event.
Let's quickly pull in the code of the
send method. our case, we're going to notify logged-in users when they receive a new message. So we've tried to mimic that behavior in the
send method.
Next, we've used the
event helper function to raise the
NewMessageNotification event. Since the
NewMessageNotification event is of
ShouldBroadcastNow type, Laravel loads the default broadcast configuration from the
config/broadcasting.php file. Finally, it broadcasts the
NewMessageNotification event to the configured web-socket server on the
user.{USER_ID} channel.
In our case, the event will be broadcast to the Pusher web-socket server on the
user.{USER_ID} channel. If the ID of the recipient user is
1, the event will be broadcast over the
user.1 channel.
As we discussed earlier, we already have a setup that listens to events on this channel, so it should be able to receive this event, and the alert box is displayed to the user!
Let's go ahead and walk through how you are supposed to test the use-case that we've built so far.
Open the URL in your browser. If you're not logged in yet, you'll be redirected to the login screen. Once you're logged in, you should see the broadcast view that we defined earlier—nothing fancy yet.
In fact, Laravel has done a quite a bit of work in the background already for you. As we've enabled the
Pusher.logToConsole setting provided by the Pusher client library, it logs everything in the browser console for debugging purposes. Let's see what's being logged to the console when you access the page.
Pusher : State changed : initialized -> connecting Pusher : Connecting : {"transport":"ws","url":"wss://ws-ap2.pusher.com:443/app/c91c1b7e8c6ece46053b?protocol=7&client=js&version=4.1.0&flash=false"} Pusher : Connecting : {"transport":"xhr_streaming","url":""} Pusher : State changed : connecting -> connected with new socket ID 1386.68660 Pusher : Event sent : {"event":"pusher:subscribe","data":{"auth":"c91c1b7e8c6ece46053b:cd8b924580e2cbbd2977fd4ef0d41f1846eb358e9b7c327d89ff6bdc2de9082d","channel":"private-user.2"}} Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"private-user.2"} Pusher : No callbacks on private-user.2 for pusher:subscription_succeeded
It has opened the web-socket connection with the Pusher web-socket server and subscribed itself to listen to events on the private channel. Of course, you could have a different channel name in your case based on the ID of the user that you're logged in with. Now, let's keep this page open as we move to test the
send method.
Next, let's open the URL in the other tab or in a different browser. If you're going to use a different browser, you need to log in to be able to access that page.
As soon as you open the page, you should be able to see an alert message in the other tab at.
Let's navigate to the console to see what has just happened.
Pusher : Event recd : {"event":"App\\Events\\NewMessageNotification","data":{"message":{"id":57,"from":1,"to":2,"message":"Demo message from user 1 to user 2","created_at":"2018-01-13 07:10:10","updated_at":"2018-01-13 07:10:10"}},"channel":"private-user.2"}
As you can see, it tells you that you've just received the
App\Events\NewMessageNotification event from the Pusher web-socket server on the
private-user.2 channel.
In fact, you can see what's happening out there at the Pusher end as well. Go to your Pusher account and navigate to your application. Under the Debug Console, you should be able to see messages being logged.
And that brings us to the end of this article! Hopefully, it wasn't too much in a single go as I've tried to simplify things to the best of my knowledge.
Today, we went through one of the least discussed features of Laravel—broadcasting. It allows you to send real-time notifications using web sockets. Throughout the course of this article, we built a real-world example that demonstrated the aforementioned concept.
Yes I know, it's a lot of stuff to digest in a single article, so feel free to use the comment feed below should you find yourself in trouble during implementation.… | https://www.4elements.com/nl/blog/read/how-laravel-broadcasting-works/ | CC-MAIN-2019-18 | refinedweb | 3,012 | 55.54 |
gem5
/
public
/
gem5
/
refs/heads/master
/
.
/
ext
/
pybind11
/
docs
/
changelog.rst
blob: bb5457eec15c7409c24e067a8187b6f33b1cd58d [
file
] [
log
] [
blame
]
.. _changelog:
Changelog
#########
Starting with version 1.8.0, pybind11 releases use a `semantic versioning
<>`_ policy.
IN DEVELOPMENT
--------------
v2.8.1 (Oct 27, 2021)
---------------------
Changes and additions:
* The simple namespace creation shortcut added in 2.8.0 was deprecated due to
usage of CPython internal API, and will be removed soon. Use
``py::module_::import("types").attr("SimpleNamespace")``.
`#3374 <>`_
* Add C++ Exception type to throw and catch ``AttributeError``. Useful for
defining custom ``__setattr__`` and ``__getattr__`` methods.
`#3387 <>`_
Fixes:
* Fixed the potential for dangling references when using properties with
``std::optional`` types.
`#3376 <>`_
* Modernize usage of ``PyCodeObject`` on Python 3.9+ (moving toward support for
Python 3.11a1)
`#3368 <>`_
* A long-standing bug in ``eigen.h`` was fixed (originally PR #3343). The bug
was unmasked by newly added ``static_assert``'s in the Eigen 3.4.0 release.
`#3352 <>`_
* Support multiple raw inclusion of CMake helper files (Conan.io does this for
multi-config generators).
`#3420 <>`_
* Fix harmless warning on upcoming CMake 3.22.
`#3368 <>`_
* Fix 2.8.0 regression with MSVC 2017 + C++17 mode + Python 3.
`#3407 <>`_
* Fix 2.8.0 regression that caused undefined behavior (typically
segfaults) in ``make_key_iterator``/``make_value_iterator`` if dereferencing
the iterator returned a temporary value instead of a reference.
`#3348 <>`_
v2.8.0 (Oct 4, 2021)
--------------------
New features:
* Added ``py::raise_from`` to enable chaining exceptions.
`#3215 <>`_
* Allow exception translators to be optionally registered local to a module
instead of applying globally across all pybind11 modules. Use
``register_local_exception_translator(ExceptionTranslator&& translator)``
instead of ``register_exception_translator(ExceptionTranslator&&
translator)`` to keep your exception remapping code local to the module.
`#2650 <>`_
* Add ``make_simple_namespace`` function for instantiating Python
``SimpleNamespace`` objects. **Deprecated in 2.8.1.**
`#2840 <>`_
* ``pybind11::scoped_interpreter`` and ``initialize_interpreter`` have new
arguments to allow ``sys.argv`` initialization.
`#2341 <>`_
* Allow Python builtins to be used as callbacks in CPython.
`#1413 <>`_
* Added ``view`` to view arrays with a different datatype.
`#987 <>`_
* Implemented ``reshape`` on arrays.
`#984 <>`_
* Enable defining custom ``__new__`` methods on classes by fixing bug
preventing overriding methods if they have non-pybind11 siblings.
`#3265 <>`_
* Add ``make_value_iterator()``, and fix ``make_key_iterator()`` to return
references instead of copies.
`#3293 <>`_
* Improve the classes generated by ``bind_map``: `#3310 <>`_
* Change ``.items`` from an iterator to a dictionary view.
* Add ``.keys`` and ``.values`` (both dictionary views).
* Allow ``__contains__`` to take any object.
* ``pybind11::custom_type_setup`` was added, for customizing the
``PyHeapTypeObject`` corresponding to a class, which may be useful for
enabling garbage collection support, among other things.
`#3287 <>`_
Changes:
* Set ``__file__`` constant when running ``eval_file`` in an embedded interpreter.
`#3233 <>`_
* Python objects and (C++17) ``std::optional`` now accepted in ``py::slice``
constructor.
`#1101 <>`_
* The pybind11 proxy types ``str``, ``bytes``, ``bytearray``, ``tuple``,
``list`` now consistently support passing ``ssize_t`` values for sizes and
indexes. Previously, only ``size_t`` was accepted in several interfaces.
`#3219 <>`_
* Avoid evaluating ``PYBIND11_TLS_REPLACE_VALUE`` arguments more than once.
`#3290 <>`_
Fixes:
* Bug fix: enum value's ``__int__`` returning non-int when underlying type is
bool or of char type.
`#1334 <>`_
* Fixes bug in setting error state in Capsule's pointer methods.
`#3261 <>`_
* A long-standing memory leak in ``py::cpp_function::initialize`` was fixed.
`#3229 <>`_
* Fixes thread safety for some ``pybind11::type_caster`` which require lifetime
extension, such as for ``std::string_view``.
`#3237 <>`_
* Restore compatibility with gcc 4.8.4 as distributed by ubuntu-trusty, linuxmint-17.
`#3270 <>`_
Build system improvements:
* Fix regression in CMake Python package config: improper use of absolute path.
`#3144 <>`_
* Cached Python version information could become stale when CMake was re-run
with a different Python version. The build system now detects this and
updates this information.
`#3299 <>`_
* Specified UTF8-encoding in setup.py calls of open().
`#3137 <>`_
* Fix a harmless warning from CMake 3.21 with the classic Python discovery.
`#3220 <>`_
* Eigen repo and version can now be specified as cmake options.
`#3324 <>`_
Backend and tidying up:
* Reduced thread-local storage required for keeping alive temporary data for
type conversion to one key per ABI version, rather than one key per extension
module. This makes the total thread-local storage required by pybind11 2
keys per ABI version.
`#3275 <>`_
* Optimize NumPy array construction with additional moves.
`#3183 <>`_
* Conversion to ``std::string`` and ``std::string_view`` now avoids making an
extra copy of the data on Python >= 3.3.
`#3257 <>`_
* Remove const modifier from certain C++ methods on Python collections
(``list``, ``set``, ``dict``) such as (``clear()``, ``append()``,
``insert()``, etc...) and annotated them with ``py-non-const``.
* Enable readability ``clang-tidy-const-return`` and remove useless consts.
`#3254 <>`_
`#3194 <>`_
* The clang-tidy ``google-explicit-constructor`` option was enabled.
`#3250 <>`_
* Mark a pytype move constructor as noexcept (perf).
`#3236 <>`_
* Enable clang-tidy check to guard against inheritance slicing.
`#3210 <>`_
* Legacy warning suppression pragma were removed from eigen.h. On Unix
platforms, please use -isystem for Eigen include directories, to suppress
compiler warnings originating from Eigen headers. Note that CMake does this
by default. No adjustments are needed for Windows.
`#3198 <>`_
* Format pybind11 with isort consistent ordering of imports
`#3195 <>`_
* The warnings-suppression "pragma clamp" at the top/bottom of pybind11 was
removed, clearing the path to refactoring and IWYU cleanup.
`#3186 <>`_
* Enable most bugprone checks in clang-tidy and fix the found potential bugs
and poor coding styles.
`#3166 <>`_
* Add ``clang-tidy-readability`` rules to make boolean casts explicit improving
code readability. Also enabled other misc and readability clang-tidy checks.
`#3148 <>`_
* Move object in ``.pop()`` for list.
`#3116 <>`_
v2.7.1 (Aug 3, 2021)
---------------------
Minor missing functionality added:
* Allow Python builtins to be used as callbacks in CPython.
`#1413 <>`_
Bug fixes:
* Fix regression in CMake Python package config: improper use of absolute path.
`#3144 <>`_
* Fix Mingw64 and add to the CI testing matrix.
`#3132 <>`_
* Specified UTF8-encoding in setup.py calls of open().
`#3137 <>`_
* Add clang-tidy-readability rules to make boolean casts explicit improving
code readability. Also enabled other misc and readability clang-tidy checks.
`#3148 <>`_
* Move object in ``.pop()`` for list.
`#3116 <>`_
Backend and tidying up:
* Removed and fixed warning suppressions.
`#3127 <>`_
`#3129 <>`_
`#3135 <>`_
`#3141 <>`_
`#3142 <>`_
`#3150 <>`_
`#3152 <>`_
`#3160 <>`_
`#3161 <>`_
v2.7.0 (Jul 16, 2021)
---------------------
New features:
* Enable ``py::implicitly_convertible<py::none, ...>`` for
``py::class_``-wrapped types.
`#3059 <>`_
* Allow function pointer extraction from overloaded functions.
`#2944 <>`_
* NumPy: added ``.char_()`` to type which gives the NumPy public ``char``
result, which also distinguishes types by bit length (unlike ``.kind()``).
`#2864 <>`_
* Add ``pybind11::bytearray`` to manipulate ``bytearray`` similar to ``bytes``.
`#2799 <>`_
* ``pybind11/stl/filesystem.h`` registers a type caster that, on C++17/Python
3.6+, converts ``std::filesystem::path`` to ``pathlib.Path`` and any
``os.PathLike`` to ``std::filesystem::path``.
`#2730 <>`_
* A ``PYBIND11_VERSION_HEX`` define was added, similar to ``PY_VERSION_HEX``.
`#3120 <>`_
Changes:
* ``py::str`` changed to exclusively hold ``PyUnicodeObject``. Previously
``py::str`` could also hold ``bytes``, which is probably surprising, was
never documented, and can mask bugs (e.g. accidental use of ``py::str``
instead of ``py::bytes``).
`#2409 <>`_
* Add a safety guard to ensure that the Python GIL is held when C++ calls back
into Python via ``object_api<>::operator()`` (e.g. ``py::function``
``__call__``). (This feature is available for Python 3.6+ only.)
`#2919 <>`_
* Catch a missing ``self`` argument in calls to ``__init__()``.
`#2914 <>`_
* Use ``std::string_view`` if available to avoid a copy when passing an object
to a ``std::ostream``.
`#3042 <>`_
* An important warning about thread safety was added to the ``iostream.h``
documentation; attempts to make ``py::scoped_ostream_redirect`` thread safe
have been removed, as it was only partially effective.
`#2995 <>`_
Fixes:
* Performance: avoid unnecessary strlen calls.
`#3058 <>`_
* Fix auto-generated documentation string when using ``const T`` in
``pyarray_t``.
`#3020 <>`_
* Unify error messages thrown by ``simple_collector``/``unpacking_collector``.
`#3013 <>`_
* ``pybind11::builtin_exception`` is now explicitly exported, which means the
types included/defined in different modules are identical, and exceptions
raised in different modules can be caught correctly. The documentation was
updated to explain that custom exceptions that are used across module
boundaries need to be explicitly exported as well.
`#2999 <>`_
* Fixed exception when printing UTF-8 to a ``scoped_ostream_redirect``.
`#2982 <>`_
* Pickle support enhancement: ``setstate`` implementation will attempt to
``setattr`` ``__dict__`` only if the unpickled ``dict`` object is not empty,
to not force use of ``py::dynamic_attr()`` unnecessarily.
`#2972 <>`_
* Allow negative timedelta values to roundtrip.
`#2870 <>`_
* Fix unchecked errors could potentially swallow signals/other exceptions.
`#2863 <>`_
* Add null pointer check with ``std::localtime``.
`#2846 <>`_
* Fix the ``weakref`` constructor from ``py::object`` to create a new
``weakref`` on conversion.
`#2832 <>`_
* Avoid relying on exceptions in C++17 when getting a ``shared_ptr`` holder
from a ``shared_from_this`` class.
`#2819 <>`_
* Allow the codec's exception to be raised instead of :code:`RuntimeError` when
casting from :code:`py::str` to :code:`std::string`.
`#2903 <>`_
Build system improvements:
* In ``setup_helpers.py``, test for platforms that have some multiprocessing
features but lack semaphores, which ``ParallelCompile`` requires.
`#3043 <>`_
* Fix ``pybind11_INCLUDE_DIR`` in case ``CMAKE_INSTALL_INCLUDEDIR`` is
absolute.
`#3005 <>`_
* Fix bug not respecting ``WITH_SOABI`` or ``WITHOUT_SOABI`` to CMake.
`#2938 <>`_
* Fix the default ``Pybind11Extension`` compilation flags with a Mingw64 python.
`#2921 <>`_
* Clang on Windows: do not pass ``/MP`` (ignored flag).
`#2824 <>`_
* ``pybind11.setup_helpers.intree_extensions`` can be used to generate
``Pybind11Extension`` instances from cpp files placed in the Python package
source tree.
`#2831 <>`_
Backend and tidying up:
* Enable clang-tidy performance, readability, and modernization checks
throughout the codebase to enforce best coding practices.
`#3046 <>`_,
`#3049 <>`_,
`#3051 <>`_,
`#3052 <>`_,
`#3080 <>`_, and
`#3094 <>`_
* Checks for common misspellings were added to the pre-commit hooks.
`#3076 <>`_
* Changed ``Werror`` to stricter ``Werror-all`` for Intel compiler and fixed
minor issues.
`#2948 <>`_
* Fixed compilation with GCC < 5 when the user defines ``_GLIBCXX_USE_CXX11_ABI``.
`#2956 <>`_
* Added nox support for easier local testing and linting of contributions.
`#3101 <>`_ and
`#3121 <>`_
* Avoid RTD style issue with docutils 0.17+.
`#3119 <>`_
* Support pipx run, such as ``pipx run pybind11 --include`` for a quick compile.
`#3117 <>`_
v2.6.2 (Jan 26, 2021)
---------------------
Minor missing functionality added:
* enum: add missing Enum.value property.
`#2739 <>`_
* Allow thread termination to be avoided during shutdown for CPython 3.7+ via
``.disarm`` for ``gil_scoped_acquire``/``gil_scoped_release``.
`#2657 <>`_
Fixed or improved behavior in a few special cases:
* Fix bug where the constructor of ``object`` subclasses would not throw on
being passed a Python object of the wrong type.
`#2701 <>`_
* The ``type_caster`` for integers does not convert Python objects with
``__int__`` anymore with ``noconvert`` or during the first round of trying
overloads.
`#2698 <>`_
* When casting to a C++ integer, ``__index__`` is always called and not
considered as conversion, consistent with Python 3.8+.
`#2801 <>`_
Build improvements:
* Setup helpers: ``extra_compile_args`` and ``extra_link_args`` automatically set by
Pybind11Extension are now prepended, which allows them to be overridden
by user-set ``extra_compile_args`` and ``extra_link_args``.
`#2808 <>`_
* Setup helpers: Don't trigger unused parameter warning.
`#2735 <>`_
* CMake: Support running with ``--warn-uninitialized`` active.
`#2806 <>`_
* CMake: Avoid error if included from two submodule directories.
`#2804 <>`_
* CMake: Fix ``STATIC`` / ``SHARED`` being ignored in FindPython mode.
`#2796 <>`_
* CMake: Respect the setting for ``CMAKE_CXX_VISIBILITY_PRESET`` if defined.
`#2793 <>`_
* CMake: Fix issue with FindPython2/FindPython3 not working with ``pybind11::embed``.
`#2662 <>`_
* CMake: mixing local and installed pybind11's would prioritize the installed
one over the local one (regression in 2.6.0).
`#2716 <>`_
Bug fixes:
* Fixed segfault in multithreaded environments when using
``scoped_ostream_redirect``.
`#2675 <>`_
* Leave docstring unset when all docstring-related options are disabled, rather
than set an empty string.
`#2745 <>`_
* The module key in builtins that pybind11 uses to store its internals changed
from std::string to a python str type (more natural on Python 2, no change on
Python 3).
`#2814 <>`_
* Fixed assertion error related to unhandled (later overwritten) exception in
CPython 3.8 and 3.9 debug builds.
`#2685 <>`_
* Fix ``py::gil_scoped_acquire`` assert with CPython 3.9 debug build.
`#2683 <>`_
* Fix issue with a test failing on pytest 6.2.
`#2741 <>`_
Warning fixes:
* Fix warning modifying constructor parameter 'flag' that shadows a field of
'set_flag' ``[-Wshadow-field-in-constructor-modified]``.
`#2780 <>`_
* Suppressed some deprecation warnings about old-style
``__init__``/``__setstate__`` in the tests.
`#2759 <>`_
Valgrind work:
* Fix invalid access when calling a pybind11 ``__init__`` on a non-pybind11
class instance.
`#2755 <>`_
* Fixed various minor memory leaks in pybind11's test suite.
`#2758 <>`_
* Resolved memory leak in cpp_function initialization when exceptions occurred.
`#2756 <>`_
* Added a Valgrind build, checking for leaks and memory-related UB, to CI.
`#2746 <>`_
Compiler support:
* Intel compiler was not activating C++14 support due to a broken define.
`#2679 <>`_
* Support ICC and NVIDIA HPC SDK in C++17 mode.
`#2729 <>`_
* Support Intel OneAPI compiler (ICC 20.2) and add to CI.
`#2573 <>`_
v2.6.1 (Nov 11, 2020)
---------------------
* ``py::exec``, ``py::eval``, and ``py::eval_file`` now add the builtins module
as ``"__builtins__"`` to their ``globals`` argument, better matching ``exec``
and ``eval`` in pure Python.
`#2616 <>`_
* ``setup_helpers`` will no longer set a minimum macOS version higher than the
current version.
`#2622 <>`_
* Allow deleting static properties.
`#2629 <>`_
* Seal a leak in ``def_buffer``, cleaning up the ``capture`` object after the
``class_`` object goes out of scope.
`#2634 <>`_
* ``pybind11_INCLUDE_DIRS`` was incorrect, potentially causing a regression if
it was expected to include ``PYTHON_INCLUDE_DIRS`` (please use targets
instead).
`#2636 <>`_
* Added parameter names to the ``py::enum_`` constructor and methods, avoiding
``arg0`` in the generated docstrings.
`#2637 <>`_
* Added ``needs_recompile`` optional function to the ``ParallelCompiler``
helper, to allow a recompile to be skipped based on a user-defined function.
`#2643 <>`_
v2.6.0 (Oct 21, 2020)
---------------------
See :ref:`upgrade-guide-2.6` for help upgrading to the new version.
New features:
* Keyword-only arguments supported in Python 2 or 3 with ``py::kw_only()``.
`#2100 <>`_
* Positional-only arguments supported in Python 2 or 3 with ``py::pos_only()``.
`#2459 <>`_
* ``py::is_final()`` class modifier to block subclassing (CPython only).
`#2151 <>`_
* Added ``py::prepend()``, allowing a function to be placed at the beginning of
the overload chain.
`#1131 <>`_
* Access to the type object now provided with ``py::type::of<T>()`` and
``py::type::of(h)``.
`#2364 <>`_
* Perfect forwarding support for methods.
`#2048 <>`_
* Added ``py::error_already_set::discard_as_unraisable()``.
`#2372 <>`_
* ``py::hash`` is now public.
`#2217 <>`_
* ``py::class_<union_type>`` is now supported. Note that writing to one data
member of the union and reading another (type punning) is UB in C++. Thus
pybind11-bound enums should never be used for such conversions.
`#2320 <>`_.
* Classes now check local scope when registering members, allowing a subclass
to have a member with the same name as a parent (such as an enum).
`#2335 <>`_
Code correctness features:
* Error now thrown when ``__init__`` is forgotten on subclasses.
`#2152 <>`_
* Throw error if conversion to a pybind11 type if the Python object isn't a
valid instance of that type, such as ``py::bytes(o)`` when ``py::object o``
isn't a bytes instance.
`#2349 <>`_
* Throw if conversion to ``str`` fails.
`#2477 <>`_
API changes:
* ``py::module`` was renamed ``py::module_`` to avoid issues with C++20 when
used unqualified, but an alias ``py::module`` is provided for backward
compatibility.
`#2489 <>`_
* Public constructors for ``py::module_`` have been deprecated; please use
``pybind11::module_::create_extension_module`` if you were using the public
constructor (fairly rare after ``PYBIND11_MODULE`` was introduced).
`#2552 <>`_
* ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function replaced by
correctly-named ``PYBIND11_OVERRIDE*`` and ``get_override``, fixing
inconsistencies in the presence of a closing ``;`` in these macros.
``get_type_overload`` is deprecated.
`#2325 <>`_
Packaging / building improvements:
* The Python package was reworked to be more powerful and useful.
`#2433 <>`_
* :ref:`build-setuptools` is easier thanks to a new
``pybind11.setup_helpers`` module, which provides utilities to use
setuptools with pybind11. It can be used via PEP 518, ``setup_requires``,
or by directly importing or copying ``setup_helpers.py`` into your project.
* CMake configuration files are now included in the Python package. Use
``pybind11.get_cmake_dir()`` or ``python -m pybind11 --cmakedir`` to get
the directory with the CMake configuration files, or include the
site-packages location in your ``CMAKE_MODULE_PATH``. Or you can use the
new ``pybind11[global]`` extra when you install ``pybind11``, which
installs the CMake files and headers into your base environment in the
standard location.
* ``pybind11-config`` is another way to write ``python -m pybind11`` if you
have your PATH set up.
* Added external typing support to the helper module, code from
``import pybind11`` can now be type checked.
`#2588 <>`_
* Minimum CMake required increased to 3.4.
`#2338 <>`_ and
`#2370 <>`_
* Full integration with CMake’s C++ standard system and compile features
replaces ``PYBIND11_CPP_STANDARD``.
* Generated config file is now portable to different Python/compiler/CMake
versions.
* Virtual environments prioritized if ``PYTHON_EXECUTABLE`` is not set
(``venv``, ``virtualenv``, and ``conda``) (similar to the new FindPython
mode).
* Other CMake features now natively supported, like
``CMAKE_INTERPROCEDURAL_OPTIMIZATION``, ``set(CMAKE_CXX_VISIBILITY_PRESET
hidden)``.
* ``CUDA`` as a language is now supported.
* Helper functions ``pybind11_strip``, ``pybind11_extension``,
``pybind11_find_import`` added, see :doc:`cmake/index`.
* Optional :ref:`find-python-mode` and :ref:`nopython-mode` with CMake.
`#2370 <>`_
* Uninstall target added.
`#2265 <>`_ and
`#2346 <>`_
* ``pybind11_add_module()`` now accepts an optional ``OPT_SIZE`` flag that
switches the binding target to size-based optimization if the global build
type can not always be fixed to ``MinSizeRel`` (except in debug mode, where
optimizations remain disabled). ``MinSizeRel`` or this flag reduces binary
size quite substantially (~25% on some platforms).
`#2463 <>`_
Smaller or developer focused features and fixes:
* Moved ``mkdoc.py`` to a new repo, `pybind11-mkdoc`_. There are no longer
submodules in the main repo.
* ``py::memoryview`` segfault fix and update, with new
``py::memoryview::from_memory`` in Python 3, and documentation.
`#2223 <>`_
* Fix for ``buffer_info`` on Python 2.
`#2503 <>`_
* If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to
``None``.
`#2291 <>`_
* ``py::ellipsis`` now also works on Python 2.
`#2360 <>`_
* Pointer to ``std::tuple`` & ``std::pair`` supported in cast.
`#2334 <>`_
* Small fixes in NumPy support. ``py::array`` now uses ``py::ssize_t`` as first
argument type.
`#2293 <>`_
* Added missing signature for ``py::array``.
`#2363 <>`_
* ``unchecked_mutable_reference`` has access to operator ``()`` and ``[]`` when
const.
`#2514 <>`_
* ``py::vectorize`` is now supported on functions that return void.
`#1969 <>`_
* ``py::capsule`` supports ``get_pointer`` and ``set_pointer``.
`#1131 <>`_
* Fix crash when different instances share the same pointer of the same type.
`#2252 <>`_
* Fix for ``py::len`` not clearing Python's error state when it fails and throws.
`#2575 <>`_
* Bugfixes related to more extensive testing, new GitHub Actions CI.
`#2321 <>`_
* Bug in timezone issue in Eastern hemisphere midnight fixed.
`#2438 <>`_
* ``std::chrono::time_point`` now works when the resolution is not the same as
the system.
`#2481 <>`_
* Bug fixed where ``py::array_t`` could accept arrays that did not match the
requested ordering.
`#2484 <>`_
* Avoid a segfault on some compilers when types are removed in Python.
`#2564 <>`_
* ``py::arg::none()`` is now also respected when passing keyword arguments.
`#2611 <>`_
* PyPy fixes, PyPy 7.3.x now supported, including PyPy3. (Known issue with
PyPy2 and Windows `#2596 <>`_).
`#2146 <>`_
* CPython 3.9.0 workaround for undefined behavior (macOS segfault).
`#2576 <>`_
* CPython 3.9 warning fixes.
`#2253 <>`_
* Improved C++20 support, now tested in CI.
`#2489 <>`_
`#2599 <>`_
* Improved but still incomplete debug Python interpreter support.
`#2025 <>`_
* NVCC (CUDA 11) now supported and tested in CI.
`#2461 <>`_
* NVIDIA PGI compilers now supported and tested in CI.
`#2475 <>`_
* At least Intel 18 now explicitly required when compiling with Intel.
`#2577 <>`_
* Extensive style checking in CI, with `pre-commit`_ support. Code
modernization, checked by clang-tidy.
* Expanded docs, including new main page, new installing section, and CMake
helpers page, along with over a dozen new sections on existing pages.
* In GitHub, new docs for contributing and new issue templates.
.. _pre-commit:
.. _pybind11-mkdoc:
v2.5.0 (Mar 31, 2020)
-----------------------------------------------------
* Use C++17 fold expressions in type casters, if available. This can
improve performance during overload resolution when functions have
multiple arguments.
`#2043 <>`_.
* Changed include directory resolution in ``pybind11/__init__.py``
and installation in ``setup.py``. This fixes a number of open issues
where pybind11 headers could not be found in certain environments.
`#1995 <>`_.
* C++20 ``char8_t`` and ``u8string`` support. `#2026
<>`_.
* CMake: search for Python 3.9. `bb9c91
<>`_.
* Fixes for MSYS-based build environments.
`#2087 <>`_,
`#2053 <>`_.
* STL bindings for ``std::vector<...>::clear``. `#2074
<>`_.
* Read-only flag for ``py::buffer``. `#1466
<>`_.
* Exception handling during module initialization.
`bf2b031 <>`_.
* Support linking against a CPython debug build.
`#2025 <>`_.
* Fixed issues involving the availability and use of aligned ``new`` and
``delete``. `#1988 <>`_,
`759221 <>`_.
* Fixed a resource leak upon interpreter shutdown.
`#2020 <>`_.
* Fixed error handling in the boolean caster.
`#1976 <>`_.
v2.4.3 (Oct 15, 2019)
-----------------------------------------------------
* Adapt pybind11 to a C API convention change in Python 3.8. `#1950
<>`_.
v2.4.2 (Sep 21, 2019)
-----------------------------------------------------
* Replaced usage of a C++14 only construct. `#1929
<>`_.
* Made an ifdef future-proof for Python >= 4. `f3109d
<>`_.
v2.4.1 (Sep 20, 2019)
-----------------------------------------------------
* Fixed a problem involving implicit conversion from enumerations to integers
on Python 3.8. `#1780 <>`_.
v2.4.0 (Sep 19, 2019)
-----------------------------------------------------
* Try harder to keep pybind11-internal data structures separate when there
are potential ABI incompatibilities. Fixes crashes that occurred when loading
multiple pybind11 extensions that were e.g. compiled by GCC (libstdc++)
and Clang (libc++).
`#1588 <>`_ and
`c9f5a <>`_.
* Added support for ``__await__``, ``__aiter__``, and ``__anext__`` protocols.
`#1842 <>`_.
* ``pybind11_add_module()``: don't strip symbols when compiling in
``RelWithDebInfo`` mode. `#1980
<>`_.
* ``enum_``: Reproduce Python behavior when comparing against invalid values
(e.g. ``None``, strings, etc.). Add back support for ``__invert__()``.
`#1912 <>`_,
`#1907 <>`_.
* List insertion operation for ``py::list``.
Added ``.empty()`` to all collection types.
Added ``py::set::contains()`` and ``py::dict::contains()``.
`#1887 <>`_,
`#1884 <>`_,
`#1888 <>`_.
* ``py::details::overload_cast_impl`` is available in C++11 mode, can be used
like ``overload_cast`` with an additional set of parentheses.
`#1581 <>`_.
* Fixed ``get_include()`` on Conda.
`#1877 <>`_.
* ``stl_bind.h``: negative indexing support.
`#1882 <>`_.
* Minor CMake fix to add MinGW compatibility.
`#1851 <>`_.
* GIL-related fixes.
`#1836 <>`_,
`8b90b <>`_.
* Other very minor/subtle fixes and improvements.
`#1329 <>`_,
`#1910 <>`_,
`#1863 <>`_,
`#1847 <>`_,
`#1890 <>`_,
`#1860 <>`_,
`#1848 <>`_,
`#1821 <>`_,
`#1837 <>`_,
`#1833 <>`_,
`#1748 <>`_,
`#1852 <>`_.
v2.3.0 (June 11, 2019)
-----------------------------------------------------
* Significantly reduced module binary size (10-20%) when compiled in C++11 mode
with GCC/Clang, or in any mode with MSVC. Function signatures are now always
precomputed at compile time (this was previously only available in C++14 mode
for non-MSVC compilers).
`#934 <>`_.
* Add basic support for tag-based static polymorphism, where classes
provide a method to returns the desired type of an instance.
`#1326 <>`_.
* Python type wrappers (``py::handle``, ``py::object``, etc.)
now support map Python's number protocol onto C++ arithmetic
operators such as ``operator+``, ``operator/=``, etc.
`#1511 <>`_.
* A number of improvements related to enumerations:
1. The ``enum_`` implementation was rewritten from scratch to reduce
code bloat. Rather than instantiating a full implementation for each
enumeration, most code is now contained in a generic base class.
`#1511 <>`_.
2. The ``value()`` method of ``py::enum_`` now accepts an optional
docstring that will be shown in the documentation of the associated
enumeration. `#1160 <>`_.
3. check for already existing enum value and throw an error if present.
`#1453 <>`_.
* Support for over-aligned type allocation via C++17's aligned ``new``
statement. `#1582 <>`_.
* Added ``py::ellipsis()`` method for slicing of multidimensional NumPy arrays
`#1502 <>`_.
* Numerous Improvements to the ``mkdoc.py`` script for extracting documentation
from C++ header files.
`#1788 <>`_.
* ``pybind11_add_module()``: allow including Python as a ``SYSTEM`` include path.
`#1416 <>`_.
* ``pybind11/stl.h`` does not convert strings to ``vector<string>`` anymore.
`#1258 <>`_.
* Mark static methods as such to fix auto-generated Sphinx documentation.
`#1732 <>`_.
* Re-throw forced unwind exceptions (e.g. during pthread termination).
`#1208 <>`_.
* Added ``__contains__`` method to the bindings of maps (``std::map``,
``std::unordered_map``).
`#1767 <>`_.
* Improvements to ``gil_scoped_acquire``.
`#1211 <>`_.
* Type caster support for ``std::deque<T>``.
`#1609 <>`_.
* Support for ``std::unique_ptr`` holders, whose deleters differ between a base and derived
class. `#1353 <>`_.
* Construction of STL array/vector-like data structures from
iterators. Added an ``extend()`` operation.
`#1709 <>`_,
* CMake build system improvements for projects that include non-C++
files (e.g. plain C, CUDA) in ``pybind11_add_module`` et al.
`#1678 <>`_.
* Fixed asynchronous invocation and deallocation of Python functions
wrapped in ``std::function``.
`#1595 <>`_.
* Fixes regarding return value policy propagation in STL type casters.
`#1603 <>`_.
* Fixed scoped enum comparisons.
`#1571 <>`_.
* Fixed iostream redirection for code that releases the GIL.
`#1368 <>`_,
* A number of CI-related fixes.
`#1757 <>`_,
`#1744 <>`_,
`#1670 <>`_.
v2.2.4 (September 11, 2018)
-----------------------------------------------------
* Use new Python 3.7 Thread Specific Storage (TSS) implementation if available.
`#1454 <>`_,
`#1517 <>`_.
* Fixes for newer MSVC versions and C++17 mode.
`#1347 <>`_,
`#1462 <>`_.
* Propagate return value policies to type-specific casters
when casting STL containers.
`#1455 <>`_.
* Allow ostream-redirection of more than 1024 characters.
`#1479 <>`_.
* Set ``Py_DEBUG`` define when compiling against a debug Python build.
`#1438 <>`_.
* Untangle integer logic in number type caster to work for custom
types that may only be castable to a restricted set of builtin types.
`#1442 <>`_.
* CMake build system: Remember Python version in cache file.
`#1434 <>`_.
* Fix for custom smart pointers: use ``std::addressof`` to obtain holder
address instead of ``operator&``.
`#1435 <>`_.
* Properly report exceptions thrown during module initialization.
`#1362 <>`_.
* Fixed a segmentation fault when creating empty-shaped NumPy array.
`#1371 <>`_.
* The version of Intel C++ compiler must be >= 2017, and this is now checked by
the header files. `#1363 <>`_.
* A few minor typo fixes and improvements to the test suite, and
patches that silence compiler warnings.
* Vectors now support construction from generators, as well as ``extend()`` from a
list or generator.
`#1496 <>`_.
v2.2.3 (April 29, 2018)
-----------------------------------------------------
* The pybind11 header location detection was replaced by a new implementation
that no longer depends on ``pip`` internals (the recently released ``pip``
10 has restricted access to this API).
`#1190 <>`_.
* Small adjustment to an implementation detail to work around a compiler segmentation fault in Clang 3.3/3.4.
`#1350 <>`_.
* The minimal supported version of the Intel compiler was >= 17.0 since
pybind11 v2.1. This check is now explicit, and a compile-time error is raised
if the compiler meet the requirement.
`#1363 <>`_.
* Fixed an endianness-related fault in the test suite.
`#1287 <>`_.
v2.2.2 (February 7, 2018)
-----------------------------------------------------
* Fixed a segfault when combining embedded interpreter
shutdown/reinitialization with external loaded pybind11 modules.
`#1092 <>`_.
* Eigen support: fixed a bug where Nx1/1xN numpy inputs couldn't be passed as
arguments to Eigen vectors (which for Eigen are simply compile-time fixed
Nx1/1xN matrices).
`#1106 <>`_.
* Clarified to license by moving the licensing of contributions from
``LICENSE`` into ``CONTRIBUTING.md``: the licensing of contributions is not
actually part of the software license as distributed. This isn't meant to be
a substantial change in the licensing of the project, but addresses concerns
that the clause made the license non-standard.
`#1109 <>`_.
* Fixed a regression introduced in 2.1 that broke binding functions with lvalue
character literal arguments.
`#1128 <>`_.
* MSVC: fix for compilation failures under /permissive-, and added the flag to
the appveyor test suite.
`#1155 <>`_.
* Fixed ``__qualname__`` generation, and in turn, fixes how class names
(especially nested class names) are shown in generated docstrings.
`#1171 <>`_.
* Updated the FAQ with a suggested project citation reference.
`#1189 <>`_.
* Added fixes for deprecation warnings when compiled under C++17 with
``-Wdeprecated`` turned on, and add ``-Wdeprecated`` to the test suite
compilation flags.
`#1191 <>`_.
* Fixed outdated PyPI URLs in ``setup.py``.
`#1213 <>`_.
* Fixed a refcount leak for arguments that end up in a ``py::args`` argument
for functions with both fixed positional and ``py::args`` arguments.
`#1216 <>`_.
* Fixed a potential segfault resulting from possible premature destruction of
``py::args``/``py::kwargs`` arguments with overloaded functions.
`#1223 <>`_.
* Fixed ``del map[item]`` for a ``stl_bind.h`` bound stl map.
`#1229 <>`_.
* Fixed a regression from v2.1.x where the aggregate initialization could
unintentionally end up at a constructor taking a templated
``std::initializer_list<T>`` argument.
`#1249 <>`_.
* Fixed an issue where calling a function with a keep_alive policy on the same
nurse/patient pair would cause the internal patient storage to needlessly
grow (unboundedly, if the nurse is long-lived).
`#1251 <>`_.
* Various other minor fixes.
v2.2.1 (September 14, 2017)
-----------------------------------------------------
* Added ``py::module_::reload()`` member function for reloading a module.
`#1040 <>`_.
* Fixed a reference leak in the number converter.
`#1078 <>`_.
* Fixed compilation with Clang on host GCC < 5 (old libstdc++ which isn't fully
C++11 compliant). `#1062 <>`_.
* Fixed a regression where the automatic ``std::vector<bool>`` caster would
fail to compile. The same fix also applies to any container which returns
element proxies instead of references.
`#1053 <>`_.
* Fixed a regression where the ``py::keep_alive`` policy could not be applied
to constructors. `#1065 <>`_.
* Fixed a nullptr dereference when loading a ``py::module_local`` type
that's only registered in an external module.
`#1058 <>`_.
* Fixed implicit conversion of accessors to types derived from ``py::object``.
`#1076 <>`_.
* The ``name`` in ``PYBIND11_MODULE(name, variable)`` can now be a macro.
`#1082 <>`_.
* Relaxed overly strict ``py::pickle()`` check for matching get and set types.
`#1064 <>`_.
* Conversion errors now try to be more informative when it's likely that
a missing header is the cause (e.g. forgetting ``<pybind11/stl.h>``).
`#1077 <>`_.
v2.2.0 (August 31, 2017)
-----------------------------------------------------
* Support for embedding the Python interpreter. See the
:doc:`documentation page </advanced/embedding>` for a
full overview of the new features.
`#774 <>`_,
`#889 <>`_,
`#892 <>`_,
`#920 <>`_.
.. code-block:: cpp
#include <pybind11/embed.h>
namespace py = pybind11;
int main() {
py::scoped_interpreter guard{}; // start the interpreter and keep it alive
py::print("Hello, World!"); // use the Python API
}
* Support for inheriting from multiple C++ bases in Python.
`#693 <>`_.
.. code-block:: python
from cpp_module import CppBase1, CppBase2
class PyDerived(CppBase1, CppBase2):
def __init__(self):
CppBase1.__init__(self) # C++ bases must be initialized explicitly
CppBase2.__init__(self)
* ``PYBIND11_MODULE`` is now the preferred way to create module entry points.
``PYBIND11_PLUGIN`` is deprecated. See :ref:`macros` for details.
`#879 <>`_.
.. code-block:: cpp
// new
PYBIND11_MODULE(example, m) {
m.def("add", [](int a, int b) { return a + b; });
}
// old
PYBIND11_PLUGIN(example) {
py::module m("example");
m.def("add", [](int a, int b) { return a + b; });
return m.ptr();
}
* pybind11's headers and build system now more strictly enforce hidden symbol
visibility for extension modules. This should be seamless for most users,
but see the :doc:`upgrade` if you use a custom build system.
`#995 <>`_.
* Support for ``py::module_local`` types which allow multiple modules to
export the same C++ types without conflicts. This is useful for opaque
types like ``std::vector<int>``. ``py::bind_vector`` and ``py::bind_map``
now default to ``py::module_local`` if their elements are builtins or
local types. See :ref:`module_local` for details.
`#949 <>`_,
`#981 <>`_,
`#995 <>`_,
`#997 <>`_.
* Custom constructors can now be added very easily using lambdas or factory
functions which return a class instance by value, pointer or holder. This
supersedes the old placement-new ``__init__`` technique.
See :ref:`custom_constructors` for details.
`#805 <>`_,
`#1014 <>`_.
.. code-block:: cpp
struct Example {
Example(std::string);
};
py::class_<Example>(m, "Example")
.def(py::init<std::string>()) // existing constructor
.def(py::init([](int n) { // custom constructor
return std::make_unique<Example>(std::to_string(n));
}));
* Similarly to custom constructors, pickling support functions are now bound
using the ``py::pickle()`` adaptor which improves type safety. See the
:doc:`upgrade` and :ref:`pickling` for details.
`#1038 <>`_.
* Builtin support for converting C++17 standard library types and general
conversion improvements:
1. C++17 ``std::variant`` is supported right out of the box. C++11/14
equivalents (e.g. ``boost::variant``) can also be added with a simple
user-defined specialization. See :ref:`cpp17_container_casters` for details.
`#811 <>`_,
`#845 <>`_,
`#989 <>`_.
2. Out-of-the-box support for C++17 ``std::string_view``.
`#906 <>`_.
3. Improved compatibility of the builtin ``optional`` converter.
`#874 <>`_.
4. The ``bool`` converter now accepts ``numpy.bool_`` and types which
define ``__bool__`` (Python 3.x) or ``__nonzero__`` (Python 2.7).
`#925 <>`_.
5. C++-to-Python casters are now more efficient and move elements out
of rvalue containers whenever possible.
`#851 <>`_,
`#936 <>`_,
`#938 <>`_.
6. Fixed ``bytes`` to ``std::string/char*`` conversion on Python 3.
`#817 <>`_.
7. Fixed lifetime of temporary C++ objects created in Python-to-C++ conversions.
`#924 <>`_.
* Scope guard call policy for RAII types, e.g. ``py::call_guard<py::gil_scoped_release>()``,
``py::call_guard<py::scoped_ostream_redirect>()``. See :ref:`call_policies` for details.
`#740 <>`_.
* Utility for redirecting C++ streams to Python (e.g. ``std::cout`` ->
``sys.stdout``). Scope guard ``py::scoped_ostream_redirect`` in C++ and
a context manager in Python. See :ref:`ostream_redirect`.
`#1009 <>`_.
* Improved handling of types and exceptions across module boundaries.
`#915 <>`_,
`#951 <>`_,
`#995 <>`_.
* Fixed destruction order of ``py::keep_alive`` nurse/patient objects
in reference cycles.
`#856 <>`_.
* NumPy and buffer protocol related improvements:
1. Support for negative strides in Python buffer objects/numpy arrays. This
required changing integers from unsigned to signed for the related C++ APIs.
Note: If you have compiler warnings enabled, you may notice some new conversion
warnings after upgrading. These can be resolved with ``static_cast``.
`#782 <>`_.
2. Support ``std::complex`` and arrays inside ``PYBIND11_NUMPY_DTYPE``.
`#831 <>`_,
`#832 <>`_.
3. Support for constructing ``py::buffer_info`` and ``py::arrays`` using
arbitrary containers or iterators instead of requiring a ``std::vector``.
`#788 <>`_,
`#822 <>`_,
`#860 <>`_.
4. Explicitly check numpy version and require >= 1.7.0.
`#819 <>`_.
* Support for allowing/prohibiting ``None`` for specific arguments and improved
``None`` overload resolution order. See :ref:`none_arguments` for details.
`#843 <>`_.
`#859 <>`_.
* Added ``py::exec()`` as a shortcut for ``py::eval<py::eval_statements>()``
and support for C++11 raw string literals as input. See :ref:`eval`.
`#766 <>`_,
`#827 <>`_.
* ``py::vectorize()`` ignores non-vectorizable arguments and supports
member functions.
`#762 <>`_.
* Support for bound methods as callbacks (``pybind11/functional.h``).
`#815 <>`_.
* Allow aliasing pybind11 methods: ``cls.attr("foo") = cls.attr("bar")``.
`#802 <>`_.
* Don't allow mixed static/non-static overloads.
`#804 <>`_.
* Fixed overriding static properties in derived classes.
`#784 <>`_.
* Added support for write only properties.
`#1144 <>`_.
* Improved deduction of member functions of a derived class when its bases
aren't registered with pybind11.
`#855 <>`_.
.. code-block:: cpp
struct Base {
int foo() { return 42; }
}
struct Derived : Base {}
// Now works, but previously required also binding `Base`
py::class_<Derived>(m, "Derived")
.def("foo", &Derived::foo); // function is actually from `Base`
* The implementation of ``py::init<>`` now uses C++11 brace initialization
syntax to construct instances, which permits binding implicit constructors of
aggregate types. `#1015 <>`_.
.. code-block:: cpp
struct Aggregate {
int a;
std::string b;
};
py::class_<Aggregate>(m, "Aggregate")
.def(py::init<int, const std::string &>());
* Fixed issues with multiple inheritance with offset base/derived pointers.
`#812 <>`_,
`#866 <>`_,
`#960 <>`_.
* Fixed reference leak of type objects.
`#1030 <>`_.
* Improved support for the ``/std:c++14`` and ``/std:c++latest`` modes
on MSVC 2017.
`#841 <>`_,
`#999 <>`_.
* Fixed detection of private operator new on MSVC.
`#893 <>`_,
`#918 <>`_.
* Intel C++ compiler compatibility fixes.
`#937 <>`_.
* Fixed implicit conversion of ``py::enum_`` to integer types on Python 2.7.
`#821 <>`_.
* Added ``py::hash`` to fetch the hash value of Python objects, and
``.def(hash(py::self))`` to provide the C++ ``std::hash`` as the Python
``__hash__`` method.
`#1034 <>`_.
* Fixed ``__truediv__`` on Python 2 and ``__itruediv__`` on Python 3.
`#867 <>`_.
* ``py::capsule`` objects now support the ``name`` attribute. This is useful
for interfacing with ``scipy.LowLevelCallable``.
`#902 <>`_.
* Fixed ``py::make_iterator``'s ``__next__()`` for past-the-end calls.
`#897 <>`_.
* Added ``error_already_set::matches()`` for checking Python exceptions.
`#772 <>`_.
* Deprecated ``py::error_already_set::clear()``. It's no longer needed
following a simplification of the ``py::error_already_set`` class.
`#954 <>`_.
* Deprecated ``py::handle::operator==()`` in favor of ``py::handle::is()``
`#825 <>`_.
* Deprecated ``py::object::borrowed``/``py::object::stolen``.
Use ``py::object::borrowed_t{}``/``py::object::stolen_t{}`` instead.
`#771 <>`_.
* Changed internal data structure versioning to avoid conflicts between
modules compiled with different revisions of pybind11.
`#1012 <>`_.
* Additional compile-time and run-time error checking and more informative messages.
`#786 <>`_,
`#794 <>`_,
`#803 <>`_.
* Various minor improvements and fixes.
`#764 <>`_,
`#791 <>`_,
`#795 <>`_,
`#840 <>`_,
`#844 <>`_,
`#846 <>`_,
`#849 <>`_,
`#858 <>`_,
`#862 <>`_,
`#871 <>`_,
`#872 <>`_,
`#881 <>`_,
`#888 <>`_,
`#899 <>`_,
`#928 <>`_,
`#931 <>`_,
`#944 <>`_,
`#950 <>`_,
`#952 <>`_,
`#962 <>`_,
`#965 <>`_,
`#970 <>`_,
`#978 <>`_,
`#979 <>`_,
`#986 <>`_,
`#1020 <>`_,
`#1027 <>`_,
`#1037 <>`_.
* Testing improvements.
`#798 <>`_,
`#882 <>`_,
`#898 <>`_,
`#900 <>`_,
`#921 <>`_,
`#923 <>`_,
`#963 <>`_.
v2.1.1 (April 7, 2017)
-----------------------------------------------------
* Fixed minimum version requirement for MSVC 2015u3
`#773 <>`_.
v2.1.0 (March 22, 2017)
-----------------------------------------------------
* pybind11 now performs function overload resolution in two phases. The first
phase only considers exact type matches, while the second allows for implicit
conversions to take place. A special ``noconvert()`` syntax can be used to
completely disable implicit conversions for specific arguments.
`#643 <>`_,
`#634 <>`_,
`#650 <>`_.
* Fixed a regression where static properties no longer worked with classes
using multiple inheritance. The ``py::metaclass`` attribute is no longer
necessary (and deprecated as of this release) when binding classes with
static properties.
`#679 <>`_,
* Classes bound using ``pybind11`` can now use custom metaclasses.
`#679 <>`_,
* ``py::args`` and ``py::kwargs`` can now be mixed with other positional
arguments when binding functions using pybind11.
`#611 <>`_.
* Improved support for C++11 unicode string and character types; added
extensive documentation regarding pybind11's string conversion behavior.
`#624 <>`_,
`#636 <>`_,
`#715 <>`_.
* pybind11 can now avoid expensive copies when converting Eigen arrays to NumPy
arrays (and vice versa). `#610 <>`_.
* The "fast path" in ``py::vectorize`` now works for any full-size group of C or
F-contiguous arrays. The non-fast path is also faster since it no longer performs
copies of the input arguments (except when type conversions are necessary).
`#610 <>`_.
* Added fast, unchecked access to NumPy arrays via a proxy object.
`#746 <>`_.
* Transparent support for class-specific ``operator new`` and
``operator delete`` implementations.
`#755 <>`_.
* Slimmer and more efficient STL-compatible iterator interface for sequence types.
`#662 <>`_.
* Improved custom holder type support.
`#607 <>`_.
* ``nullptr`` to ``None`` conversion fixed in various builtin type casters.
`#732 <>`_.
* ``enum_`` now exposes its members via a special ``__members__`` attribute.
`#666 <>`_.
* ``std::vector`` bindings created using ``stl_bind.h`` can now optionally
implement the buffer protocol. `#488 <>`_.
* Automated C++ reference documentation using doxygen and breathe.
`#598 <>`_.
* Added minimum compiler version assertions.
`#727 <>`_.
* Improved compatibility with C++1z.
`#677 <>`_.
* Improved ``py::capsule`` API. Can be used to implement cleanup
callbacks that are involved at module destruction time.
`#752 <>`_.
* Various minor improvements and fixes.
`#595 <>`_,
`#588 <>`_,
`#589 <>`_,
`#603 <>`_,
`#619 <>`_,
`#648 <>`_,
`#695 <>`_,
`#720 <>`_,
`#723 <>`_,
`#729 <>`_,
`#724 <>`_,
`#742 <>`_,
`#753 <>`_.
v2.0.1 (Jan 4, 2017)
-----------------------------------------------------
* Fix pointer to reference error in type_caster on MSVC
`#583 <>`_.
* Fixed a segmentation in the test suite due to a typo
`cd7eac <>`_.
v2.0.0 (Jan 1, 2017)
-----------------------------------------------------
* Fixed a reference counting regression affecting types with custom metaclasses
(introduced in v2.0.0-rc1).
`#571 <>`_.
* Quenched a CMake policy warning.
`#570 <>`_.
v2.0.0-rc1 (Dec 23, 2016)
-----------------------------------------------------
The pybind11 developers are excited to issue a release candidate of pybind11
with a subsequent v2.0.0 release planned in early January next year.
An incredible amount of effort by went into pybind11 over the last ~5 months,
leading to a release that is jam-packed with exciting new features and numerous
usability improvements. The following list links PRs or individual commits
whenever applicable.
Happy Christmas!
* Support for binding C++ class hierarchies that make use of multiple
inheritance. `#410 <>`_.
* PyPy support: pybind11 now supports nightly builds of PyPy and will
interoperate with the future 5.7 release. No code changes are necessary,
everything "just" works as usual. Note that we only target the Python 2.7
branch for now; support for 3.x will be added once its ``cpyext`` extension
support catches up. A few minor features remain unsupported for the time
being (notably dynamic attributes in custom types).
`#527 <>`_.
* Significant work on the documentation -- in particular, the monolithic
``advanced.rst`` file was restructured into a easier to read hierarchical
organization. `#448 <>`_.
* Many NumPy-related improvements:
1. Object-oriented API to access and modify NumPy ``ndarray`` instances,
replicating much of the corresponding NumPy C API functionality.
`#402 <>`_.
2. NumPy array ``dtype`` array descriptors are now first-class citizens and
are exposed via a new class ``py::dtype``.
3. Structured dtypes can be registered using the ``PYBIND11_NUMPY_DTYPE()``
macro. Special ``array`` constructors accepting dtype objects were also
added.
One potential caveat involving this change: format descriptor strings
should now be accessed via ``format_descriptor::format()`` (however, for
compatibility purposes, the old syntax ``format_descriptor::value`` will
still work for non-structured data types). `#308
<>`_.
4. Further improvements to support structured dtypes throughout the system.
`#472 <>`_,
`#474 <>`_,
`#459 <>`_,
`#453 <>`_,
`#452 <>`_, and
`#505 <>`_.
5. Fast access operators. `#497 <>`_.
6. Constructors for arrays whose storage is owned by another object.
`#440 <>`_.
7. Added constructors for ``array`` and ``array_t`` explicitly accepting shape
and strides; if strides are not provided, they are deduced assuming
C-contiguity. Also added simplified constructors for 1-dimensional case.
8. Added buffer/NumPy support for ``char[N]`` and ``std::array<char, N>`` types.
9. Added ``memoryview`` wrapper type which is constructible from ``buffer_info``.
* Eigen: many additional conversions and support for non-contiguous
arrays/slices.
`#427 <>`_,
`#315 <>`_,
`#316 <>`_,
`#312 <>`_, and
`#267 <>`_
* Incompatible changes in ``class_<...>::class_()``:
1. Declarations of types that provide access via the buffer protocol must
now include the ``py::buffer_protocol()`` annotation as an argument to
the ``class_`` constructor.
2. Declarations of types that require a custom metaclass (i.e. all classes
which include static properties via commands such as
``def_readwrite_static()``) must now include the ``py::metaclass()``
annotation as an argument to the ``class_`` constructor.
These two changes were necessary to make type definitions in pybind11
future-proof, and to support PyPy via its cpyext mechanism. `#527
<>`_.
3. This version of pybind11 uses a redesigned mechanism for instantiating
trampoline classes that are used to override virtual methods from within
Python. This led to the following user-visible syntax change: instead of
.. code-block:: cpp
py::class_<TrampolineClass>("MyClass")
.alias<MyClass>()
....
write
.. code-block:: cpp
py::class_<MyClass, TrampolineClass>("MyClass")
....
Importantly, both the original and the trampoline class are now
specified as an arguments (in arbitrary order) to the ``py::class_``
template, and the ``alias<..>()`` call is gone. The new scheme has zero
overhead in cases when Python doesn't override any functions of the
underlying C++ class. `rev. 86d825
<>`_.
* Added ``eval`` and ``eval_file`` functions for evaluating expressions and
statements from a string or file. `rev. 0d3fc3
<>`_.
* pybind11 can now create types with a modifiable dictionary.
`#437 <>`_ and
`#444 <>`_.
* Support for translation of arbitrary C++ exceptions to Python counterparts.
`#296 <>`_ and
`#273 <>`_.
* Report full backtraces through mixed C++/Python code, better reporting for
import errors, fixed GIL management in exception processing.
`#537 <>`_,
`#494 <>`_,
`rev. e72d95 <>`_, and
`rev. 099d6e <>`_.
* Support for bit-level operations, comparisons, and serialization of C++
enumerations. `#503 <>`_,
`#508 <>`_,
`#380 <>`_,
`#309 <>`_.
`#311 <>`_.
* The ``class_`` constructor now accepts its template arguments in any order.
`#385 <>`_.
* Attribute and item accessors now have a more complete interface which makes
it possible to chain attributes as in
``obj.attr("a")[key].attr("b").attr("method")(1, 2, 3)``. `#425
<>`_.
* Major redesign of the default and conversion constructors in ``pytypes.h``.
`#464 <>`_.
* Added built-in support for ``std::shared_ptr`` holder type. It is no longer
necessary to to include a declaration of the form
``PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)`` (though continuing to
do so won't cause an error).
`#454 <>`_.
* New ``py::overload_cast`` casting operator to select among multiple possible
overloads of a function. An example:
.. code-block:: cpp
py::class_<Pet>(m, "Pet")
.def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
.def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
This feature only works on C++14-capable compilers.
`#541 <>`_.
* C++ types are automatically cast to Python types, e.g. when assigning
them as an attribute. For instance, the following is now legal:
.. code-block:: cpp
py::module m = /* ... */
m.attr("constant") = 123;
(Previously, a ``py::cast`` call was necessary to avoid a compilation error.)
`#551 <>`_.
* Redesigned ``pytest``-based test suite. `#321 <>`_.
* Instance tracking to detect reference leaks in test suite. `#324 <>`_
* pybind11 can now distinguish between multiple different instances that are
located at the same memory address, but which have different types.
`#329 <>`_.
* Improved logic in ``move`` return value policy.
`#510 <>`_,
`#297 <>`_.
* Generalized unpacking API to permit calling Python functions from C++ using
notation such as ``foo(a1, a2, *args, "ka"_a=1, "kb"_a=2, **kwargs)``. `#372 <>`_.
* ``py::print()`` function whose behavior matches that of the native Python
``print()`` function. `#372 <>`_.
* Added ``py::dict`` keyword constructor:``auto d = dict("number"_a=42,
"name"_a="World");``. `#372 <>`_.
* Added ``py::str::format()`` method and ``_s`` literal: ``py::str s = "1 + 2
= {}"_s.format(3);``. `#372 <>`_.
* Added ``py::repr()`` function which is equivalent to Python's builtin
``repr()``. `#333 <>`_.
* Improved construction and destruction logic for holder types. It is now
possible to reference instances with smart pointer holder types without
constructing the holder if desired. The ``PYBIND11_DECLARE_HOLDER_TYPE``
macro now accepts an optional second parameter to indicate whether the holder
type uses intrusive reference counting.
`#533 <>`_ and
`#561 <>`_.
* Mapping a stateless C++ function to Python and back is now "for free" (i.e.
no extra indirections or argument conversion overheads). `rev. 954b79
<>`_.
* Bindings for ``std::valarray<T>``.
`#545 <>`_.
* Improved support for C++17 capable compilers.
`#562 <>`_.
* Bindings for ``std::optional<t>``.
`#475 <>`_,
`#476 <>`_,
`#479 <>`_,
`#499 <>`_, and
`#501 <>`_.
* ``stl_bind.h``: general improvements and support for ``std::map`` and
``std::unordered_map``.
`#490 <>`_,
`#282 <>`_,
`#235 <>`_.
* The ``std::tuple``, ``std::pair``, ``std::list``, and ``std::vector`` type
casters now accept any Python sequence type as input. `rev. 107285
<>`_.
* Improved CMake Python detection on multi-architecture Linux.
`#532 <>`_.
* Infrastructure to selectively disable or enable parts of the automatically
generated docstrings. `#486 <>`_.
* ``reference`` and ``reference_internal`` are now the default return value
properties for static and non-static properties, respectively. `#473
<>`_. (the previous defaults
were ``automatic``). `#473 <>`_.
* Support for ``std::unique_ptr`` with non-default deleters or no deleter at
all (``py::nodelete``). `#384 <>`_.
* Deprecated ``handle::call()`` method. The new syntax to call Python
functions is simply ``handle()``. It can also be invoked explicitly via
``handle::operator<X>()``, where ``X`` is an optional return value policy.
* Print more informative error messages when ``make_tuple()`` or ``cast()``
fail. `#262 <>`_.
* Creation of holder types for classes deriving from
``std::enable_shared_from_this<>`` now also works for ``const`` values.
`#260 <>`_.
* ``make_iterator()`` improvements for better compatibility with various
types (now uses prefix increment operator); it now also accepts iterators
with different begin/end types as long as they are equality comparable.
`#247 <>`_.
* ``arg()`` now accepts a wider range of argument types for default values.
`#244 <>`_.
* Support ``keep_alive`` where the nurse object may be ``None``. `#341
<>`_.
* Added constructors for ``str`` and ``bytes`` from zero-terminated char
pointers, and from char pointers and length. Added constructors for ``str``
from ``bytes`` and for ``bytes`` from ``str``, which will perform UTF-8
decoding/encoding as required.
* Many other improvements of library internals without user-visible changes
1.8.1 (July 12, 2016)
----------------------
* Fixed a rare but potentially very severe issue when the garbage collector ran
during pybind11 type creation.
1.8.0 (June 14, 2016)
----------------------
* Redesigned CMake build system which exports a convenient
``pybind11_add_module`` function to parent projects.
* ``std::vector<>`` type bindings analogous to Boost.Python's ``indexing_suite``
* Transparent conversion of sparse and dense Eigen matrices and vectors (``eigen.h``)
* Added an ``ExtraFlags`` template argument to the NumPy ``array_t<>`` wrapper
to disable an enforced cast that may lose precision, e.g. to create overloads
for different precisions and complex vs real-valued matrices.
* Prevent implicit conversion of floating point values to integral types in
function arguments
* Fixed incorrect default return value policy for functions returning a shared
pointer
* Don't allow registering a type via ``class_`` twice
* Don't allow casting a ``None`` value into a C++ lvalue reference
* Fixed a crash in ``enum_::operator==`` that was triggered by the ``help()`` command
* Improved detection of whether or not custom C++ types can be copy/move-constructed
* Extended ``str`` type to also work with ``bytes`` instances
* Added a ``"name"_a`` user defined string literal that is equivalent to ``py::arg("name")``.
* When specifying function arguments via ``py::arg``, the test that verifies
the number of arguments now runs at compile time.
* Added ``[[noreturn]]`` attribute to ``pybind11_fail()`` to quench some
compiler warnings
* List function arguments in exception text when the dispatch code cannot find
a matching overload
* Added ``PYBIND11_OVERLOAD_NAME`` and ``PYBIND11_OVERLOAD_PURE_NAME`` macros which
can be used to override virtual methods whose name differs in C++ and Python
(e.g. ``__call__`` and ``operator()``)
* Various minor ``iterator`` and ``make_iterator()`` improvements
* Transparently support ``__bool__`` on Python 2.x and Python 3.x
* Fixed issue with destructor of unpickled object not being called
* Minor CMake build system improvements on Windows
* New ``pybind11::args`` and ``pybind11::kwargs`` types to create functions which
take an arbitrary number of arguments and keyword arguments
* New syntax to call a Python function from C++ using ``*args`` and ``*kwargs``
* The functions ``def_property_*`` now correctly process docstring arguments (these
formerly caused a segmentation fault)
* Many ``mkdoc.py`` improvements (enumerations, template arguments, ``DOC()``
macro accepts more arguments)
* Cygwin support
* Documentation improvements (pickling support, ``keep_alive``, macro usage)
1.7 (April 30, 2016)
----------------------
* Added a new ``move`` return value policy that triggers C++11 move semantics.
The automatic return value policy falls back to this case whenever a rvalue
reference is encountered
* Significantly more general GIL state routines that are used instead of
Python's troublesome ``PyGILState_Ensure`` and ``PyGILState_Release`` API
* Redesign of opaque types that drastically simplifies their usage
* Extended ability to pass values of type ``[const] void *``
* ``keep_alive`` fix: don't fail when there is no patient
* ``functional.h``: acquire the GIL before calling a Python function
* Added Python RAII type wrappers ``none`` and ``iterable``
* Added ``*args`` and ``*kwargs`` pass-through parameters to
``pybind11.get_include()`` function
* Iterator improvements and fixes
* Documentation on return value policies and opaque types improved
1.6 (April 30, 2016)
----------------------
* Skipped due to upload to PyPI gone wrong and inability to recover
()
1.5 (April 21, 2016)
----------------------
* For polymorphic types, use RTTI to try to return the closest type registered with pybind11
* Pickling support for serializing and unserializing C++ instances to a byte stream in Python
* Added a convenience routine ``make_iterator()`` which turns a range indicated
by a pair of C++ iterators into a iterable Python object
* Added ``len()`` and a variadic ``make_tuple()`` function
* Addressed a rare issue that could confuse the current virtual function
dispatcher and another that could lead to crashes in multi-threaded
applications
* Added a ``get_include()`` function to the Python module that returns the path
of the directory containing the installed pybind11 header files
* Documentation improvements: import issues, symbol visibility, pickling, limitations
* Added casting support for ``std::reference_wrapper<>``
1.4 (April 7, 2016)
--------------------------
* Transparent type conversion for ``std::wstring`` and ``wchar_t``
* Allow passing ``nullptr``-valued strings
* Transparent passing of ``void *`` pointers using capsules
* Transparent support for returning values wrapped in ``std::unique_ptr<>``
* Improved docstring generation for compatibility with Sphinx
* Nicer debug error message when default parameter construction fails
* Support for "opaque" types that bypass the transparent conversion layer for STL containers
* Redesigned type casting interface to avoid ambiguities that could occasionally cause compiler errors
* Redesigned property implementation; fixes crashes due to an unfortunate default return value policy
* Anaconda package generation support
1.3 (March 8, 2016)
--------------------------
* Added support for the Intel C++ compiler (v15+)
* Added support for the STL unordered set/map data structures
* Added support for the STL linked list data structure
* NumPy-style broadcasting support in ``pybind11::vectorize``
* pybind11 now displays more verbose error messages when ``arg::operator=()`` fails
* pybind11 internal data structures now live in a version-dependent namespace to avoid ABI issues
* Many, many bugfixes involving corner cases and advanced usage
1.2 (February 7, 2016)
--------------------------
* Optional: efficient generation of function signatures at compile time using C++14
* Switched to a simpler and more general way of dealing with function default
arguments. Unused keyword arguments in function calls are now detected and
cause errors as expected
* New ``keep_alive`` call policy analogous to Boost.Python's ``with_custodian_and_ward``
* New ``pybind11::base<>`` attribute to indicate a subclass relationship
* Improved interface for RAII type wrappers in ``pytypes.h``
* Use RAII type wrappers consistently within pybind11 itself. This
fixes various potential refcount leaks when exceptions occur
* Added new ``bytes`` RAII type wrapper (maps to ``string`` in Python 2.7)
* Made handle and related RAII classes const correct, using them more
consistently everywhere now
* Got rid of the ugly ``__pybind11__`` attributes on the Python side---they are
now stored in a C++ hash table that is not visible in Python
* Fixed refcount leaks involving NumPy arrays and bound functions
* Vastly improved handling of shared/smart pointers
* Removed an unnecessary copy operation in ``pybind11::vectorize``
* Fixed naming clashes when both pybind11 and NumPy headers are included
* Added conversions for additional exception types
* Documentation improvements (using multiple extension modules, smart pointers,
other minor clarifications)
* unified infrastructure for parsing variadic arguments in ``class_`` and cpp_function
* Fixed license text (was: ZLIB, should have been: 3-clause BSD)
* Python 3.2 compatibility
* Fixed remaining issues when accessing types in another plugin module
* Added enum comparison and casting methods
* Improved SFINAE-based detection of whether types are copy-constructible
* Eliminated many warnings about unused variables and the use of ``offsetof()``
* Support for ``std::array<>`` conversions
1.1 (December 7, 2015)
--------------------------
* Documentation improvements (GIL, wrapping functions, casting, fixed many typos)
* Generalized conversion of integer types
* Improved support for casting function objects
* Improved support for ``std::shared_ptr<>`` conversions
* Initial support for ``std::set<>`` conversions
* Fixed type resolution issue for types defined in a separate plugin module
* CMake build system improvements
* Factored out generic functionality to non-templated code (smaller code size)
* Added a code size / compile time benchmark vs Boost.Python
* Added an appveyor CI script
1.0 (October 15, 2015)
------------------------
* Initial release | https://gem5.googlesource.com/public/gem5/+/refs/heads/master/ext/pybind11/docs/changelog.rst | CC-MAIN-2022-40 | refinedweb | 9,249 | 58.48 |
Hey All,
I'm having issues with my SOAP transaction.
I've used the setHeader($header) method in order to set the necessary headers but when I do that now the body of my soap transaction is empty and it just passes an empty soap data transaction, it has the root elements along with the reburied namespace element properties of the body transaction and that's it.
I've tried both the call() method and the overloading method used by getProxy() to dynamically create the function name and they both display the same behavior. My input in the function in both instances is a nested array of my data structure made to look like the SOAP transaction. Is this a bug, known issue, or am I doing something wrong?
Without the header I've been able to create a fully working soap body, I add the header and it disappears except for the root element. | https://sourceforge.net/p/nusoap/discussion/193579/thread/398a0fc5/ | CC-MAIN-2017-43 | refinedweb | 155 | 63.22 |
DataFrames power data analysis in Python – they allow us to use grids just like we would conventional spreadsheets. They give us labelled columns and rows, functions, filtering and many more tools to get the most insight and ease of use from our data.
This page will introduce the creation of data frames, a few functions and tools to make selections within them. Let’s import our packages to get started (I’m sure you’ve installed them by now!).
import pandas as pd import numpy as np
Our table below has a scout report on 4 different players’ shooting, passing and defending skills.
PlayerList = ["Pagbo","Grazemen","Cantay","Ravane"] SkillList=["Shooting","Passing","Defending"] #For this example, we have a random number generator for our scout #I wouldn't recommend this for an actual team ScoresArray = np.random.randint(1,10,(4,3)) df = pd.DataFrame(data=ScoresArray, index=PlayerList, columns=SkillList) df
In this example, dataFrame needs 3 arguments for a fully labelled dataframe – data is the values that make up the body, index goes along the y axis and is the name of each row. Finally, columns runs along the x axis to name the columns.
There are other ways to create dataFrames, but this will serve us perfectly for now.
You’ve come a long way from lists and individual values!
Selecting and indexing
You can probably guess how we select individual values and groups
#Square brackets for columns #If the result looks familiar, that's because DataFrame columns are series! df['Shooting']
Pagbo 6 Grazemen 7 Cantay 2 Ravane 2 Name: Shooting, dtype: int32
#For rows, we use .loc if we use a name #Turns out that DataFrame rows are also series! df.loc['Pagbo']
Shooting 6 Passing 7 Defending 3 Name: Pagbo, dtype: int32
#Or if we use a index number, .iloc df.iloc[1:3]
Creating and removing columns/rows
DataFrames make it really easy for us to be flexible with our datasets. Let’s ask our scout for their thoughts on more players and skills.
#Scout, what about their communication? df['Communication'] = np.random.randint(1,10,4) df
To add a new column, we refer to a new column with square brackets, give it a new name then fill it with a series. Remember, our scout uses random numbers as scouting scores.
Our new manager doesn’t care about defending – they want these scores removed from report. The ‘.drop’ method makes this easy:
#axis=1 refers to columns df = df.drop('Defending',axis=1) df
Great job adding and removing columns!
Turns out, though, that our scout didn’t do their homework on the players’ transfer fees. Grazemen is far too expensive and we need to swap him for another player – Mogez.
For rows, we use ‘.drop’ with the axis argument set to 0:
df = df.drop('Grazemen',axis=0) df
And to add a new one, we refer to our new row with ‘.loc’ (just like we did to refer to an existing one earlier). We then give this new row the list or series of values. Once again, we just use random numbers to fill the set here.
df.loc['Gomez'] = np.random.randint(1,10,3) df
Conditonal Selection
In our series, we used a true or false condition to select the data that we wanted to see. We use the exact same logic here. Let’s see where players’ attributes are above 5:
df>5
Cool, we can see which players meet our criteria. You’ll notice that this returns a DataFrame of true or false values. Just like with series, we can use these booleans to return a DataFrame according to our criteria.
Let’s apply this to a column (which we already know is just a series):
df['Shooting']>5
Pagbo True Cantay False Ravane False Gomez True Name: Shooting, dtype: bool
As expected, we have a series of boolean values. If we use square brackets to select our dataframe using these, we will just get the filtered DataFrame.
Therefore, if the coach is asking for players with great shooting skills, we can easily filter our DataFrame.
df[df['Shooting']>5]
Summary
Great job getting to understand DataFrames – the tool that will underpin our analysis moving forward.
You have created them, added new rows and columns, then filtered them according to your criteria.
There is lots more to learn about DataFrames, so read around more articles on the topic and learn what you can from other articles that use them. | http://fcpython.com/data-analysis/dataframes | CC-MAIN-2018-51 | refinedweb | 752 | 63.29 |
Adding an object to the global namespace through " f_globals" isthat allowed ?
Discussion in 'Python' started by Stef Mientki,,136
- Steven Cheng[MSFT]
- Aug 3, 2004
namespace not allowed in script code declaration block?Steve Richter, Apr 5, 2005, in forum: ASP .Net
- Replies:
- 3
- Views:
- 3,583
- Brock Allen
- Apr 5, 2005
"Explicit specialization only allowed at file or namespace scope"Bas, Jun 3, 2009, in forum: C++
- Replies:
- 3
- Views:
- 638
- Bas
- Jun 3, 2009
Re: Adding an object to the global namespace through " f_globals"is that allowed ?Terry Reedy, Jul 2, 2009, in forum: Python
- Replies:
- 3
- Views:
- 365
- Chris Rebert
- Jul 3, 2009
Why defining a constant in a method is not allowed but usingself.class.const_set is allowed?Iñaki Baz Castillo, Apr 30, 2011, in forum: Ruby
- Replies:
- 13
- Views:
- 621
- Iñaki Baz Castillo
- May 1, 2011 | http://www.thecodingforums.com/threads/adding-an-object-to-the-global-namespace-through-f_globals-isthat-allowed.689789/ | CC-MAIN-2015-27 | refinedweb | 143 | 69.21 |
CircleCI Server v3.x Installation
Before you begin with the CircleCI Server v3.x installation process, ensure all prerequisites are met.
- Step 1 - Install KOTs
- Step 2 - Configure Server (Part 1)
- Step 3 - Obtain Load Balancer IPs
- Step 4 - Install Nomad Clients
- Step 5 - Create DNS Entries for the Frontend
- Step 6 - Configure Server (Part 2) and Deploy
- Step 7 - Validate Installation
- What to read next
Step 1 - Install KOTs
CircleCI Server v3.x uses KOTs from Replicated to manage and
distribute Server v3.x. KOTs is a
kubectl plugin.
To install the latest version, you can run
curl | bash.
Ensure you are running the minimum KOTs (KOTs 1.26) by running
kubectl kots version.
Next, run:
kubectl kots install circleci-server
You will be prompted for a:
namespace for the deployment
password for the KOTs admin console
When complete, you should be provided with a URL to access the admin console. Usually this is.
If you need to get back to the management console at a later date you can run:
kubectl kots admin-console -n <namespace kots was installed in>
Step 2 - Configure Server (Part 1)
Once you have accessed the URL to the administrative console and uploaded your license file, you will see similar to the following, where you will need to configure CircleCI Server.
Global Settings
Global configuration settings are a collection of cross-cutting configuration settings that affect the function of the entire application as a whole. Component-specific settings can be found below under the Component Settings section.
Domain Name (required): The domain name for your server installation. For example, circleci.yourcompany.com. You will need to configure this domain and point it to the external Frontend Load Balancer once it is configured in a later step.
Frontend TLS Private Key: A PEM encoded TLS private key for the web application. A default, self-signed TLS key is provided.
Frontend TLS Certificate: A PEM encoded TLS certificate for the web application. A default, self-signed TLS certificate is provided.
VM Service Load Balancer Hostname (required): The hostname or IP of your VM Service Load Balancer. If you do not yet have this value, you can deploy the application with any value and then retrieve and update it in Step 3 - Obtain Load Balancer IPs.
Output Processor Load Balancer Hostname (required): The hostname or IP of your Output Processor load balancer. If you do not yet have this value, you can deploy the application with any value and then retrieve and update it in Step 3 - Obtain Load Balancer IPs.
Nomad Load Balancer Hostname (required): The hostname or IP of your Nomad load balancer. If you do not yet have this value, you can deploy the application with any value and then retrieve and update it in Step 3 - Obtain Load Balancer IPs.
Optional: Generate a TLS Certificate
By default, CircleCI Server will create self-signed certificates to get you started. In production, you should supply a certificate from a trusted certificate authority. The LetsEncrypt certificate authority, for example, can issue a certificate for free using their certbot tool.
For example, if you host your DNS on Google Cloud, the following commands will provision a certification for your installation:
DOMAIN=example.com # replace with the domain of your installation of server GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json # Path to GCP credentials sudo certbot certonly --dns-google \ --dns-google-credentials ${GOOGLE_APPLICATION_CREDENTIALS} \ -d "${DOMAIN}" \ -d "app.${DOMAIN}"
If instead you’re using AWS Route53 for DNS, execute this example:
DOMAIN=example.com # replace with the domain of your installation of server sudo certbot certonly --dns-route53 \ -d "${DOMAIN}" \ -d "app.${DOMAIN}"
This will create a private key and certificate (including intermediate certificates) in
/etc/letsencrypt/live/${DOMAIN}/.
Encryption
These keysets are used to encrypt and sign artifacts generated by CircleCI.
Artifact Signing Key (required): To generate, run:
docker run circleci/server-keysets:latest generate signing -a stdout
Copy and paste the entirety of the output into the Artifact Signing Key field.
Encryption Signing Key (required) : To generate, run:
docker run circleci/server-keysets:latest generate encryption -a stdout
Copy and paste the entirety of the output into the Encryption Signing Key field.
GitHub
These settings control authorization to server using Github OAuth and allow for updates to Github using build status information.
Github Type: Select Cloud or Enterprise.
OAuth Client ID (required): In GitHub, navigate to Settings > Developer Settings > OAuth Apps and select the Register a new application button.
The domain you selected for your CircleCI installation is the Homepage URL and <your-circle-ci-domain>/auth/github is the Authorization callback URL.
OAuth Client Secret (required): On your Oauth application, you can create one by selecting the Generate a new client secret button in GitHub.
Object Storage
Server 3.0 hosts build artifacts, test results, and other state in object storage. Please choose the one that best suits your needs. A Storage Bucket Name is required, in addition to the following fields, depending on if you are using AWS or GCP. Ensure that the bucket name you provide exists in your chosen object storage provider before proceeeding.
AWS S3
AWS S3 (required): Region your S3 bucket is in.
AWS IAM Access Key ID (required): AWS Access Key ID for S3 bucket access.
AWS IAM Secret Key (required): IAM Secret Key for S3 bucket access.
It is recommended to create a new user with programmatic access for this purpose. You should attach the following IAM policy to the user:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::<<Bucket Name>>", "arn:aws:s3:::<<Bucket Name>>/*" ] }, { "Action": [ "sts:GetFederationToken" ], "Resource": [ "arn:aws:sts::<<AWS account ID>>:federated-user/build-*" ], "Effect": "Allow" } ] }
Google Cloud Storage
Service Account JSON: A JSON format key of the Service Account to use for bucket access.
A dedicated service account is recommended. Add to it the
Storage Object Admin role, with a condition on the resource
name limiting access to only the bucket specified above. For example, enter the following into the Google’s Condition Editor:
resource.name.startsWith("projects/_/buckets/<bucket-name>")
Embedded Object Storage (coming soon)
Server 3.0 will utilize Minio for alternative object storage options. Minio provides a S3 like interface on top of numerous object storage options. For more information on Minio please see.
Build notifications are sent via email.
Email Submission server hostname: Host name of the submission server (e.g., for Sendgrid use smtp.sendgrid.net).
Username: Username to authenticate to submission server. This is commonly the same as the user’s e-mail address.
Password: Password to authenticate to submission server.
Port: Port of the submission server. This is usually either 25 or 587. While port 465 is also commonly used for email submission, it is often used with implicit TLS instead of StartTLS. Server only supports StartTLS for encrypted submission.
Enable StartTLS: Enabling this will encrypt mail submission.
VM Service
VM Service configures VM and remote docker jobs. You can configure a number of options for VM service, such as scaling rules.
Authentication and Permissions
AWS EC2
You will need the following fields to configure your VM Service to work with AWS EC2. Note that the Access Key and Secret Key used by VM Service differs from the policy used by object storage in the previous section.
AWS Region (required): This is the region the application is in.
AWS Windows AMI ID (optional): If you require Windows builders, you can supply an AMI ID for them here.
Subnet ID (required): Choose a subnet (public or private) where the VMs should be deployed.
Security Group ID (required): This is the security group that will be attached to the VMs.
The recommended security group configuration can be found in the Hardening Your Cluster section.
AWS IAM Access Key ID (required): AWS Access Key ID for EC2 access.
AWS IAM Secret Key (required): IAM Secret Key for EC2 access.
It is recommended to create a new user with programmatic access for this purpose. You should attach the following IAM policy to the user:
{ "Version": "2012-10-17", "Statement": [ { "Action": "ec2:RunInstances", "Effect": "Allow", "Resource": [ "arn:aws:ec2:*::image/*", "arn:aws:ec2:*::snapshot/*", "arn:aws:ec2:*:*:key-pair/*", "arn:aws:ec2:*:*:launch-template/*", "arn:aws:ec2:*:*:network-interface/*", "arn:aws:ec2:*:*:placement-group/*", "arn:aws:ec2:*:*:volume/*", "arn:aws:ec2:*:*:subnet/*", "arn:aws:ec2:*:*:security-group/${SECURITY_GROUP_ID}" ] }, { "Action": "ec2:RunInstances", "Effect": "Allow", "Resource": "arn:aws:ec2:*:*:instance/*", "Condition": { "StringEquals": { "aws:RequestTag/ManagedBy": "circleci-vm-service" } } }, { "Action": [ "ec2:CreateVolume" ], "Effect": "Allow", "Resource": [ "arn:aws:ec2:*:*:volume/*" ], "Condition": { "StringEquals": { "aws:RequestTag/ManagedBy": "circleci-vm-service" } } }, { "Action": [ "ec2:Describe*" ], "Effect": "Allow", "Resource": "*" }, { "Effect": "Allow", "Action": [ "ec2:CreateTags" ], "Resource": "arn:aws:ec2:*:*:*/*", "Condition": { "StringEquals": { "ec2:CreateAction" : "CreateVolume" } } }, { "Effect": "Allow", "Action": [ "ec2:CreateTags" ], "Resource": "arn:aws:ec2:*:*:*/*", "Condition": { "StringEquals": { "ec2:CreateAction" : "RunInstances" } } }, { "Action": [ "ec2:CreateTags", "ec2:StartInstances", "ec2:StopInstances", "ec2:TerminateInstances", "ec2:AttachVolume", "ec2:DetachVolume", "ec2:DeleteVolume" ], "Effect": "Allow", "Resource": "arn:aws:ec2:*:*:*/*", "Condition": { "StringEquals": { "ec2:ResourceTag/ManagedBy": "circleci-vm-service" } } }, { "Action": [ "ec2:RunInstances", "ec2:StartInstances", "ec2:StopInstances", "ec2:TerminateInstances" ], "Effect": "Allow", "Resource": "arn:aws:ec2:*:*:subnet/*", "Condition": { "StringEquals": { "ec2:Vpc": "${VPC_ARN}" } } } ] }
Google Cloud Platform
You will need the following fields to configure your VM Service to work with Google Cloud Platform (GCP).
GCP project ID (required): Name of the GCP project the cluster resides.
GCP Zone (required): GCP zone the virtual machines instances should be created in IE
us-east1-b.
GCP Windows Image (optional): Name of the image used for Windows builds. Leave this field blank if you do not require them.
GCP VPC Network (required): Name of the VPC Network.
GCP VPC Subnet (optional): Name of the VPC Subnet. If using auto-subnetting, leave this field blank.
GCP Service Account JSON file (required): Copy and paste the contents of your service account JSON file.
Configuring VM Service
Number of <VM type> VMs to keep prescaled: By default, this field is set to 0 which will create and provision instances of a resource type on demand. You have the option of preallocating up to 5 instances per resource type. Preallocating instances lowers the start time allowing for faster machine and
remote_dockerbuilds. Note, that preallocated instances are always running and could potentially increase costs. Decreasing this number may also take up to 24 hours for changes to take effect. You have the option of terminating those instances manually, if required.
VM Service Custom Configuration: Custom configuration can fine tune many aspects of your VM service. This is an advanced option and we recommend you reach out to your account manager to learn more.
Nomad
Configure aspects of your Nomad control plane here.
Enable Mutual TLS (mTLS)
mTLS encrypts and authenticates traffic between your Nomad control plane and Nomad clients. You should disable mTLS until you have completed Step 4 - Install Nomad Clients and can obtain the certificate, private key and certificate authority output after completing Step 4.
When all required information has been provided, click the Continue button and your CircleCI installation will be put through a set of preflight checks to verify your cluster meets the minimum requirements and attempt to deploy. When completed successfully, you should see something like the following and you can continue to the next step:
Step 3 - Obtain Load Balancer IPs
Run
kubectl get services and note the following load balancer addresses. You will need these to finish configuring your
installation.
Frontend External
Circleci Server Traefik Proxy
VM Service Load Balancer URI
Output Processor Load Balancer URI
Nomad Server Load Balancer URI
Depending on your cloud environment and configuration, your output can contain either an external IP address or a hostname for your load balancers. Either will work.
The values for VM Service, Output Processor and Nomad Server should be added into the config as described in Step 2 - Configure Server (Part 1). The value from Frontend External should be used in Step 5 - Create DNS Entries for the Frontend to create the DNS entry for your applications domain name and sub-domain.
If you had to leave the default value in place for the Nomad
server_endpoint in the previous step, you can now go back
to the terraform repository, fill in the correct value in
terraform.tfvars and run
terraform apply again.
Step 4 - Install Nomad Clients
As mentioned in the Overview, Nomad is a workload orchestration tool that CircleCI uses to schedule (via Nomad Server) and run (via Nomad Clients) CircleCI jobs.
Nomad client machines are provisioned outside the cluster and need access to the Nomad Control Plane, Output Processor, and VM Service.
CircleCI curates Terraform modules to help install Nomad clients in your cloud provider of choice. You can browse the modules in our public repository.
AWS
If you would like to install Nomad clients in AWS, create a file
main.tf file with the following contents:
# main.tf terraform {=3.0.0" } } } provider "aws" { # Your region of choice here region = "us-west-1" } module "nomad_clients" { source = "git::" # Number of nomad clients to run nodes = 4 subnet = "<< ID of subnet you want to run nomad clients in >>" vpc_id = "<< ID of VPC you want to run nomad client in >>" server_endpoint = "<< hostname:port of nomad server >>" dns_server = "<< ip address of your VPC DNS server >>" blocked_cidrs = [ "<< cidr blocks you’d like to block access to e.g 10.0.1.0/24 >>" ] }.
Google Cloud Platform
If you’d like to to install Nomad clients in Google Cloud Platform, create a file
main.tf. An example is provided below
to document common settings. For documentation on all available variables please see the
module README.
# main.tf provider "google-beta" { # Your specific credentials here project = "your-project" region = "us-west1" zone = "us-west1-a" } module "nomad_clients" { # Note the use of ref=<<tag>> to pin the version to a fixed release source = "git::" zone = "us-west1-a" region = "us-west1" network = "my-network" # Only specify a subnet if you use custom subnetworks in your VPC. Otherwise delete the next line. subnet = "my-nomad-subnet" # hostname:port of Nomad load balancer, leave port as 4647 unless you know what you are doing server_endpoint = "nomad.example.com:4647" # Number of nomad clients to run min_replicas = 3 max_replicas = 10 # Example autoscaling policy: scale up if we ever reach 70% cpu utilization autoscaling_mode = "ONLY_UP" target_cpu_utilization = 0.70 # Network policy example: block access to 1.1.1.1 from jobs and allow retry # with SSH from only 2.2.2.2 blocked_cidrs = [ "1.1.1.1/32" ] retry_with_ssh_allowed_cidr_blocks = [ "2.2.2.2/32" ] }.
Optional: Running Jobs Outside the Nomad Client
CircleCI Server can run Docker jobs on Nomad clients, but it can also run jobs in a dedicated VM. These VM jobs are controlled by Nomad clients, therefore the Nomad clients must be able to access the VM machines on port 22 for SSH and port 2376 for remote Docker jobs.
Step 5 - Create DNS Entries for the Frontend
Next, create a DNS entry for your external frontend and traefik load balancer, i.e.
circleci.your.domain.com and
app.circleci.your.domain.com, respectively. You will recall that in Step 2 - Configure Server (Part 1) we detailed how
to create TLS certs for your server install. Although TLS is optional, should it be used, it is important to ensure your TLS cert
covers both the server domain and sub-domain as in the examples provided. Once the user is logged in, all client requests
are routed through your traefik sub-domain, i.e,
app.{your_domain}.com.
For more information on adding a new DNS record, see the following documentation:
Step 6 - Configure Server (Part 2) and Deploy
Go back to the Config tab in the admin console.
Global Settings
Enter the values obtained from Step 3 - Obtain Load Balancer IPs into VM Service Load Balancer Hostname, Output Processor Load Balancer Hostname, and Nomad Load Balancer Hostname under Global Settings.
Nomad
mTLS encrypts and authenticates traffic between your Nomad control plane and Nomad clients. If you have already deployed the Nomad clients via terraform in Step 4 - Install Nomad Clients you can and should enable mutual TLS (mTLS).
Nomad Server Certificate (required if mTLS is enabled): Obtained in Step 4 - Install Nomad Clients.
Nomad Server Private Key (required if mTLS is enabled): Obtained in Step 4 - Install Nomad Clients.
Nomad Server Certificate Authority (CA) Certificate (required if mTLS is enabled): Obtained in Step 4 - Install Nomad Clients.
Deploy
Click the Save config button to update your installation and re-deploy server.
Step 7 - Validate Installation
Launch your CircleCI installation in your browser, for example.
. If you are using a self-signed TLS cert, you will see a security warning at this stage. You will need to use proper TLS certs if you want to avoid this.
Sign up/Log in into your CircleCI installation. As the first user to log in, you will become the administrator at this point.
Take a look at our Getting Started guide to start adding projects.
Use the CircleCI realitycheck repository and follow the README to check basic CircleCI functionality.
If you are unable to run your first builds successfully, start with the Troubleshooting guide for general troubleshooting topics, and the Introduction to Nomad Cluster Operation for information about how to check the status of Nomad Clients within your installation. | https://circleci.com/docs/2.0/server-3-install/index.html | CC-MAIN-2021-21 | refinedweb | 2,864 | 54.22 |
Ruby Array Exercises: Check whether the sum of all the 3's of an given array of integers is exactly 9
Ruby Array: Exercise-33 with Solution
Write a Ruby program to check whether the sum of all the 3's of an given array of integers is exactly 9.
Ruby Code:
def check_array(nums) sum = 0 i = 0 while i < nums.length if(nums[i] == 3) sum += 3 end i += 1 end return (sum == 9); end print check_array([3, 5, 3, 3]),"\n" print check_array([3, 3, 2, 1]),"\n" print check_array([3, 3, 3, 3]),"\n"
Output:
true false false
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to compute the sum of the numbers of an given array except the number 17 and numbers that come immediately after a 17. Return 0 for an empty array.
Next: Write a Ruby program to check whether the number of 2's is greater than the number of 5's | https://www.w3resource.com/ruby-exercises/array/ruby-array-exercise-33.php | CC-MAIN-2021-21 | refinedweb | 168 | 54.05 |
Opened 11 years ago
Last modified 8 years ago
#10750 needs_work defect
Fix solve so that additional args are properly handled
Description (last modified by )
In this ask.sagemath question, there is some inconsistency in our use of Maxima's solve, or possibly its solving.
s=list(var('s_%d' % i) for i in range(3)); var('x y z'); print solve([],s_0,s_1,s_2) print solve([z==z],s_0,s_1,s_2) print solve([z==z,y==y],s_0,s_1,s_2) print solve([z==z,y==y,x==x],s_0,s_1,s_2) print solve([s_0==0],s_0,s_1,s_2); print solve([s_0==0,s_1==s_1],s_0,s_1,s_2)
[[s_0 == c1, s_1 == c2, s_2 == c3]] ({s_0: r1}, []) [[s_0 == r6, s_1 == r5, s_2 == r4]] [[s_0 == r9, s_1 == r8, s_2 == r7]] ([s_0 == 0], [1]) [[s_0 == 0, s_1 == r11, s_2 == r10]]
Most of these do make sense, but you'll notice the change from complex to real variables, one place that seems to have a multiplicity, and the one with only a dictionary as output!
See also this sage-devel thread for another example of where this cropped up. We need to change the behavior of solve and the documentation to fix this.
Attachments (1)
Change History (15)
comment:1 follow-up: ↓ 2 Changed 11 years ago by
comment:2 in reply to: ↑ 1 Changed 10 years ago by
comment:3 Changed 10 years ago by
Okay, it turns out that there are a few problems here.
- When one solves a single
Expression, all args are passed to
Expression.solve()which means
s_1goes to
multiplicities, and so we are getting multiplicities with the trailing
[]and
[1].
- If one does this with three variables, then
solution_dictis also
Trueand we get the dict.
- Then there is the complex/real issue, which I haven't delved into.
We should fix this all so that the solutions make sense and are consistent.
comment:4 Changed 10 years ago by
comment:5 Changed 10 years ago by
comment:6 Changed 10 years ago by
- Summary changed from Unify certain solve outputs to Fix solve so that additional args are properly handled
comment:7 Changed 10 years ago by
The documentation for "solve" in symbolic/relation.py says that the arguments are
- ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict``
The function is defined as
def solve(f, *args, **kwds):. So I think we can assume that
args is the list of variables, whereas any keywords are in
kwds. So
- we should document some more possible keywords, like
multiplicities, or at least give pointers to documentation to any other solve routines which get called by this one, and
- if args has length greater than one, then we obviously shouldn't just call
Expression.solve(), but deal with it some other way. Can we just change the beginning?(This is completely untested. Maybe we also need to check
sage/symbolic/relation.py
diff --git a/sage/symbolic/relation.py b/sage/symbolic/relation.py
is_SymbolicVariable(args[0])...)
comment:8 Changed 10 years ago by
Some of the documentation things you mention are dealt with (to some extent) at #10444, which bitrotted a bit.
Your potential solution seems reasonable - really (as Jason implies in his post about the Python keywords issue) the args shouldn't go on without keywords in this case. I wouldn't worry as much about the
is_Symbolic... though I guess it couldn't hurt.
comment:9 follow-up: ↓ 10 Changed 10 years ago by
- Status changed from new to needs_review
Oh, I didn't see your comment, so I wrote a new patch which adds the same documentation as in #10444, although not quite in the same way. The attached patch passes doctests for me, at least for the patched file. It just adds one new doctest, to illustrate that you can solve for a single equation with respect to more than one variable.
I'm marking as this as "needs review", but it may just be a first draft. I certainly haven't tested it very thoroughly.
Changed 10 years ago by
comment:10 in reply to: ↑ 9 Changed 10 years ago by
I'm marking as this as "needs review", but it may just be a first draft. I certainly haven't tested it very thoroughly.
I think you changed the previous test, which is fine. But we should catch the
solution_dict issue as well (that is to say we should test that that error no longer occurs).
To test this, one should especially try to make things which previously would have gone into
Expression.solve break. For instance, we would want to make sure multiplicities still could work as well as possible. I think your code will keep that, but it's what would want to be checked. I do not think I will have time to do that right now, sadly.
Someone would also want to just check whether this is enough to close #10444 as a dup, which jhpalmieri is suggesting and I suspect is true.
comment:11 Changed 10 years ago by
- Keywords sd35.5 added
- Reviewers set to Paul Zimmermann
- Status changed from needs_review to needs_work
- Work issues set to error in Maxima
after importing the patch on top of sage-4.8.apha6, I get:
Loading Sage library. Current Mercurial branch is: 10750 sage: s=list(var('s_%d' % i) for i in range(3)); sage: var('x y z'); sage: print solve([],s_0,s_1,s_2) [ [s_0 == c1, s_1 == c2, s_2 == c3] ] sage: print solve([z==z],s_0,s_1,s_2) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) /localdisk/tmp/sage-4.8.alpha6/<ipython console> in <module>() /localdisk/tmp/sage-4.8.alpha6/local/lib/python2.6/site-packages/sage/symbolic/relation.pyc in solve(f, *args, **kwds) 736 raise 737 --> 738 if len(s)==0: # if Maxima's solve gave no solutions, try its to_poly_solve 739 try: 740 s = m.to_poly_solve(variables) /localdisk/tmp/sage-4.8.alpha6/local/lib/python2.6/site-packages/sage/interfaces/maxima_abstract.pyc in __len__(self) 1618 """ 1619 P = self._check_valid() -> 1620 return int(P.eval('length(%s)'%self.name())) 1621 1622 def dot(self, other): /localdisk/tmp/sage-4.8.alpha6/local/lib/python2.6/site-packages/sage/interfaces/maxima_lib.pyc in _eval_line(self, line, locals, reformat, **kwds) 418 statement = line[:ind_semi] 419 line = line[ind_semi+1:] --> 420 if statement: result = ((result + '\n') if result else '') + max_to_string(maxima_eval("#$%s$"%statement)) 421 else: 422 statement = line[:ind_dollar] /localdisk/tmp/sage-4.8.alpha6/local/lib/python2.6/site-packages/sage/libs/ecl.so in sage.libs.ecl.EclObject.__call__ (sage/libs/ecl.c:4732)() /localdisk/tmp/sage-4.8.alpha6/local/lib/python2.6/site-packages/sage/libs/ecl.so in sage.libs.ecl.ecl_safe_apply (sage/libs/ecl.c:2838)() RuntimeError: ECL says: Error executing code in Maxima: length: argument cannot be a symbol; found all
Paul
comment:12 Changed 10 years ago by
Paul's problem is just that Maxima recognized that everything is a solution and returned
all.
(%i1) solve(q=q,(w,y,z)); (%o1) all (%i2) solve(w=w,(w,y,z)); (%o2) all (%i3) solve(w=w,y); (%o3) all (%i4) solve(w=w,w); (%o4) all
We would need to special-case this somehow. Good eye!
Here's another place where someone might have run into this problem. We should really fix this soon.
comment:13 Changed 9 years ago by
comment:14 Changed 8 years ago by
I think is probably related to this as well.
AFAIK, the issue with only a dictionary output was fixed in #8553. Multiplicity seems to be (one of) the problem(s) in #5679. Perhaps we should make this ticket only about the real & complex variables.
There are so many tickets about
solve(). It would be good to make a trac wiki page to list all of them. This should help avoid duplicates. | https://trac.sagemath.org/ticket/10750 | CC-MAIN-2021-49 | refinedweb | 1,320 | 62.48 |
The java.io.PipedInputStream class and java.io.PipedOutputStream classes provide a convenient means to move data from one thread to another. Output from one thread becomes input for the other thread, as shown in Figure 9-1.
Figure 9-1. Data moving between threads using piped streams
public class PipedInputStream extends InputStream public class PipedOutputStream extends OutputStream
The PipedInputStream class has two constructors:
public PipedInputStream( ) public PipedInputStream(PipedOutputStream source) throws IOException
The no-argument constructor creates a piped input stream that is not yet connected to a piped output stream. The second constructor creates a piped input stream that's connected to the piped output stream source.
The PipedOutputStream class also has two constructors:
public PipedOutputStream(PipedInputStream sink) throws IOException public PipedOutputStream( )
The no-argument constructor creates a piped output stream that is not yet connected to a piped input stream. The second constructor creates a piped output stream that's connected to the piped input stream sink.
Piped streams are normally created in pairs. The piped output stream becomes the underlying source for the piped input stream. For example:
PipedOutputStream pout = new PipedOutputStream( ); PipedInputStream pin = new PipedInputStream(pout);
This simple example is a little deceptive because these lines of code will normally be in different methods and perhaps even different classes. Some mechanism must be established to pass a reference to the PipedOutputStream into the thread that handles the PipedInputStream. Or you can create them in the same thread, then pass a reference to the connected stream into a separate thread. Alternately, you can reverse the order:
PipedInputStream pin = new PipedInputStream( ); PipedOutputStream pout = new PipedOutputStream(pin);
Or you can create them both unconnected, then use one or the other's connect( ) method to link them:
PipedInputStream pin = new PipedInputStream( ); PipedOutputStream pout = new PipedOutputStream( ); pin.connect(pout);
Otherwise, these classes just have the usual read( ), write( ), flush( ), close( ), and available( ) public methods like all stream classes.
PipedInputStream also has four protected fields and one protected method that are used to implement the piping:
protected static final int PIPE_SIZE protected byte[] buffer protected int in protected int out protected void receive(int b) throws IOException
PIPE_SIZE is a named constant for the size of the buffer. The buffer is the byte array where the data is stored, and it's initialized to be an array of length PIPE_SIZE. When a client class invokes a write( ) method in the piped output stream class, the write( ) method invokes the receive( ) method in the connected piped input stream to place the data in the byte array buffer. Data is always written at the position in the buffer given by the field in and read from the position in the buffer given by the field out.
There are two possible blocks here. The first occurs if the writing thread tries to write data while the reading thread's input buffer is full. When this occurs, the output stream enters an infinite loop in which it repeatedly waits for one second until some thread reads some data out of the buffer and frees up space. If this is likely to be a problem for your application, subclass PipedInputStream and make the buffer larger. The second possible block is when the reading thread tries to read and no data is present in the buffer. In this case, the input stream enters an infinite loop in which it repeatedly waits for one second until some thread writes some data into the buffer.
Although piped input streams contain an internal buffer, they do not support marking and resetting. The circular nature of the buffer would make this excessively complicated. You can always chain the piped input stream to a buffered input stream and read from that if you need marking and resetting.
The following program is a simple and somewhat artificial example that generates Fibonacci numbers in one thread and writes them onto a piped output stream while another thread reads the numbers from a corresponding piped input stream and prints them on System.out. This program uses three classes: FibonacciProducer and FibonacciConsumer, which are subclasses of Thread, and FibonacciDriver, which manages the other two classes. Example 9-3 shows the FibonacciProducer class, a subclass of Thread. This class does not directly use a piped output stream. It just writes data onto the output stream that it's given in the constructor.
Example 9-3. The FibonacciProducer class
Example 9-4 is the FibonacciConsumer class. It could just as well have been called the IntegerConsumer class since it doesn't know anything about Fibonacci numbers. Its run( ) method merely reads integers from its input stream until the stream is exhausted. At this point, the other end of the pipe closes and an IOException is thrown. The only way to tell the difference between this normal termination and a real exception is to check the exception message.
Example 9-4. The FibonacciConsumer classm
Example 9-5 is the FibonacciDriver class. It creates a piped output stream and a piped input stream and uses those to construct FibonacciProducer and FibonacciConsumer objects. These streams are a channel of communication between the two threads. As data is written by the FibonacciProducer thread, it becomes available for the FibonacciConsumer tHRead to read. Both the FibonacciProducer and the FibonacciConsumer are run with normal priority so that when the FibonacciProducer blocks or is preempted, the FibonacciConsumer runs and vice versa.
Example 9-5. The FibonacciDriver class
You may be wondering how the piped streams differ from the stream copiers presented earlier in the book. The first difference is that the piped stream moves data from an output stream to an input stream. The stream copier always moves data in the opposite direction, from an input stream to an output stream. The second difference is that the stream copier actively moves the data by calling the read( ) and write( ) methods of the underlying streams. A piped output stream merely makes the data available to the input stream. It is still necessary for some other object to invoke the piped input stream's read( ) method to read the data. If no other object reads from the piped input stream, after about one kilobyte of data has been written onto the piped output stream, the writing thread blocks while it waits for the piped input stream's buffer to empty. | https://flylib.com/books/en/1.134.1/communicating_between_threads_using_piped_streams.html | CC-MAIN-2018-51 | refinedweb | 1,052 | 50.36 |
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
The header file 'boost/algorithm/cxx11/none_of.hpp' contains four variants
of a single algorithm,
none_of.
The algorithm tests all the elements of a sequence and returns true if they
none of them share a property.
The routine
none_of takes
a sequence and a predicate. It will return true if the predicate returns
false when applied to every element in the sequence.
The routine
none_of_equal
takes a sequence and a value. It will return true if none of the elements
in the sequence compare equal to the passed in value.
Both routines come in two forms; the first one takes two iterators to define the range. The second form takes a single range parameter, and uses Boost.Range to traverse it.
The function
none_of returns
true if the predicate returns false for every item in the sequence. There
are two versions; one takes two iterators, and the other takes a range.
namespace boost { namespace algorithm { template<typename InputIterator, typename Predicate> bool none_of ( InputIterator first, InputIterator last, Predicate p ); template<typename Range, typename Predicate> bool none_of ( const Range &r, Predicate p ); }}
The function
none_of_equal
is similar to
none_of, but
instead of taking a predicate to test the elements of the sequence, it takes
a value to compare against.
namespace boost { namespace algorithm { template<typename InputIterator, typename V> bool none_of_equal ( InputIterator first, InputIterator last, V const &val ); template<typename Range, typename V> bool none_of_equal ( const Range &r, V const &val ); }}
Given the container
c containing
{ 0, 1,
2, 3, 14, 15 },
then
bool isOdd ( int i ) { return i % 2 == 1; } bool lessThan10 ( int i ) { return i < 10; } using boost::algorithm; none_of ( c, isOdd ) --> false none_of ( c.begin (), c.end (), lessThan10 ) --> false none_of ( c.begin () + 4, c.end (), lessThan10 ) --> true none_of ( c.end (), c.end (), isOdd ) --> true // empty range none_of_equal ( c, 3 ) --> false none_of_equal ( c.begin (), c.begin () + 3, 3 ) --> true none_of_equal ( c.begin (), c.begin (), 99 ) --> true // empty range
none_of and
none_of_equal work on all iterators except
output iterators.
All of the variants of
none_of
and
none_of_equal run in
O(N) (linear) time; that is, they compare against each
element in the list once. If any of the comparisons succeed, the algorithm
will terminate immediately, without examining the remaining members of the
sequence.
All of the variants of
none_of
and
none_of_equal take their
parameters by value or const reference, and do not depend upon any global
state. Therefore, all the routines in this file provide the strong exception
guarantee.
none_ofis part of the C++11 standard. When compiled using a C++11 implementation, the implementation from the standard library will be used.
none_ofand
none_of_equalboth return true for empty ranges, no matter what is passed to test against.
none false (where
iteris an iterator to each element in the sequence) | http://www.boost.org/doc/libs/1_55_0/libs/algorithm/doc/html/the_boost_algorithm_library/CXX11/none_of.html | CC-MAIN-2014-10 | refinedweb | 480 | 55.44 |
String Representations
00:00 In this lesson, I’m going to tell you about string representations of time in Python. This is kind of on the far end of the continuum that I’ve been talking about for Python time object representations.
00:12 Strings are the most readable for human beings, but they’re the hardest to operate on for machines. When you craft a good string representation, what’s important is that you need to include all of the information that a user needs to interact with your application, but only that information that’s totally necessary.
00:29 That’s going to be the focus of this lesson.
00:33
There are three useful functions that I want to show you for time string conversion. The first is
time.asctime, which simply takes in an optional
struct_time or time tuple object, and just returns the timestamp, which is kind of a basic formatted string for the time.
00:51
strftime() (“string format time’), in a kind of opposition to that, is a much more flexible, but also more labor-intensive, way to get a string version of a time, because you have to pass in a directive string, I’ll explain that in a little bit, and then a
struct_time.
01:05
It returns the specified string version based on what you pass in as the directive.
time.strptime (“string parse time”) just does the opposite, where it takes in an already formatted string and the directive that was used to format that string, and it returns the
struct_time object based on that data.
01:23
If you pass in no directive, it will assume that this time string is in timestamp format, so you can pass the result of
time.asctime(), to
time.strptime without any directive, and you’ll get a correct
struct_time object out of that.
01:37 Let’s take a look at these directives in a little more depth. The directives, also called format strings, are essentially just a language of special characters that allows you to create format strings, which are combinations of normal characters and these special format characters, which then give an output of some date or time format.
02:00
And so, for example, if I pass in
"%a, %B %d" I get abbreviated weekday for little
a,
02:09
I get the full month name for big
B, and then I get the zero-padded decimal day for
%d. And of course, the comma in here just stays in its same place because it’s not a special character, and the same goes for this
"%m/%d/%Y" (“month/day/year”) format, where the slashes stay in the same place. And then, of course, down here all of the words and other letters stay in the same place, except for the things directly following the percent sign.
02:35
So it’s a very flexible language and it works a lot like C’s
printf() syntax if you’re familiar with that. If you’re not, that’s not a big deal, just know that these format characters are directly substituted with the thing that they correspond to from the date that you are actually using, the date or the time that you’re actually using to create this string.
02:55
So you pass a format string and you pass a time object, and then these fields are automatically filled based on the data from the time object by
strftime, or vice versa, they’re parsed by
strptime, so that’s very convenient.
03:10
Let’s move over into the Python REPL and take a look at how this works in practice. As usual, let’s start out by importing
time.
03:18
The first function I want to show you is the simplest, which is just
time.asctime. As you’ll remember from the previous slides, it takes in an optional time tuple, but if you don’t pass anything in it will just use the current local time and convert that to a timestamp, as you can see here. So it’s Monday, May 4th, “May the 4th be with you,” and it is 13:40 in the afternoon with 13 seconds gone by in the year 2020.
03:45 This gets you pretty much all the information you could want to know about the date in a kind of passing glance of the date and time, but it really is not very flexible, because it doesn’t allow you to include less or more of that information as might be necessary for your application.
04:02 So for example, in a calendar application, it wouldn’t make much sense to have an abbreviated month, and you might also want to include the option to have 12-hour time for users in countries that don’t tend to use 24-hour time.
04:16
Maybe you might also want to have the day of the week or something like that, so there’s a lot of information that you can either add or delete from this, that
asctime doesn’t allow you to do.
04:25
That’s where
time.strftime() comes in, and as you remember, you need to pass in a format string. I’ll start off with something simple, just the year, the month, and the day.
04:36 It also takes in an optional second parameter, and just to show you that this is in fact the same, I’m going to just pass this explicitly, even though this is what it will default to anyway. And as you can see, I get the year 2020, the month is the 5th month and the day is the 4th day.
04:54 But maybe you want a more verbose string representation, more suitable for a more text-based application, and so you might say something like, “In the year,
05:05
%Y, it was the warm spring month of
%m
05:15
on the day,
%d.” And I don’t need to pass this parameter in. And so, “In the year 2020, it was a warm spring month of 05 on the 04 day.” But this isn’t super helpful, because obviously “this warm spring month of 05,” that doesn’t tell you much, and so what you might want to do instead is replace this with a capital
B, which will give the full month name, and that might be more useful.
05:38
And then you could add really any number of different things in here. You could put in all sorts of different characters, but I’ll let you play around with that on your own time, especially by looking at the
time module documentation, to find all of these different format characters you can have to make your time output really pretty. So that’s good, and it gives us a way to have all, but only the necessary, information to convey in your application. Now, if you want to reverse this, you can use
strptime().
06:06 And as I mentioned in the slides a second ago, if you don’t give it any particular format argument, it will just assume that the string passed in is a timestamp.
06:16
And so I’ll just use
time.asctime() as the string parameter and then I won’t pass in a format parameter. As you can see, this just gives me the current time as a
struct_time.
06:27
So this is kind of a super, super roundabout way to just say
time.localtime(). And as you can see, these turn out to be almost exactly the same thing and the “almost” is just because I called them at different times.
06:37
So that’s how you can parse a timestamp, and then if you want to parse something more complicated, you could do something like this, where you give it a string, and let’s say something like 2020, let’s do the string that I did up here,
"2020-05-04" and then I have to give it the format string that I used there, which was
"%Y-%m-%d" and as you can see, it will just give me the
struct_time object, but of course what you might realize already is that you might lose some information when you do something like this. So
strptime() is super useful, but you also have to be careful because, in this representation, I don’t give an hour, a minute, a second, a weekday, anything like that.
07:21
The weekday is parsed, but I don’t give an hour, a minute, or a second, or anything like that, and I don’t specify whether the time is daylight savings. And so you lose, or you don’t lose information, but there is information that a
struct_time can convey that this time representation doesn’t actually do justice to.
07:37
And so you have to be careful with that when you’re working with these times. I want to show you one more thing here, which is how
asctime() and
strftime() respond differently to changes in locale information. Let me just clear my screen real quick.
07:53
What I want to show you is how, if you change the locale, it can change the output of your string formatting functions, but not for all of them. So, what I want to do first, before I change my locale, is I’ll just show you, I have to
import time, of course,
time.asctime, and then
time.strftime.
08:14
And what I’m going to do is I’m going to just use the
"%c" directive, which just returns a locale-specific timestamp. So as you can see, these both have the same exact format, but now if I change my locale, so I’m going to say
locale.setlocale, and I have to pass in a category, so it’s going to be
category.LC_TIME, so the time section of the locale, and if you want more information about this, I would say your best bet is to go to the
locale documentation, just because there’s a lot more to it than I can explain here, but I’m going to set it to the German locale,
"de_DE".
08:51
And then what I can do is I’ll show you, first,
asctime, and as you can see, this just doesn’t change at all from what it was with the other locale, which was English USA. That was my first locale. I didn’t actually print it out, but that’s what it was. It was
"en_US".
09:10
So that doesn’t change, the
asctime, but if I do
time.strftime and I pass it in this
"%c" directive, then that actually does change to reflect the differences in spelling from the German locale. So “Mai” as opposed to “May”, and “Montag”, as opposed to “Monday”, and they have different abbreviations in the different languages.
09:33
So you can see that
strftime() is actually sensitive to locale-specific data. And you can see this, as well, if I do something like just, I’ll say, let’s do the full month name. And as you can see, that’s
"Mai", so
time.strftime is sensitive to the locale.
09:51 That’s something that’s really important to note when you’re using these functions: you want to always make sure you know what is going to be changing based on the locale of your user. With that in mind, in the next lesson, I’m going to go through just a couple of quick little functions that the time module offers to work with performance in Python.
10:11 That’s going to be measuring performance with a precision time counter, and then also sleeping your current thread execution and the different benefits that that can have.
Become a Member to join the conversation. | https://realpython.com/lessons/string-representations/ | CC-MAIN-2021-17 | refinedweb | 2,008 | 72.5 |
Suites are a way to package and distribute applications in a common framework to give a common look and feel, or to group functionality under a common container. Extending the suite to add new applications, or to update existing ones, can be problematic. The approach I will demonstrate here is to use dynamic runtime discovery to load applications from DLLs.
The Outlook Bar used in this project is from Marc Clifton�s article An Outlook Bar Implementation. I made a small modification to support an additional field.
The suite container is the shell that holds everything together. It gives the applications a common look and feel, menu items, and basically a place to hang out. For this project, I�ve created a very simple container with an Outlook Bar to group and show loaded apps and an area to display the apps interface.
When the suite container starts, it needs to look for any applications to load. One way to do this is to have it search a given path for any DLLs and attempt to load them. The obvious problem with this approach is that the path may contain support DLLs that can�t, or should not, be loaded. A way to get around this is to use custom attributes to indicate that the class, or classes, within the DLL are meant to be part of the application suite.
public static Hashtable FindApps() { // Create hashtable to fill in Hashtable hashAssemblies = new Hashtable(); // Get the current application path string strPath = Path.GetDirectoryName(ExecutablePath); // Iterate through all dll's in this path DirectoryInfo di = new DirectoryInfo(strPath); foreach(FileInfo file in di.GetFiles("*.dll") ) { // Load the assembly so we can query for info about it. Assembly asm = Assembly.LoadFile(file.FullName); // Iterate through each module in this assembly foreach(Module mod in asm.GetModules() ) { // Iterate through the types in this module foreach( Type t in mod.GetTypes() ) { // Check for the custom attribute // and get the group and name object[] attributes = t.GetCustomAttributes(typeof(SuiteAppAttrib.SuiteAppAttribute), true); if( attributes.Length == 1 ) { string strName = ((SuiteAppAttrib.SuiteAppAttribute)attributes[0]).Name; string strGroup = ((SuiteAppAttrib.SuiteAppAttribute)attributes[0]).Group; // Create a new app instance and add it to the list SuiteApp app = new SuiteApp(t.Name, file.FullName, strName, strGroup); // Make sure the names sin't already being used if( hashAssemblies.ContainsKey(t.Name) ) throw new Exception("Name already in use."); hashAssemblies.Add(t.Name, app); } } } } return hashAssemblies; }
As you can see from this code, we are searching the application path for any DLLs, then loading them and checking for the presence of our custom attribute.
t.GetCustomAttributes(typeof(SuiteAppAttribute), true);
If found, we then create an instance of the
SuiteApp helper class and place it in a
Hashtable with the apps name as the key. This will come into play later when we need to look up the app for activation. It does place the limit of not allowing duplicate application names, but to avoid confusion on the user end, it is a good thing.
Attributes are a means to convey information about an assembly, class, method, etc. Much more information about them can be found here, C# Programmer's Reference Attributes Tutorial. In the case of this project, a custom attribute is created and used to give two pieces of information necessary for the suite to load any app it finds. First, just by querying for the mere presence of the attribute, we can tell that the DLL should be loaded. The second part of information we get from the attribute is the name of the Outlook Bar group it should be added to and the name to be shown for the application.
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)] public class SuiteAppAttribute : Attribute { private string m_strName; private string m_strGroup; /// <SUMMARY> /// Ctor /// </SUMMARY> /// <PARAM name="strName">App name</PARAM> /// <PARAM name="strGroup">Group name</PARAM> public SuiteAppAttribute(string strName, string strGroup) { m_strName = strName; m_strGroup = strGroup; } /// <SUMMARY> /// Name of application /// </SUMMARY> public string Name { get{ return m_strName; } } /// <SUMMARY> /// Name of group to which the app /// should be assigned /// </SUMMARY> public string Group { get{ return m_strGroup; } } }
The first thing to note here is the attribute applied to this custom attribute.
[AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]
This tells the runtime that this particular custom attribute can only be applied to a class and further can only be applied once.
To create applications to become part of our suite, we need to start with the
Build event. To facilitate debugging, the application(s) must be moved to a location where the suite container can detect and load them. This step can be automated by adding a post-build step.
copy $(TargetDir)$(TargetFileName) $(SolutionDir)SuiteAppContainer\bin\debug
Provided that everything is in the same solution, this will copy the output of the application's compile step to the debug folder of the suite container.
To activate the application once the icon has been selected, we first make a check that it does indeed exist in the
HashTable, if not there are some real problems. We also need to make sure the form has not already been created. Once these checks are verified, the path to the assembly is located and loaded. The
InvokeMember function is used to create an instance of the form in question. We set a handler for the form closing event, so it can be handled as we�ll see later.
public void OnSelectApp(object sender, EventArgs e) { OutlookBar.PanelIcon panel = ((Control)sender).Tag as OutlookBar.PanelIcon; // Get the item clicked string strItem = panel.AppName; // Make sure the app is in the list if( m_hashApps.ContainsKey(strItem) ) { // If the windows hasn't already been created do it now if( ((SuiteApp)m_hashApps[strItem]).Form == null ) { // Load the assembly SuiteApp app = (SuiteApp)m_hashApps[strItem]; Assembly asm = Assembly.LoadFile(app.Path); Type[] types = asm.GetTypes(); // Create the application instance Form frm = (Form)Activator.CreateInstance(types[0]); // Set the parameters and show frm.MdiParent = this; frm.Show(); // Set the form closing event so we can handle it frm.Closing += new CancelEventHandler(ChildFormClosing); // Save the form for later use ((SuiteApp)m_hashApps[strItem]).Form = frm; // We're done for now return; } else { // Form exists so we just need to activate it ((SuiteApp)m_hashApps[strItem]).Form.Activate(); } } else throw new Exception("Application not found"); }
If the form already exists then we just want to activate it, bring it to the front.
((SuiteApp)m_hashApps[strItem]).Form.Activate();
We need to be able to capture when the child forms close so that the resources can be freed and when it is required again the form will be recreated rather than attempting to activate a form that has already been closed.
private void ChildFormClosing(object sender, CancelEventArgs e) { string strName = ((Form)sender).Text; // If the app is in the list then null it if( m_hashApps.ContainsKey(strName) ) ((SuiteApp)m_hashApps[strName]).Form = null; }
The next area to address are the menus. The main container app has a basic menu structure and each application it houses will have its own menus, some with the same items.
Combining menus isn�t terribly difficult; it just takes some attention to detail and planning. The menu properties
MergeType and
MergeOrder are used to sort out how the menus are merged and where the items appear. The default settings are
MergeType = Add and
MergeOrder = 0. In the case of this example, we want to merge the File menu of the container app with the File menu from the child app. To start with, we need to set the
MergeType of the main window file menu to
MergeItems. The File menu in the child app must also be set to
MergeItems.
This gets a little closer but as can be seen, we have duplicates of some items. I�ve renamed the child�s exit menu to better illustrate the problem. To correct this, we need to change the main window�s exit menu item to
MergeType = Replace.
Now, we have the expected results. The next step is to set the
MenuOrder. This doesn�t affect the merging of the menus but does affect where the items appear. Reviewing the sample project, we can see that the exit menu items have a
MergeOrder of 99. Merging starts at 0 with higher numbered items being merged lower in the menu.
By setting the
MergeOrder to 0, we see that the exit menu item is placed higher in the file menu.
This is certainly not an earth shattering killer application. What I hope is, it is a learning tool to explorer capabilities and present the seeds for thought, possibly some of the techniques can be incorporated into other applications.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/suiteapp.aspx | crawl-002 | refinedweb | 1,438 | 63.8 |
This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Good remark
Posted by Herman Jansen on 03 Nov 1998, 3:31 AM
I think your remarks are very good and surely valid. In my opinionaggragation and compostion is very much the same. There is nodifference in the code when you look at composition or aggragation.It is more a subjective semantic thing. It is how much you feelsomething is a part of something else. It is clear that your armsand legs are part of yourself and should be considered aggragation.But what about the clothes you wear. Is that a composition oran aggregation ?I think both are right, it is just the context you are working in.The code you produce will be the same
> Hi,
> What about aggregation ? Is it not the other side of composition ? I view aggregartion as holding a reference to an object which exist outside the current object, otherwise same as composition.
> Couple of good thigs happen here:
> 1. Performance hit might be reduced as the object is already created
> 2. More importantly, it can do distributed processing ! The aggregated object need not me in the same namespace of the aggregator !(Pardon the nouns). Try to do this with inheritence !
> I think, when we talk about composition, we should consider aggregation also especially in this age of distributed computing.
> cheers | https://www.artima.com/legacy/design/compoinh/messages/23.html | CC-MAIN-2017-51 | refinedweb | 251 | 67.96 |
If you have done some dev stuff with MOSS you have most likely seen this:
“An unexpected error has occurred. ” is something that you probably don’t want to see at your browser…. you want to have customized error page. In ASP.NET application you normally put Application_Error into you global.asax file. However in SharePoint that place has been taken by the product itself 🙂 So if you want to do customized approach then you can take HttpModule approach which I’m going to go through in this post.
So let’s create our custom exception handler http module. Here’s the code for that:
You can probably see from the code that I’ll attach my code to the Error event and in my event I’ll do some basic stuff and then transfer to my MyCustomErrorPage.aspx. I used Server.Transfer just because I want user to stay at the same url where exception happened. If I would use Response.Redirect it would “change” the url at the users browser. Same “change” would happen if your custom error page would be normal SharePoint publishing page (i.e. /Pages/MyCustomErrorPage.aspx). If the url stays the same the user can actually press F5 and retry the operation right away. Of course it can be bad thing too and you may want to redirect to another page to avoid creating the same exception all over again. I’ll let you decide what you want 🙂 So do some testing and then decide what’s good for you.
But one important thing to notice. You need to put your IHttpModule before SharePoint specific modules in your web.config or otherwise your error routines may not work as you would expect. Here’s example from that:
See line 6 where I put my exception handler definition.
Anyways… Happy hacking!
J
PingBack from
Hacía tiempo que no revisaba mis RSS sobre SharePoint , y claro me ha costado ponerme al día, y aquí
I am getting error saying that The given assembly name or codebase was invalid.
Janne,
We tried the same appraoch by creating a HTTPmodule hooking to Error event and registered the same as a first module in MOSS web.config.But it did not work for us !
Do you have any idea that what may be the cause of the issue ?
Regards,
Ram
Hi Ram!
Are you able to debug your code? I mean that if you attach your VS to the w3wp.exe process you’re able to step through the lines of you handler?
J
Janee,
But when i deployed the http module i get this error:
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047
Line 146: <add name="MyExceptionHandler" type="MyExceptionHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=229eff298acf7a7d" />
Thank f for that. 1st person suggesting a solution. My inferior but workable solution was to remove the error.aspx page from the layouts folder – the application_error event then fires in global.asax and I was able to handle it there.
Just wondering, can something similar be done for unauthorised access errors?
Will your saolution work when the message is
File not found?…
I created the httpmodule and added the tag in Web.config.
<httpModules>
<clear />
<add name="SABICCustomError" type="SABICCustomError,SABICCustomError, Version=1.0.0.0, Culture=neutral, PublicKeyToken= 80a3837ac70f49e8" />
Attaching debugger and putting a breakpoint doesnt works.
Looking forward for any help.
namanc@gmail.com
what can you do if you limit a survey to only one response and the user gets an error page instead of a friendly "sorry, you cannot take the survey more than once." and then return them to the home page.
Neat! I like that.
One question though – what if I just want to use the HTTPModule to change the master page my error master page uses, rather than the simple.master it normally uses? I don’t seem to be able to do that.
Or, come to that, of redirecting the error pages for a single site/url? Hmm. Tricky.
m3rd, I suppose you could use what Janne has built above, but look at the error and if it is the survey exception, cancel the error and redirect to your own page with that message.
Nice and Elegant….
I was using before this approach which i think is worse than the one proposed by Janne
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler ( OnUnhandledException );
private void OnUnhandledException ( object sender, UnhandledExceptionEventArgs e )
{
Logger.Log ( e.ExceptionObject.ToString ( ), CATEGORY_UNHANDLED_EXCEPTIONS );
}
I’m having trouble implementing this. I’m using it in conjunction with stsdev. The error never gets attached. Am I missing something? Any ideas/tips to get started?
This was a nice insight into Error Handling in SharePoint and very useful. I’ve implemented more-or-less your design with a few additional logical paths to decide how to handle errors based on the web.config file settings. We also had a requirement to log any exceptions so we opted for the EventLog (which needed to be called by an elevated method call using SPSecurity) which again works perfectly.
We’ve had a couple of Publishing-based projects recently that have certainly benefited from this so many thanks again. 😉
Hi, I have check this approach and it works fine for me. My custom page uses simple.master (just like error.aspx). I just need to ask if there would be any way to replace simple.master with my custom.master page.
Hi,
I am able to create my on Custom Error Page with this approach, but some time it is throwing error in HTTPModule on Server.Transfer Statement. The error description is ""Error executing child request for ___.aspx". Can any body tell me regarding that. What workaround do i have to do for that. Note down that I implement this for my Custom Sharepoint (MOSS) Site.
To fix Given assembly or code base name is invalid error,
Go to SharePoint site Web.Config file
Add the newly created modules like below
<add name="Class Name" type="NameSpace.ClassName,NameSpace, Version=1.0.0.0, Culture=neutral,PublicKeyToken=Token" />
please make sure that replace classname,namespace and token value according to your project
That's lengthy solution. Try following one.
go to web.config file.
1)“>
2) And
<customErrors mode=“On“ />
To
<customErrors mode=“Off“ />
That's it… Simple !
I have implemented custom error handling mechanism in the similar way (Using Http Module).
But when I browse for this page http://<SiteURL>/_layouts/addcontentsource.aspx , I still get the sharepoint error page with the following error message:
"This page is accessible only from a Shared Services Provider admin site."
What could be the issue here ? | https://blogs.msdn.microsoft.com/jannemattila/2008/02/04/catching-unhandled-exceptions-in-sharepoint/ | CC-MAIN-2017-22 | refinedweb | 1,113 | 67.25 |
in reply to
Re^2: The App:: namespace? Sharing a webapp on CPAN
in thread The App:: namespace? Sharing a webapp on CPAN
I'm not sure what you want to point out with that link. I know there are scripts there, but that doesn't change my opinion that it's not the best space for scripts to begin with. HTML::Template can also be found on freshmeat. Not the best place IMHO.
Where do you think is a good place for fairly short scripts (as opposed to large "apps" that might merit their own google-code/freshmeat/whatever)?
Benefits include:
If scripts are too small for sourceforge, it's probably a quick hack to perform task X. Cool Uses For Perl looks like a good place, or Snippets.
Hell yes!
Definitely not
I guess so
I guess not
Results (44 votes),
past polls | http://www.perlmonks.org/index.pl?node_id=685655 | CC-MAIN-2014-52 | refinedweb | 145 | 83.05 |
Opened 11 years ago
Closed 8 years ago
#3508 closed (fixed)
MergeDict needs more descriptive return values from __str__ and __repr__
Description
Since MergeDict is a subclass of object, it inherits the default str and repr methods. The default methods are very generic and not as useful as they could be, especially when you're trying to inspect objects.
I'm submitting a patch that gives a detailed representation of the instance data when you run str(myMergeDict) and returns an "eval-able" value when you run repr(myMergeDict).
Attachments (2)
Change History (15)
Changed 11 years ago by
comment:1 Changed 11 years ago by
Offhand, django is still targeting python 2.3; you're using a genexp in the repr which is py2.4. Bit of a no go.
Also, use iteritems. No point in having the interp. build the intermediate list...
comment:2 Changed 11 years ago by
Brian's comment is correct: the patch needs to work with Python 2.3.
comment:3 Changed 11 years ago by
OK, I am attaching another patch that I tested in Python 2.3. It uses a list expression in place of the genexp in the repr.
However, I'm not sure where I could use iteritems. MergeDict isn't like a normal dict. The data isn't stored the same, and MergeDict itself doesn't have an iteritems method. Could you be more specific about where you would use iteritems?
Changed 11 years ago by
MergeDict patch that works with Python 2.3
comment:4 Changed 11 years ago by
An example of how this patch might be used:
> python2.3 Python 2.3.6 (#1, Feb 15 2007, 22:57:09) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from django.utils.datastructures import MergeDict >>> a = MergeDict({'a': 1, 'b': 2}, {'id': 'asdf', 'user': 'joe', 'color': 'blue'}) >>> str(a) "{'a': 1, 'color': 'blue', 'b': 2, 'id': 'asdf', 'user': 'joe'}" >>> repr(a) "MergeDict({'a': 1, 'b': 2}, {'color': 'blue', 'id': 'asdf', 'user': 'joe'})" >>>
comment:5 Changed 11 years ago by
No iteritems on MergeDict? Bah. Simple solution, add one ;)
Bit curious why MergeDict doesn't support the full dict protocol though; iteritems specifically would be useful compared to the current implementation.
Would use a map personally, but list comp seems preferred in the src.
Meanwhile, back to the patch- str output won't be valid;
>>> print MergeDict({1:2}, {1:3}) {1:3} >>> print MergeDict({1:2}, {1:3})[1] 2
Fault lies with MergeDict diverting from the dict protocol; its items is a list built via L->R walk of the internal dicts, concating the list on the end as it goes. Dict instantiation works via just walking the args, adding them- meaning the rightmost key wins.
you want-
def __str__(self): l = self.items() l.reverse() return str(dict(l))
Although personally, I'd look at making MergeDict into a proper dict, and just using return str(dict(self.iteritems())) # till someone gets bored and implements it efficiently.
comment:6 Changed 11 years ago by
Brian,
I would also have implemented MergeDict differently. However, my intent for this patch was not to change how MergeDict behaved - just to add the "documenter" methods to make debugging and interactive inspection of request.REQUEST easier.
Grepping the code yielded the following example as the only way that MergeDict is used:
self._request = datastructures.MergeDict(self.POST, self.GET)
I'm happy to re-work the request.REQUEST and MergeDict implementations if that is what the community desires. Again, my initial goals were to minimize API impact while enhancing the inspection-related properties of the class.
comment:7 Changed 11 years ago by
Also see the REQUEST docs:
They say the REQUEST searches POST first, then GET.
All-in-all, very low impact. I don't care if this gets merged in - I've even stopped using REQUEST myself. I just thought it might be useful to others. <shrug>
comment:8 Changed 11 years ago by
comment:9 Changed 11 years ago by
comment:10 Changed 11 years ago by
comment:11 Changed 8 years ago by
Aside from Brian Harring's comment, this patch is low impact and just does what it says, adds better str and repr and nothing else. The 2.4 version is sufficient now that 2.3 is no longer supported.
comment:12 Changed 8 years ago by
Can we get this checked in? contrib.auth.views has several uses of request.REQUEST, and I just had the occasion to need to inspect them. Having this patch would have made life easier, for sure.
patch to add str and repr to MergeDict | https://code.djangoproject.com/ticket/3508 | CC-MAIN-2018-17 | refinedweb | 791 | 73.47 |
pcre2_get_mark (3) - Linux Man Pages
pcre2_get_mark: Perl-compatible regular expressions (revised API)
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
SYNOPSIS
#include <pcre2.h>
PCRE2_SPTR pcre2_get_mark(pcre2_match_data *match_data);
DESCRIPTION
After a call of pcre2_match() that was passed the match block that is this function's argument, this function returns a pointer to the last (*MARK), (*PRUNE), or (*THEN) name that was encountered during the matching process. The name is zero-terminated, and is within the compiled pattern. The length of the name is in the preceding code unit. If no name is available, NULL is returned.
After a successful match, the name that is returned is the last one on the matching path. After a failed match or a partial match, the last encountered name is returned.
There is a complete description of the PCRE2 native API in the pcre2api page and a description of the POSIX API in the pcre2posix page. | https://www.systutorials.com/docs/linux/man/docs/linux/man/3-pcre2_get_mark/ | CC-MAIN-2021-17 | refinedweb | 152 | 61.36 |
I’m actually to lazy to write a full argument here, so I will just post my bullshit filler crap from a recent research paper:
5.3 Designing a Graphical User Interface
The discussion of GUI design should start by choosing appropriate widget toolkit. Java offers developers several attractive graphical environments. We will first take a closer look on each of them. Visualization details will then be explained in terms of that chosen toolkit.
5.3.1 Choosing a Widget Toolkit
There are three competing major widget toolkits that can be used for building graphical user interfaces in Java: AWT, Swing and SWT. Both AWT and Swing are currently included in Java Standard Edition, while SWT is an external set of libraries that needs to be downloaded and deployed separately.
The AWT toolkit was the first widget system implemented for Java. It is composed from fairly simple wrapper classes which in turn make calls to the native windowing environment to display GUI elements. Since each platform has a different set of native widgets, Sun only included the most basic ones in AWT [37].
Swing toolkit was developed in 1998 as a replacement of AWT. It abandoned the idea of using the systems native windowing environment, and designed a complete, feature rich widget toolkit entirely in Java. Swing is still in active development, and offers an impressing number of different graphical tools and GUI elements to the developers. For example, the package included in Java 1.4 includes 85 public interfaces, and 451 public classes [40].
The pure Java implementation however has proved to be both a blessing and a curse for this toolkit. Since Swing elements are really Java objects, they can only communicate with the underlying operating system through the JVM. In some cases this can create significant overhead, and thus Java based interfaces will often appear
to be less responsive, or slower than their native counterparts [37].
The Standard Widget Toolkit (SWT) [41] developed by IBM is a hybrid between Swing and AWT. It combines both approaches by including both calls to native widget elements, as well as implementing pure Java based ones. This helps to significantly improve the performance without sacrificing any of the advanced features one may
look for in an enterprise grade product [37].
The difference in performance, and responsiveness between Swing and SWT however is widely disputed and highly controversial. For example some benchmarks claim that Swing can outperform it’s competitor with respect to speed of rendering and re drawing windows on non-windows platforms [42]. Thus is is not very clear if SWT is really faster than Swing, or if overhead of the native calls and communication between Java and non-Java elements diminishes any performance gains stemming from using a native widget implementation.
Benchmarking the two toolkits is out of scope for this paper, and thus we chose Swing as our GUI toolkit because it is a Java standard, and it reduces the complexity of our code by eliminating dependency on a third party library.
Bibliography
[37] S. Holzner, Eclipse: Programming Java Applications. O’Reilly, 2004.
[40] R. Eckstein, J. Elliott, B. Cole, D. Wood, and M. Loy, Java Swing. O’Reilly, 2002.
[41] “The standard widget toolkit,” IBM. [Online]. Available:
[42] I. Kriznar, “Swt vs. swing performance comparison,” Cosylab D.O.O, 2005. [Online]. Available Here
© 2007 Lukasz Grzegorz Maciak
I pulled the above from a draft version because it’s late, and I don’t feel like locating the finalized reviewed document. So there might be typos and grammar errors in there – which is of course nothing new around ere.
I ended up using Swing, and perhaps it was not the best choice. Not for an image processing application perhaps. So you tell me. Which one is better in your experience. Is SWK really that much faster than Swing? Is the added speed worth the hassle of bundling it with correct SWK packages for correct systems?
I would love to hear from bit SWK supporters – what are the best selling points of this widget kit over Swing, other than the speed? Anyone knows any good benchmark tests that were done to compare these?
I will have to make this same decision for another project soon, and as usual I’m not entirely convinced which one to choose. I’m leaning towards Swing because I worked with it before, and I know at least some of it’s quirks and pitfalls to be avoided. SWK would be a completely new ballgame.
What do you think?
[tags]java, swing, swk, gui widgets, gui toolkits, gui, java gui, ibm, sun[/tags]
As to image processing application, your choice of swing is correct. Swing may not be faster than SWT. But as an image and graphics tools, it has lots of advantages over SWT.
What do I think?
I think if your first sentence is telling me you’ve posted the bullshit from your paper, then I’m not going to waste my time.
I’m looking for reviews on the best choice for a Java GUI toolkit (or at least an unbiased comparison). But it’s nowhere to be found. | http://www.terminally-incoherent.com/blog/2007/06/30/java-swing-or-swt-which-one-is-better/ | CC-MAIN-2014-35 | refinedweb | 858 | 64.2 |
:
Swing / AWT / SWT
Which Container should I use?
Jay Brass
Ranch Hand
Posts: 76
1
posted 7 years ago
I have a GUI with a row of buttons across the top. Clicking one of those buttons will display a column of buttons down the left hand side. Clicking one of the column buttons will display a row of buttons across the bottom of the screen. Clicking on each button will also show a grid of data in a JTable displayed in the middle of the screen. The purpose is each new set of buttons will allow the user to drill down to finer detail about the data being displayed. The data comes from a SQL Server database. What I want to do, is to hold all of the buttons in some sort of container so I never have to go to the database to get new buttons. The first buttons along the top, Level1, each have their own specific set of buttons that will show up on the left hand side in a column, Level 2. So button 1 will show different buttons in the column then button 2. Each button in the Level 2 column also has a specific set of buttons to show along the bottom, Level 3, so that the top button will show different buttons along the bottom then the next button down. I had thought of a 3 dimensional HashMap, if there is such a thing. The top map would have a button ID as the key, and the value would be another HashMap containing a button ID as the key and another HashMap as the value. The final map would have a button ID and the name to be displayed as the value. I'm not sure this is the best approach. I want to tie them all together, so that each Level 1 button and it's respective Level 2's with their Level 3's are easily accessible. A tree comes to mind but I can't figure out the best solution. Has anyone ever done anything like this?
Currently, I go to the database to get the Level 1 buttons. When one is clicked, I go to the database to get the Level 2 buttons that are specific to the Level 1 button that was clicked. When a Level 2 button is clicked, I go to the database to get all of the Level 3 buttons that are specific to the Level 2 button clicked. I would like to avoid all this back and forth to the database.
Thanks,
Maneesh Godbole
Bartender
Posts: 11445
18
I like...
posted 7 years ago
Buttons in the database? You will have to provide some more clarification on this on.
GUI related. Moving to the proper forum.
[
How to ask questions
] [
Donate a pint, save a life!
] [
Onff-turn it on!
]
Paul Clapham
Sheriff
Posts: 24366
55
I like...
posted 7 years ago
So each button at level 1 has a
list
of buttons which are at level 2? And each button at level 2 has a
list
of buttons which are at level 3? Then I know what collection I would use to store the relationships.
Jay Brass
Ranch Hand
Posts: 76
1
posted 7 years ago
Thanks for assigning this topic to the proper forum. The button names are contained in the database, that is true. What I need is a container, a HashMap, a 3 dimensional Array, or something to hold the buttons. They have a 1 to many to many relationship with other buttons on the screen. Maybe an example would be better.
Along the top of the GUI are buttons "CAT" "DOG" "Dinosaur"
Pressing the cat button would display down the left side:
HouseCat
Lion
Tiger
Leopard
You wouldn't want those buttons to show up if you pressed the dog button or the dinosaur button since they are specific to cats.
Pressing a Tiger button would display a list of new buttons along the bottom
"Bengal" "Stripes" and so on.
What I need is a way to keep all of the Cats together.
I hope this makes things a bit clearer.
~J
Paul Clapham
Sheriff
Posts: 24366
55
I like...
posted 7 years ago
So each button contains a list of lower-level buttons. The container to use would therefore be a List.
Jay Brass
Ranch Hand
Posts: 76
1
posted 7 years ago
Thanks Paul,
I had kinda gotten you hint in your first post, I'm not sure how to implement it though. Creating a list isn't the problem. What I'm having trouble with is how to get to the lower lever buttons from the top list. I have to name the buttons based on a value in the database, to keep things generic. If the top list has a bunch of names in it, how do I store or retrieve the list of buttons for the lower level?
I had thought of creating a class like a bean and storing some attributes in it.(buttonName, buttonText, buttonColor, etc) Then I could add that object to the list. One of the attributes in the class could be a list so it would have the lower level buttons available by iterating over the list contained in the class.
I'm still not sure this is the best solution though. I will be trying it, and will let you know how I make out.
Thanks
~J
Paul Clapham
Sheriff
Posts: 24366
55
I like...
posted 7 years ago
It's not that difficult. Remember I said "Each button
contains
a list of lower-level buttons?
public class JButtonWithList extends JButton { private List<JButton> lowerLevelButtons; // and so on
This makes it trivially simple to get to the lower-level buttons from the button in the higher level.
Jay Brass
Ranch Hand
Posts: 76
1
posted 7 years ago
You're awesome. I don't know why I couldn't think of it.
Thank you.
~J
Paul Clapham
Sheriff
Posts: 24366
55
I like...
posted 7 years ago
I dunno.
Java
is an object-oriented language, so the fundamental thing to do is to design classes which do the things which you want your application to do. And yet people are stuck writing monolithic chunks of code which use only classes from the standard API. There seems to be some big barrier between ordinary programming and object-oriented design, and I don't know why that is the case.
please buy this thing and then I get a fat cut of the action:
Create Edit Print & Convert PDF Using Free API with Java
Post Reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Regarding Jtable row Deletion
Radiobuttons in JTree
Someone Must Have an Example Like This!
dynamic table with sort
Doubt using JButton
More... | https://coderanch.com/t/550279/java/Container | CC-MAIN-2019-22 | refinedweb | 1,139 | 80.21 |
This action might not be possible to undo. Are you sure you want to continue?
Electromagnetic Field Theory
B O T HIDÉ
ϒ
U PSILON B OOKS
E LECTROMAGNETIC F IELD T HEORY
Electromagnetic Field Theory
B O T HIDÉ
Swedish Institute of Space Physics Uppsala, Sweden and Department of Astronomy and Space Physics Uppsala University, Sweden and LOIS Space Centre School of Mathematics and Systems Engineering Växjö University, Sweden
ϒ
U PSILON B OOKS · U PPSALA · S WEDEN
Also available
E LECTROMAGNETIC F IELD T HEORY E XERCISES
by Tobia Carozzi, Anders Eriksson, Bengt Lundborg, Bo Thidé and Mattias Waldenvik Freely downloadable from
A This book was typeset in LTEX 2ε (based on TEX 3.141592 and Web2C 7.4.4) on an HP Visualize 9000⁄3600 workstation running HP-UX 11.11.
Copyright ©1997–2008 by Bo Thidé Uppsala, Sweden All rights reserved. Electromagnetic Field Theory ISBN X-XXX-XXXXX-X
To the memory of professor
L EV M IKHAILOVICH E RUKHIMOV (1936–1997)
dear friend, great physicist, poet and a truly remarkable man.
Downloaded from
Version released 1st July 2008 at 20:49.
C ONTENTS
Contents List of Figures Preface 1 Classical Electrodynamics 1.1 Electrostatics 1.1.1 Coulomb’s law 1.1.2 The electrostatic field 1.2 Magnetostatics 1.2.1 Ampère’s law 1.2.2 The magnetostatic field 1.3 Electrodynamics 1.3.1 Equation of continuity for electric charge 1.3.2 Maxwell’s displacement current 1.3.3 Electromotive force 1.3.4 Faraday’s law of induction 1.3.5 Maxwell’s microscopic equations 1.3.6 Maxwell’s macroscopic equations 1.4 Electromagnetic duality 1.5 Bibliography 1.6 Examples Electromagnetic Waves 2.1 The wave equations 2.1.1 The wave equation for E 2.1.2 The wave equation for B 2.1.3 The time-independent wave equation for E
ix xiii xv 1 2 2 3 6 6 7 9 10 10 11 12 15 15 16 18 20 25 26 26 27 27
2
ix
Contents
2.2
2.3 2.4 2.5 3
Plane waves 2.2.1 Telegrapher’s equation 2.2.2 Waves in conductive media Observables and averages Bibliography Example
30 31 32 33 35 36 39 39 40 40 41 42 43 47 49 49 51 53 53 53 56 58 58 59 62 63 65 67 69 71 74 74 75 76 77 77 78
Electromagnetic Potentials 3.1 The electrostatic scalar potential 3.2 The magnetostatic vector potential 3.3 The electrodynamic potentials 3.4 Gauge transformations 3.5 Gauge conditions 3.5.1 Lorenz-Lorentz gauge 3.5.2 Coulomb gauge 3.5.3 Velocity gauge 3.6 Bibliography 3.7 Examples Electromagnetic Fields and Matter 4.1 Electric polarisation and displacement 4.1.1 Electric multipole moments 4.2 Magnetisation and the magnetising field 4.3 Energy and momentum 4.3.1 The energy theorem in Maxwell’s theory 4.3.2 The momentum theorem in Maxwell’s theory 4.4 Bibliography 4.5 Example Electromagnetic Fields from Arbitrary Source Distributions 5.1 The magnetic field 5.2 The electric field 5.3 The radiation fields 5.4 Radiated energy 5.4.1 Monochromatic signals 5.4.2 Finite bandwidth signals 5.5 Bibliography Electromagnetic Radiation and Radiating Systems 6.1 Radiation from an extended source volume at rest 6.1.1 Radiation from a one-dimensional current distribution
4
5
6
x
Version released 1st July 2008 at 20:49.
Downloaded from
6.2
6.3
6.4 6.5 7
6.1.2 Radiation from a two-dimensional current distribution Radiation from a localised source volume at rest 6.2.1 The Hertz potential 6.2.2 Electric dipole radiation 6.2.3 Magnetic dipole radiation 6.2.4 Electric quadrupole radiation Radiation from a localised charge in arbitrary motion 6.3.1 The Liénard-Wiechert potentials 6.3.2 Radiation from an accelerated point charge 6.3.3 Bremsstrahlung 6.3.4 Cyclotron and synchrotron radiation 6.3.5 Radiation from charges moving in matter Bibliography Examples
81 85 85 90 91 93 93 94 97 105 108 116 123 124 133 133 134 136 141 143 145 145 146 148 152 155 155 155 161 162 169 171 173 173 173 174 174 174
Relativistic Electrodynamics 7.1 The special theory of relativity 7.1.1 The Lorentz transformation 7.1.2 Lorentz space 7.1.3 Minkowski space 7.2 Covariant classical mechanics 7.3 Covariant classical electrodynamics 7.3.1 The four-potential 7.3.2 The Liénard-Wiechert potentials 7.3.3 The electromagnetic field tensor 7.4 Bibliography Electromagnetic Fields and Particles 8.1 Charged particles in an electromagnetic field 8.1.1 Covariant equations of motion 8.2 Covariant field theory 8.2.1 Lagrange-Hamilton formalism for fields and interactions 8.3 Bibliography 8.4 Example Formulæ F.1 The electromagnetic field F.1.1 Maxwell’s equations F.1.2 Fields and potentials F.1.3 Force and energy F.2 Electromagnetic radiation
8
F
Downloaded from
Version released 1st July 2008 at 20:49.
xi
Contents
F.3
F.4
F.5
F.2.1 Relationship between the field vectors in a plane wave F.2.2 The far fields from an extended source distribution F.2.3 The far fields from an electric dipole F.2.4 The far fields from a magnetic dipole F.2.5 The far fields from an electric quadrupole F.2.6 The fields from a point charge in arbitrary motion Special relativity F.3.1 Metric tensor F.3.2 Covariant and contravariant four-vectors F.3.3 Lorentz transformation of a four-vector F.3.4 Invariant line element F.3.5 Four-velocity F.3.6 Four-momentum F.3.7 Four-current density F.3.8 Four-potential F.3.9 Field tensor Vector relations F.4.1 Spherical polar coordinates F.4.2 Vector formulae Bibliography
174 174 175 175 175 175 176 176 176 176 176 176 177 177 177 177 177 178 178 180 181 181 182 183 187 189 191 191 192 194 202 203
M Mathematical Methods M.1 Scalars, vectors and tensors M.1.1 Vectors M.1.2 Fields M.1.3 Vector algebra M.1.4 Vector analysis M.2 Analytical mechanics M.2.1 Lagrange’s equations M.2.2 Hamilton’s equations M.3 Examples M.4 Bibliography Index
xii
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
L IST OF F IGURES
1.1 1.2 1.3 1.4 5.1 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 7.1 7.2 7.3 8.1
Coulomb interaction between two electric charges Coulomb interaction for a distribution of electric charges Ampère interaction Moving loop in a varying B field Radiation in the far zone Linear antenna Electric dipole antenna geometry Loop antenna Multipole radiation geometry Electric dipole geometry Radiation from a moving charge in vacuum An accelerated charge in vacuum Angular distribution of radiation during bremsstrahlung Location of radiation during bremsstrahlung Radiation from a charge in circular motion Synchrotron radiation lobe width The perpendicular electric field of a moving charge Electron-electron scattering ˇ Vavilov-Cerenkov cone Relative motion of two inertial systems Rotation in a 2D Euclidean space Minkowski diagram Linear one-dimensional mass chain
3 5 7 13 73 79 80 82 87 89 94 96 105 107 109 111 114 116 120 135 141 142 162 194
M.1 Tetrahedron-like volume element of matter
xiii
Downloaded from
Version released 1st July 2008 at 20:49.
P REFACE
This book is the result of a more than thirty-five year long love affair. In the autumn of 1972, I took my first advanced course in electrodynamics at the Department of Theoretical Physics, Uppsala University. A year later, I joined the research group there and took on the task of helping the late professor P ER O LOF F RÖMAN, who one year later become my Ph.D. thesis advisor, with the preparation of a new version of his lecture notes on the Theory of Electricity. These two things opened up my eyes for the beauty and intricacy of electrodynamics, already at the classical level, and I fell in love with it. Ever since that time, I have on and off had reason to return to electrodynamics, both in my studies, research and the teaching of a course in advanced electrodynamics at Uppsala University some twenty odd years after I experienced the first encounter with this subject. The current version of the book is an outgrowth of the lecture notes that I prepared for the four-credit course Electrodynamics that was introduced in the Uppsala University curriculum in 1992, to become the five-credit course Classical Electrodynamics in 1997. To some extent, parts of these notes were based on lecture notes prepared, in Swedish, by my friend and colleague B ENGT L UNDBORG, who created, developed and taught the earlier, two-credit course Electromagnetic Radiation at our faculty. Intended primarily as a textbook for physics students at the advanced undergraduate or beginning graduate level, it is hoped that the present book may be useful for research workers too. It provides a thorough treatment of the theory of electrodynamics, mainly from a classical field theoretical point of view, and includes such things as formal electrostatics and magnetostatics and their unification into electrodynamics, the electromagnetic potentials, gauge transformations, covariant formulation of classical electrodynamics, force, momentum and energy of the electromagnetic field, radiation and scattering phenomena, electromagnetic waves and their propagation in vacuum and in media, and covariant Lagrangian/Hamiltonian field theoretical methods for electromagnetic fields, particles and interactions. The aim has been to write useful
xv
Preface
in higher university education anywhere in the world, it was produced within a World-Wide Web (WWW) project. This turned out to be a rather successful move. By making an electronic version of the book freely down-loadable on the net, comments have been received from fellow Internet physicists around the world and from WWW ‘hit’ statistics it seems that the book serves as a frequently used Internet resource.1 This way it is hoped that it will be particularly useful for students and researchers working under financial or other circumstances that make it difficult to procure a printed copy of the book. Thanks are due not only to Bengt Lundborg for providing the inspiration to write this book, but also to professor C HRISTER WAHLBERG and professor G ÖRAN FÄLDT, Uppsala University, and professor YAKOV I STOMIN, Lebedev Institute, Moscow, for interesting discussions on electrodynamics and relativity in general and on this book in particular. Comments from former graduate students M ATTIAS WALDENVIK, TOBIA C AROZZI and ROGER K ARLSSON as well as A NDERS E RIKS SON , all at the Swedish Institute of Space Physics in Uppsala and who all have participated in the teaching on the material covered in the course and in this book are gratefully acknowledged. Thanks are also due to my long-term space physics colleague H ELMUT KOPKA of the Max-Planck-Institut für Aeronomie, Lindau, Germany, who not only taught me about the practical aspects of high-power radio wave transmitters and transmission lines, but also about the more delicate aspects A of typesetting a book in TEX and LTEX. I am particularly indebted to Academician professor V ITALIY L AZAREVICH G INZBURG, 2003 Nobel Laureate in Physics, for his many fascinating and very elucidating lectures, comments and historical notes on electromagnetic radiation and cosmic electrodynamics while cruising on the Volga river at our joint Russian-Swedish summer schools during the 1990s, and for numerous private discussions over the years. Finally, I would like to thank all students and Internet users who have downloaded and commented on the book during its life on the World-Wide Web. I dedicate this book to my son M ATTIAS, my daughter K AROLINA, my high-school physics teacher, S TAFFAN RÖSBY, and to my fellow members of the C APELLA P EDAGOGICA U PSALIENSIS. Uppsala, Sweden June, 2008
B O T HIDÉ∼bt
1 At
the time of publication of this edition, more than 600 000 downloads have been recorded.
xvi
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
1
C LASSICAL E LECTRODYNAMICS
Classical electrodynamics deals with electric and magnetic fields and interactions caused by macroscopic distributions of electric charges and currents. This means that the concepts of localised electric charges and currents assume the validity of certain mathematical limiting processes in which it is considered possible for the charge and current distributions to be localised in infinitesimally small volumes of space. Clearly, this is in contradiction to electromagnetism on a truly microscopic scale, where charges and currents have to be treated as spatially extended objects and quantum corrections must be included. However, the limiting processes used will yield results which are correct on small as well as large macroscopic scales. It took the genius of JAMES C LERK M AXWELL to consistently unify electricity and magnetism into a super-theory, electromagnetism or classical electrodynamics (CED), and to realise that optics is a subfield of this super-theory. Early in the 20th century, H ENDRIK A NTOON L ORENTZ took the electrodynamics theory further to the microscopic scale and also laid the foundation for the special theory of relativity, formulated by A LBERT E INSTEIN in 1905. In the 1930s PAUL A. M. D IRAC expanded electrodynamics to a more symmetric form, including magnetic as well as electric charges. With his relativistic quantum mechanics, he also paved the way for the development of quantum electrodynamics (QED) for which R ICHARD P. F EYNMAN, J ULIAN S CHWINGER, and S IN -I TIRO TOMON AGA in 1965 received their Nobel prizes in physics. Around the same time, physicists such as S HELDON G LASHOW, A BDUS S ALAM, and S TEVEN W EINBERG were able to unify electrodynamics the weak interaction theory to yet another supertheory, electroweak theory, an achievement which rendered them the Nobel prize in physics 1979. The modern theory of strong interactions, quantum chromodynamics (QCD), is influenced by QED. In this chapter we start with the force interactions in classical electrostatics
1
1. Classical Electrodynamics
and classical magnetostatics and introduce the static electric and magnetic fields to find two uncoupled systems of equations for them. Then we see how the conservation of electric charge and its relation to electric current leads to the dynamic connection between electricity and magnetism and how the two can be unified into one ‘super-theory’, classical electrodynamics, described by one system of eight coupled dynamic field equations—the Maxwell equations. At the end of this chapter we study Dirac’s symmetrised form of Maxwell’s equations by introducing (hypothetical) magnetic charges and magnetic currents into the theory. While not identified unambiguously in experiments yet, magnetic charges and currents make the theory much more appealing, for instance by allowing for duality transformations in a most natural way.
1.1 Electrostatics
The theory which describes physical phenomena related to the interaction between stationary electric charges or charge distributions in a finite space which has stationary boundaries is called electrostatics. For a long time, electrostatics, under the name electricity, was considered an independent physical theory of its own, alongside other physical theories such as magnetism, mechanics, optics and thermodynamics.1
1.1.1 Coulomb’s law
It has been found experimentally that in classical electrostatics the interaction between stationary, electrically charged bodies can be described in terms of a mechanical force. Let us consider the simple case described by figure 1.1 on page 3. Let F denote the force acting on an electrically charged particle with charge q located at x, due to the presence of a charge q′ located at x′ . According to Coulomb’s law this force is, in vacuum, given by the expression F(x) =
1 The
qq′ 1 qq′ x − x′ =− ∇ ′ |3 4πε0 |x − x 4πε0 |x − x′ |
=
qq′ ′ 1 ∇ 4πε0 |x − x′ |
(1.1)
physicist and philosopher P IERRE D UHEM (1861–1916) once wrote:
‘The whole theory of electrostatics constitutes a group of abstract ideas and general propositions, formulated in the clear and concise language of geometry and algebra, and connected with one another by the rules of strict logic. This whole fully satisfies the reason of a French physicist and his taste for clarity, simplicity and order. . . .’
2
Version released 1st July 2008 at 20:49.
Downloaded from
Electrostatics
q x
x − x′
q′ x′
O
F IGURE 1 .1 : Coulomb’s law describes how a static electric charge q, located at a point x relative to the origin O, experiences an electrostatic force from a static electric charge q′ located at x′ .
where in the last step formula (F.71) on page 179 was used. In SI units, which we shall use throughout, the force F is measured in Newton (N), the electric charges q and q′ in Coulomb (C) [= Ampère-seconds (As)], and the length |x − x′ | in metres (m). The constant ε0 = 107 /(4πc2 ) ≈ 8.8542 × 10−12 Farad per metre (F/m) is the vacuum permittivity and c ≈ 2.9979 × 108 m/s is the speed of light in vacuum. In CGS units ε0 = 1/(4π) and the force is measured in dyne, electric charge in statcoulomb, and length in centimetres (cm).
1.1.2 The electrostatic field
Instead of describing the electrostatic interaction in terms of a ‘force action at a distance’, it turns out that it is for most purposes more useful to introduce the concept of a field and to describe the electrostatic interaction in terms of a static vectorial electric field Estat defined by the limiting process Estat ≡ lim
def
F q→0 q
(1.2)
where F is the electrostatic force, as defined in equation (1.1) on page 2, from a net electric charge q′ on the test particle with a small electric net electric charge q. Since the purpose of the limiting process is to assure that the test charge q does not distort the field set up by q′ , the expression for Estat does not depend explicitly on q but only on the charge q′ and the relative radius vector x − x′ . This means that we can say that any net electric charge produces an electric field in the space
Downloaded from
Version released 1st July 2008 at 20:49.
3
1. Classical Electrodynamics
that surrounds it, regardless of the existence of a second charge anywhere in this space.2 Using (1.1) and equation (1.2) on page 3, and formula (F.70) on page 179, we find that the electrostatic field Estat at the field point x (also known as the observation point), due to a field-producing electric charge q′ at the source point x′ , is given by Estat (x) = 1 q′ q′ x − x′ 3 = − 4πε ∇ |x − x′ | 4πε0 |x − x′ | 0 = q′ ′ 1 ∇ 4πε0 |x − x′ |
(1.3)
In the presence of several field producing discrete electric charges q′ , located i at the points x′ , i = 1, 2, 3, . . . , respectively, in an otherwise empty space, the asi sumption of linearity of vacuum3 allows us to superimpose their individual electrostatic fields into a total electrostatic field Estat (x) = 1 4πε0
∑ q′i
i
x − x′ i
x − x′ i
3
(1.4)
If the discrete electric charges are small and numerous enough, we introduce the electric charge density ρ, measured in C/m3 in SI units, located at x′ within a volume V ′ of limited extent and replace summation with integration over this volume. This allows us to describe the total field as Estat (x) = 1 1 x − x′ =− d3x′ ρ(x′ ) 4πε0 V ′ 4πε0 |x − x′ |3 ρ(x′ ) 1 ∇ d3x′ =− 4πε0 |x − x′ | V′ d3x′ ρ(x′ )∇ 1 |x − x′ | (1.5)
V′
where we used formula (F.70) on page 179 and the fact that ρ(x′ ) does not depend on the unprimed (field point) coordinates on which ∇ operates.
2 In the preface to the first edition of the first volume of his book A Treatise on Electricity and Magnetism, first published in 1873, James Clerk Maxwell describes this in the following almost poetic manner [9]:
‘For satisfied that they had found it in a power of action at a distance impressed on the electric fluids.’
3 In fact, vacuum exhibits a quantum mechanical nonlinearity due to vacuum polarisation effects manifesting themselves in the momentary creation and annihilation of electron-positron pairs, but classically this nonlinearity is negligible.
4
Version released 1st July 2008 at 20:49.
Downloaded from
Electrostatics
q x
x − x′ i
q′ i x′ i V′ O
F IGURE 1 .2 :
Coulomb’s law for a distribution of individual charges q′ localised i within a volume V ′ of limited extent.
We emphasise that under the assumption of linear superposition, equation (1.5) on page 4 is valid for an arbitrary distribution of electric charges, including discrete charges, in which case ρ is expressed in terms of Dirac delta distributions: ρ(x′ ) = ∑ q′ δ(x′ − x′ ) i i
i
(1.6)
as illustrated in figure 1.2. Inserting this expression into expression (1.5) on page 4 we recover expression (1.4) on page 4. Taking the divergence of the general Estat expression for an arbitrary electric charge distribution, equation (1.5) on page 4, and using the representation of the Dirac delta distribution, formula (F.73) on page 179, we find that ∇ · Estat (x) = ∇ · x − x′ 1 d3x′ ρ(x′ ) 4πε0 V ′ |x − x′ |3 1 1 =− d3x′ ρ(x′ )∇ · ∇ 4πε0 V ′ |x − x′ | 1 1 =− d3x′ ρ(x′ ) ∇2 ′ 4πε0 V |x − x′ | ρ(x) 1 d3x′ ρ(x′ ) δ(x − x′ ) = = ′ ε0 V ε0
(1.7)
which is the differential form of Gauss’s law of electrostatics. Since, according to formula (F.62) on page 179, ∇ × [∇α(x)] ≡ 0 for any 3D
Downloaded from
Version released 1st July 2008 at 20:49.
5
1. Classical Electrodynamics
R3 scalar field α(x), we immediately find that in electrostatics
∇ × Estat (x) = − 1 ∇× ∇ 4πε0
V′
d3x′
ρ(x′ ) |x − x′ |
=0
(1.8)
i.e., that Estat is an irrotational field. To summarise, electrostatics can be described in terms of two vector partial differential equations ρ(x) ε0 stat ∇ × E (x) = 0 ∇ · Estat (x) = representing four scalar partial differential equations. (1.9a) (1.9b)
1.2 Magnetostatics
While electrostatics deals with static electric charges, magnetostatics deals with stationary electric currents, i.e., electric charges moving with constant speeds, and the interaction between these currents. Here we shall discuss this theory in some detail.
1.2.1 Ampère’s law
Experiments on the interaction between two small loops of electric current have shown that they interact via a mechanical force, much the same way that electric charges interact. In figure 1.3 on page 7, let F denote such a force acting on a small loop C, with tangential line element dl, located at x and carrying a current I in the direction of dl, due to the presence of a small loop C ′ , with tangential line element dl′ , located at x′ and carrying a current I ′ in the direction of dl′ . According to Ampère’s law this force is, in vacuum, given by the expression F(x) = µ0 II ′ x − x′ dl × dl′ × 4π C |x − x′ |3 C′ 1 µ0 II ′ dl × dl′ × ∇ =− 4π C |x − x′ | C′
(1.10)
In SI units, µ0 = 4π × 10−7 ≈ 1.2566 × 10−6 H/m is the vacuum permeability. From the definition of ε0 and µ0 (in SI units) we observe that ε0 µ0 = 1 107 (F/m) × 4π × 10−7 (H/m) = 2 (s2 /m2 ) 2 4πc c (1.11)
6
Version released 1st July 2008 at 20:49.
Downloaded from
Magnetostatics
C I dl x C′ x′ x − x′ I ′ dl′
O
F IGURE 1 .3 : Ampère’s law describes how a small loop C, carrying a static electric current I through its tangential line element dl located at x, experiences a magnetostatic force from a small loop C ′ , carrying a static electric current I ′ through the tangential line element dl′ located at x′ . The loops can have arbitrary shapes as long as they are simple and closed.
which is a most useful relation. At first glance, equation (1.10) on page 6 may appear unsymmetric in terms of the loops and therefore to be a force law which is in contradiction with Newton’s third law. However, by applying the vector triple product ‘bac-cab’ formula (F.51) on page 178, we can rewrite (1.10) as F(x) = − µ0 II ′ 4π µ0 II ′ − 4π
C′
dl′
C
dl · ∇
C
C′
x − x′ dl ·dl′ |x − x′ |3
1 |x − x′ |
(1.12)
Since the integrand in the first integral is an exact differential, this integral vanishes and we can rewrite the force expression, equation (1.10) on page 6, in the following symmetric way F(x) = − µ0 II ′ 4π
C C′
which clearly exhibits the expected symmetry in terms of loops C and C ′ .
x − x′ dl · dl′ |x − x′ |3
(1.13)
1.2.2 The magnetostatic field
In analogy with the electrostatic case, we may attribute the magnetostatic interaction to a static vectorial magnetic field Bstat . It turns out that the elemental Bstat
Downloaded from
Version released 1st July 2008 at 20:49.
7
1. Classical Electrodynamics
can be defined as dBstat (x) ≡
def
which expresses the small element dBstat (x) of the static magnetic field set up at the field point x by a small line element dl′ of stationary current I ′ at the source point x′ . The SI unit for the magnetic field, sometimes called the magnetic flux density or magnetic induction, is Tesla (T). If we generalise expression (1.14) to an integrated steady state electric current density j(x), measured in A/m2 in SI units, we obtain Biot-Savart’s law: Bstat (x) = x − x′ µ0 µ0 d3x′ j(x′ ) × =− ′ |3 4π V ′ 4π |x − x ′ µ0 j(x ) = ∇ × d3x′ 4π |x − x′ | V′ d3x′ j(x′ ) × ∇ 1 |x − x′ | (1.15)
µ0 I ′ ′ x − x′ dl × 4π |x − x′ |3
(1.14)
V′
where we used formula (F.70) on page 179, formula (F.57) on page 179, and the fact that j(x′ ) does not depend on the unprimed coordinates on which ∇ operates. Comparing equation (1.5) on page 4 with equation (1.15), we see that there exists a close analogy between the expressions for Estat and Bstat but that they differ in their vectorial characteristics. With this definition of Bstat , equation (1.10) on page 6 may we written F(x) = I
C
dl × Bstat (x)
(1.16)
In order to assess the properties of Bstat , we determine its divergence and curl. Taking the divergence of both sides of equation (1.15) and utilising formula (F.63) on page 179, we obtain ∇ · Bstat (x) = µ0 ∇· ∇× 4π d3x′ j(x′ ) |x − x′ | =0 (1.17)
V′
since, according to formula (F.63) on page 179, ∇ · (∇ × a) vanishes for any vector field a(x). Applying the operator ‘bac-cab’ rule, formula (F.64) on page 179, the curl of equation (1.15) can be written ∇ × Bstat (x) = =− µ0 4π µ0 ∇× ∇× 4π j(x′ ) = |x − x′ | V′ µ0 1 1 + d3x′ [j(x′ ) · ∇′ ] ∇′ 4π V ′ |x − x′ | |x − x′ | (1.18) d3x′
V′
d3x′ j(x′ ) ∇2
8
Version released 1st July 2008 at 20:49.
Downloaded from
Electrodynamics
In the first of the two integrals on the right-hand side, we use the representation of the Dirac delta function given in formula (F.73) on page 179, and integrate the second one by parts, by utilising formula (F.56) on page 179 as follows: 1 |x − x′ | 1 ∂ = xk d3x′ ∇′ · j(x′ ) ˆ ′ ∂xk |x − x′ | V′ 1 − d3x′ ∇′ · j(x′ ) ∇′ |x − x′ | V′ 1 ∂ − = xk d2x′ n′ · j(x′ ) ′ ˆ ˆ ′ ∂xk |x − x′ | S
V′
d3x′ [j(x′ ) · ∇′ ]∇′
V′
d3x′ ∇′ · j(x′ ) ∇′
1 |x − x′ | (1.19)
Then we note that the first integral in the result, obtained by applying Gauss’s theorem, vanishes when integrated over a large sphere far away from the localised source j(x′ ), and that the second integral vanishes because ∇ · j = 0 for stationary currents (no charge accumulation in space). The net result is simply ∇ × Bstat (x) = µ0 d3x′ j(x′ )δ(x − x′ ) = µ0 j(x) (1.20)
V′
1.3 Electrodynamics
As we saw in the previous sections, the laws of electrostatics and magnetostatics can be summarised in two pairs of time-independent, uncoupled vector partial differential equations, namely the equations of classical electrostatics ρ(x) ε0 stat ∇ × E (x) = 0 ∇ · Estat (x) = and the equations of classical magnetostatics ∇ · Bstat (x) = 0
stat
(1.21a) (1.21b)
(1.22a) (1.22b)
∇×B
(x) = µ0 j(x)
Since there is nothing a priori which connects Estat directly with Bstat , we must consider classical electrostatics and classical magnetostatics as two independent theories.
Downloaded from
Version released 1st July 2008 at 20:49.
9
1. Classical Electrodynamics
However, when we include time-dependence, these theories are unified into one theory, classical electrodynamics. This unification of the theories of electricity and magnetism is motivated by two empirically established facts: 1. Electric charge is a conserved quantity and electric current is a transport of electric charge. This fact manifests itself in the equation of continuity and, as a consequence, in Maxwell’s displacement current. 2. A change in the magnetic flux through a loop will induce an EMF electric field in the loop. This is the celebrated Faraday’s law of induction.
1.3.1 Equation of continuity for electric charge
Let j(t, x) denote the time-dependent electric current density. In the simplest case it can be defined as j = vρ where v is the velocity of the electric charge density ρ. In general, j has to be defined in statistical mechanical terms as j(t, x) = ∑α qα d3v v fα (t, x, v) where fα (t, x, v) is the (normalised) distribution function for particle species α with electric charge qα . The electric charge conservation law can be formulated in the equation of continuity ∂ρ(t, x) + ∇ · j(t, x) = 0 ∂t (1.23)
which states that the time rate of change of electric charge ρ(t, x) is balanced by a divergence in the electric current density j(t, x).
1.3.2 Maxwell’s displacement current
We recall from the derivation of equation (1.20) on page 9 that there we used the fact that in magnetostatics ∇ · j(x) = 0. In the case of non-stationary sources and fields, we must, in accordance with the continuity equation (1.23), set ∇ · j(t, x) = −∂ρ(t, x)/∂t. Doing so, and formally repeating the steps in the derivation of equation (1.20) on page 9, we would obtain the formal result ∇ × B(t, x) = µ0 d3x′ j(t, x′ )δ(x − x′ ) + µ0 ∂ 4π ∂t d3x′ ρ(t, x′ )∇′ 1 |x − x′ | (1.24)
V′
V′
∂ = µ0 j(t, x) + µ0 ε0 E(t, x) ∂t
10
Version released 1st July 2008 at 20:49.
Downloaded from
Electrodynamics
where, in the last step, we have assumed that a generalisation of equation (1.5) on page 4 to time-varying fields allows us to make the identification4 1 ∂ 1 d3x′ ρ(t, x′ )∇′ 4πε0 ∂t V ′ |x − x′ | 1 ∂ 1 − = d3x′ ρ(t, x′ )∇ ∂t 4πε0 V ′ |x − x′ | 1 ρ(t, x′ ) ∂ ∂ − ∇ d3x′ = E(t, x) = ′| ′ ∂t 4πε0 ∂t |x − x V The result is Maxwell’s source equation for the B field ∇ × B(t, x) = µ0 j(t, x) + ∂ ε0 E(t, x) ∂t = µ0 j(t, x) + 1 ∂ E(t, x) c2 ∂t (1.26)
(1.25)
where the last term ∂ε0 E(t, x)/∂t is the famous displacement current. This term was introduced, in a stroke of genius, by Maxwell [8] in order to make the right hand side of this equation divergence free when j(t, x) is assumed to represent the density of the total electric current, which can be split up in ‘ordinary’ conduction currents, polarisation currents and magnetisation currents. The displacement current is an extra term which behaves like a current density flowing in vacuum. As we shall see later, its existence has far-reaching physical consequences as it predicts the existence of electromagnetic radiation that can carry energy and momentum over very long distances, even in vacuum.
1.3.3 Electromotive force
If an electric field E(t, x) is applied to a conducting medium, a current density j(t, x) will be produced in this medium. There exist also hydrodynamical and chemical processes which can create currents. Under certain physical conditions, and for certain materials, one can sometimes assume, that, as a first approximation, a linear relationship exists between the electric current density j and E. This approximation is called Ohm’s law: j(t, x) = σE(t, x) (1.27)
where σ is the electric conductivity (S/m). In the most general cases, for instance in an anisotropic conductor, σ is a tensor. We can view Ohm’s law, equation (1.27) above, as the first term in a Taylor expansion of the law j[E(t, x)]. This general law incorporates non-linear effects
4 Later,
we will need to consider this generalisation and formal identification further.
Downloaded from
Version released 1st July 2008 at 20:49.
11
1. Classical Electrodynamics
such as frequency mixing. Examples of media which are highly non-linear are semiconductors and plasma. We draw the attention to the fact that even in cases when the linear relation between E and j is a good approximation, we still have to use Ohm’s law with care. The conductivity σ is, in general, time-dependent (temporal dispersive media) but then it is often the case that equation (1.27) on page 11 is valid for each individual Fourier component of the field. If the current is caused by an applied electric field E(t, x), this electric field will exert work on the charges in the medium and, unless the medium is superconducting, there will be some energy loss. The rate at which this energy is expended is j · E per unit volume. If E is irrotational (conservative), j will decay away with time. Stationary currents therefore require that an electric field which corresponds to an electromotive force (EMF) is present. In the presence of such a field EEMF , Ohm’s law, equation (1.27) on page 11, takes the form j = σ(Estat + EEMF ) The electromotive force is defined as E=
C
(1.28)
dl · (Estat + EEMF )
(1.29)
where dl is a tangential line element of the closed loop C.
1.3.4 Faraday’s law of induction
In subsection 1.1.2 we derived the differential equations for the electrostatic field. In particular, on page 6 we derived equation (1.8) which states that ∇ × Estat (x) = 0 and thus that Estat is a conservative field (it can be expressed as a gradient of a scalar field). This implies that the closed line integral of Estat in equation (1.29) above vanishes and that this equation becomes E=
C
dl · EEMF
(1.30)
It has been established experimentally that a nonconservative EMF field is produced in a closed circuit C at rest if the magnetic flux through this circuit varies with time. This is formulated in Faraday’s law which, in Maxwell’s generalised form, reads d Φm (t) dt
S
E(t) =
C
dl · E(t, x) = −
S
=−
d dt
d2x n · B(t, x) = − ˆ
d2x n · ˆ
∂ B(t, x) ∂t
(1.31)
12
Version released 1st July 2008 at 20:49.
Downloaded from
Electrodynamics
B(x) d2x n ˆ
B(x)
v
C dl
F IGURE 1 .4 :
A loop C which moves with velocity v in a spatially varying magnetic field B(x) will sense a varying magnetic flux during the motion.
where Φm is the magnetic flux and S is the surface encircled by C which can be interpreted as a generic stationary ‘loop’ and not necessarily as a conducting circuit. Application of Stokes’ theorem on this integral equation, transforms it into the differential equation ∇ × E(t, x) = − ∂ B(t, x) ∂t (1.32)
which is valid for arbitrary variations in the fields and constitutes the Maxwell equation which explicitly connects electricity with magnetism. Any change of the magnetic flux Φm will induce an EMF. Let us therefore consider the case, illustrated if figure 1.4, that the ‘loop’ is moved in such a way that it links a magnetic field which varies during the movement. The convective derivative is evaluated according to the well-known operator formula d ∂ = +v·∇ dt ∂t
(1.33)
which follows immediately from the rules of differentiation of an arbitrary differentiable function f (t, x(t)). Applying this rule to Faraday’s law, equation (1.31) on page 12, we obtain E(t) = − d dt d2x n · B = − ˆ d2x n · ˆ ∂B − ∂t d2x n · (v · ∇)B ˆ (1.34)
S
S
S
Downloaded from
Version released 1st July 2008 at 20:49.
13
1. Classical Electrodynamics
During spatial differentiation v is to be considered as constant, and equation (1.17) on page 8 holds also for time-varying fields: ∇ · B(t, x) = 0 ∇ × (B × v) = (v · ∇)B allowing us to rewrite equation (1.34) on page 13 in the following way: E(t) = dl · EEMF = −
2
(1.35)
(it is one of Maxwell’s equations) so that, according to formula (F.59) on page 179, (1.36)
C
d dt
S
S
d2x n · B ˆ
2
∂B − = − d xn· ˆ ∂t S
(1.37)
d x n · ∇ × (B × v) ˆ
With Stokes’ theorem applied to the last integral, we finally get E(t) = dl · EEMF = − d2x n · ˆ ∂B − ∂t dl · (B × v) (1.38)
C
S
C
or, rearranging the terms, dl · (EEMF − v × B) = − d2x n · ˆ ∂B ∂t (1.39)
C
S
where EEMF is the field which is induced in the ‘loop’, i.e., in the moving system. The use of Stokes’ theorem ‘backwards’ on equation (1.39) above yields ∇ × (EEMF − v × B) = − E = EEMF − v × B qEEMF = qE + q(v × B) ∂B ∂t (1.40)
In the fixed system, an observer measures the electric field (1.41)
Hence, a moving observer measures the following Lorentz force on a charge q (1.42)
corresponding to an ‘effective’ electric field in the ‘loop’ (moving observer) EEMF = E + v × B (1.43)
Hence, we can conclude that for a stationary observer, the Maxwell equation ∇×E=− ∂B ∂t (1.44)
is indeed valid even if the ‘loop’ is moving.
14
Version released 1st July 2008 at 20:49.
Downloaded from
Electrodynamics
1.3.5 Maxwell’s microscopic equations
We are now able to collect the results from the above considerations and formulate the equations of classical electrodynamics valid for arbitrary variations in time and space of the coupled electric and magnetic fields E(t, x) and B(t, x). The equations are ρ (1.45a) ∇·E= ε0 ∂B (1.45b) ∇×E=− ∂t ∇·B=0 (1.45c) ∂E ∇ × B = ε0 µ0 + µ0 j(t, x) (1.45d) ∂t In these equations ρ(t, x) represents the total, possibly both time and space dependent, electric charge, i.e., free as well as induced (polarisation) charges, and j(t, x) represents the total, possibly both time and space dependent, electric current, i.e., conduction currents (motion of free charges) as well as all atomistic (polarisation, magnetisation) currents. As they stand, the equations therefore incorporate the classical interaction between all electric charges and currents in the system and are called Maxwell’s microscopic equations. Another name often used for them is the Maxwell-Lorentz equations. Together with the appropriate constitutive relations, which relate ρ and j to the fields, and the initial and boundary conditions pertinent to the physical situation at hand, they form a system of well-posed partial differential equations which completely determine E and B.
1.3.6 Maxwell’s macroscopic equations
The microscopic field equations (1.45) provide a correct classical picture for arbitrary field and source distributions, including both microscopic and macroscopic scales. However, for macroscopic substances it is sometimes convenient to introduce new derived fields which represent the electric and magnetic fields in which, in an average sense, the material properties of the substances are already included. These fields are the electric displacement D and the magnetising field H. In the most general case, these derived fields are complicated nonlocal, nonlinear functionals of the primary fields E and B: D = D[t, x; E, B] H = H[t, x; E, B] (1.46a) (1.46b)
Under certain conditions, for instance for very low field strengths, we may assume that the response of a substance to the fields may be approximated as a linear one
Downloaded from
Version released 1st July 2008 at 20:49.
15
1. Classical Electrodynamics
so that D = εE H=µ B
−1
(1.47) (1.48)
i.e., that the derived fields are linearly proportional to the primary fields and that the electric displacement (magnetising field) is only dependent on the electric (magnetic) field. The field equations expressed in terms of the derived field quantities D and H are ∇ · D = ρ(t, x) ∂B ∇×E=− ∂t ∇·B=0 ∂D ∇×H= + j(t, x) ∂t (1.49a) (1.49b) (1.49c) (1.49d)
and are called Maxwell’s macroscopic equations. We will study them in more detail in chapter 4.
1.4 Electromagnetic duality
If we look more closely at the microscopic Maxwell equations (1.45), we see that they exhibit a certain, albeit not complete, symmetry. Let us follow Dirac and make the ad hoc assumption that there exist magnetic monopoles represented by a magnetic charge density, which we denote by ρm = ρm (t, x), and a magnetic current density, which we denote by jm = jm (t, x). With these new quantities included in the theory, and with the electric charge density denoted ρe and the electric current density denoted je , the Maxwell equations will be symmetrised into the following two scalar and two vector, coupled, partial differential equations: ∇·E= ρe ε0 (1.50a) (1.50b) (1.50c) (1.50d)
∂B − µ0 jm ∂t ∇ · B = µ0 ρm ∂E ∇ × B = ε0 µ0 + µ0 je ∂t ∇×E=−
16
Version released 1st July 2008 at 20:49.
Downloaded from
Electromagnetic duality
We shall call these equations Dirac’s symmetrised Maxwell equations or the electromagnetodynamic equations. Taking the divergence of (1.50b), we find that ∇ · (∇ × E) = − ∂ (∇ · B) − µ0 ∇ · jm ≡ 0 ∂t (1.51)
where we used the fact that, according to formula (F.63) on page 179, the divergence of a curl always vanishes. Using (1.50c) to rewrite this relation, we obtain the magnetic monopole equation of continuity ∂ρm + ∇ · jm = 0 ∂t (1.52)
which has the same form as that for the electric monopoles (electric charges) and currents, equation (1.23) on page 10. We notice that the new equations (1.50) on page 16 exhibit the following symmetry (recall that ε0 µ0 = 1/c2 ): E → cB
e m
(1.53a) (1.53b) (1.53c)
e
cρ → ρ
m e
cB → −E ρ → −cρ
m
(1.53d) (1.53e) (1.53f)
cj → j
m
j → −cj
e
which is a particular case (θ = π/2) of the general duality transformation, also known as the Heaviside-Larmor-Rainich transformation (indicted by the Hodge star operator ⋆)
⋆ ⋆
E = E cos θ + cB sin θ
e m
(1.54a) (1.54b) (1.54c) (1.54d) (1.54e) (1.54f)
c ρ = cρ cos θ + ρ sin θ
⋆ m ⋆ e e m
c B = −E sin θ + cB cos θ
⋆ e
c j = cj cos θ + j sin θ
⋆ m e m
ρ = −cρ sin θ + ρ cos θ
e m
j = −cj sin θ + j cos θ
which leaves the symmetrised Maxwell equations, and hence the physics they describe (often referred to as electromagnetodynamics), invariant. Since E and je are (true or polar) vectors, B a pseudovector (axial vector), ρe a (true) scalar, then ρm and θ, which behaves as a mixing angle in a two-dimensional ‘charge space’, must be pseudoscalars and jm a pseudovector.
Downloaded from
Version released 1st July 2008 at 20:49.
17
1. Classical Electrodynamics
The invariance of Dirac’s symmetrised Maxwell equations under the similarity transformation means that the amount of magnetic monopole density ρm is irrelevant for the physics as long as the ratio ρm /ρe = tan θ is kept constant. So whether we assume that the particles are only electrically charged or have also a magnetic charge with a given, fixed ratio between the two types of charges is a matter of convention, as long as we assume that this fraction is the same for all particles. Such particles are referred to as dyons [14]. By varying the mixing angle θ we can change the fraction of magnetic monopoles at will without changing the laws of electrodynamics. For θ = 0 we recover the usual Maxwell electrodynamics as we know it.5
1.5 Bibliography
[1]
T. W. B ARRETT AND D. M. G RIMES, Advanced Electromagnetism. Foundations, Theory and Applications, World Scientific Publishing Co., Singapore, 1995, ISBN 981-02-20952. R. B ECKER, Electromagnetic Fields and Interactions, Dover Publications, Inc., New York, NY, 1982, ISBN 0-486-64290-9. W. G REINER, Classical Electrodynamics, Springer-Verlag, New York, Berlin, Heidelberg, 1996, ISBN 0-387-94799-X. E. H ALLÉN, Electromagnetic Theory, Chapman & Hall, Ltd., London, 1962. J. D. JACKSON, Classical Electrodynamics, third ed., John Wiley & Sons, Inc., New York, NY . . . , 1999, ISBN 0-471-30932-X.. J. C. M AXWELL, A dynamical theory of the electromagnetic field, Royal Society Transactions, 155 (1864). 11
5 As
[2]
[3]
[4] [5]
[6]
[7]
[8]
Julian Schwinger (1918–1994) put it [15]:
‘. . . there are strong theoretical reasons to believe that magnetic charge exists in nature, and may have played an important role in the development of the universe. Searches for magnetic charge continue at the present time, emphasising that electromagnetism is very far from being a closed object’.
18
Version released 1st July 2008 at 20:49.
Downloaded from
Bibliography
[9]
J. C. M AXWELL, A Treatise on Electricity and Magnetism, third ed., vol. 1, Dover Publications, Inc., New York, NY, 1954, ISBN 0-486-60636-8. 4
[10] J. C. M AXWELL, A Treatise on Electricity and Magnetism, third ed., vol. 2, Dover Publications, Inc., New York, NY, 1954, ISBN 0-486-60637-8. [11] D. B. M ELROSE AND R. C. M C P HEDRAN, Electromagnetic Processes in Dispersive Media, Cambridge University Press, Cambridge . . . , 1991, ISBN 0-521-41025-8. [12] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026. [13] F. ROHRLICH, Classical Charged Particles, Perseus Books Publishing, L.L.C., Reading, MA . . . , 1990, ISBN 0-201-48300-9. [14] J. S CHWINGER, A magnetic model of matter, Science, 165 (1969), pp. 757–761. 18 [15] J. S CHWINGER , L. L. D E R AAD , J R ., K. A. M ILTON , AND W. T SAI, Classical Electrodynamics, Perseus Books, Reading, MA, 1998, ISBN 0-7382-0056-5. 18, 121 [16] J. A. S TRATTON, Electromagnetic Theory, McGraw-Hill Book Company, Inc., New York, NY and London, 1953, ISBN 07-062150-0. [17] J. VANDERLINDE, Classical Electromagnetic Theory, John Wiley & Sons, Inc., New York, Chichester, Brisbane, Toronto, and Singapore, 1993, ISBN 0-471-57269-1.
Downloaded from
Version released 1st July 2008 at 20:49.
19
1. Classical Electrodynamics
1.6 Examples
E XAMPLE 1.1
⊲ FARADAY ’ S LAW AS A CONSEQUENCE OF CONSERVATION OF MAGNETIC CHARGE Postulate 1.1 (Indestructibility of magnetic charge). Magnetic charge exists and is indestructible in the same way that electric charge exists and is indestructible. In other words we postulate that there exists an equation of continuity for magnetic charges: ∂ρm (t, x) + ∇ · jm (t, x) = 0 ∂t Use this postulate and Dirac’s symmetrised form of Maxwell’s equations to derive Faraday’s law. The assumption of the existence of magnetic charges suggests a Coulomb-like law for magnetic fields: Bstat (x) = x − x′ µ0 µ0 d3x′ ρm (x′ ) =− 4π V ′ 4π |x − x′ |3 µ0 ρm (x′ ) = − ∇ d3x′ ′ 4π |x − x′ | V
V′
d3x′ ρm (x′ )∇
1 |x − x′ |
(1.55)
[cf. equation (1.5) on page 4 for Estat ] and, if magnetic currents exist, a Biot-Savart-like law for electric fields [cf. equation (1.15) on page 8 for Bstat ]: Estat (x) = − µ0 x − x′ µ0 d3x′ jm (x′ ) × = 4π V ′ 4π |x − x′ |3 jm (x′ ) µ0 = − ∇ × d3x′ 4π |x − x′ | V′ d3x′ jm (x′ ) × ∇ 1 |x − x′ |
V′
(1.56)
Taking the curl of the latter and using the operator ‘bac-cab’ rule, formula (F.59) on page 179, we find that ∇ × Estat (x) = − µ0 = 4π
V′
µ0 ∇× ∇× 4π
V′
d3x′
d3x′ jm (x′ )∇2
1 |x − x′ |
jm (x′ ) = |x − x′ | µ0 − d3x′ [jm (x′ ) · ∇′ ]∇′ 4π V ′
1 |x − x′ |
(1.57)
Comparing with equation (1.18) on page 8 for Estat and the evaluation of the integrals there, we obtain ∇ × Estat (x) = −µ0
V′
d3x′ jm (x′ ) δ(x − x′ ) = −µ0 jm (x)
(1.58)
We assume that formula (1.56) above is valid also for time-varying magnetic currents. Then, with the use of the representation of the Dirac delta function, equation (F.73) on page 179, the equation of continuity for magnetic charge, equation (1.52) on page 17, and the assumption of the generalisation of equation (1.55) to time-dependent magnetic charge distributions, we obtain, formally,
20
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
∇ × E(t, x) = −µ0
V′
d3x′ jm (t, x′ )δ(x − x′ ) − ∂ B(t, x) ∂t
µ0 ∂ 4π ∂t
V′
d3x′ ρm (t, x′ )∇′
1 |x − x′ | (1.59)
= −µ0 jm (t, x) −
[cf. equation (1.24) on page 10] which we recognise as equation (1.50b) on page 16. A transformation of this electromagnetodynamic result by rotating into the ‘electric realm’ of charge space, thereby letting jm tend to zero, yields the electrodynamic equation (1.50b) on page 16, i.e., the Faraday law in the ordinary Maxwell equations. This process also provides an alternative interpretation of the term ∂B/∂t as a magnetic displacement current, dual to the electric displacement current [cf. equation (1.26) on page 11]. By postulating the indestructibility of a hypothetical magnetic charge, we have thereby been able to replace Faraday’s experimental results on electromotive forces and induction in loops as a foundation for the Maxwell equations by a more appealing one. ⊳ E ND OF EXAMPLE 1.1
⊲ D UALITY OF THE ELECTROMAGNETODYNAMIC EQUATIONS Show that the symmetric, electromagnetodynamic form of Maxwell’s equations (Dirac’s symmetrised Maxwell equations), equations (1.50) on page 16, are invariant under the duality transformation (1.54). Explicit application of the transformation yields ρe cos θ + cµ0 ρm sin θ ε0 ⋆ e 1 ρ 1 ρe cos θ + ρm sin θ = = ε0 c ε0 ∂ ⋆B ∂ 1 ∇ × ⋆E + = ∇ × (E cos θ + cB sin θ) + − E sin θ + B cos θ ∂t ∂t c ∂B 1 ∂E = −µ0 jm cos θ − cos θ + cµ0 je sin θ + sin θ ∂t c ∂t 1 ∂E ∂B − sin θ + cos θ = −µ0 jm cos θ + cµ0 je sin θ c ∂t ∂t = −µ0 (−cje sin θ + jm cos θ) = −µ0 ⋆jm 1 ρe ∇ · ⋆B = ∇ · (− E sin θ + B cos θ) = − sin θ + µ0 ρm cos θ c cε0 = µ0 (−cρe sin θ + ρm cos θ) = µ0 ⋆ρm ∇ · ⋆E = ∇ · (E cos θ + cB sin θ) =
E XAMPLE 1.2
(1.60)
(1.61)
(1.62)
Downloaded from
Version released 1st July 2008 at 20:49.
21
1. Classical Electrodynamics
∇ × ⋆B −
1 ∂⋆E 1 1 ∂ = ∇ × (− E sin θ + B cos θ) − 2 (E cos θ + cB sin θ) c2 ∂t c c ∂t 1 ∂B 1 ∂E 1 cos θ + µ0 je cos θ + 2 cos θ = µ0 jm sin θ + c c ∂t c ∂t 1 ∂B 1 ∂E cos θ − sin θ − 2 c ∂t c ∂t 1 m = µ0 j sin θ + je cos θ = µ0 ⋆je c
(1.63)
QED ⊳ E ND OF EXAMPLE 1.2
E XAMPLE 1.3
⊲ D IRAC ’ S SYMMETRISED M AXWELL EQUATIONS FOR A FIXED MIXING ANGLE Show that for a fixed mixing angle θ such that ρm = cρe tan θ j = cj tan θ the symmetrised Maxwell equations reduce to the usual Maxwell equations. Explicit application of the fixed mixing angle conditions on the duality transformation (1.54) on page 17 yields 1 1 ρ = ρe cos θ + ρm sin θ = ρe cos θ + cρe tan θ sin θ c c 1 1 e 2 e 2 e = (ρ cos θ + ρ sin θ) = ρ cos θ cos θ ⋆ m ρ = −cρe sin θ + cρe tan θ cos θ = −cρe sin θ + cρe sin θ = 0 1 e 1 ⋆ e (je cos2 θ + je sin2 θ) = j j = je cos θ + je tan θ sin θ = cos θ cos θ ⋆ m j = −cje sin θ + cje tan θ cos θ = −cje sin θ + cje sin θ = 0
⋆ e m e
(1.64a) (1.64b)
(1.65a) (1.65b) (1.65c) (1.65d)
Hence, a fixed mixing angle, or, equivalently, a fixed ratio between the electric and magnetic charges/currents, ‘hides’ the magnetic monopole influence (ρm and jm ) on the dynamic equations. We notice that the inverse of the transformation given by equation (1.54) on page 17 yields E = ⋆E cos θ − c⋆B sin θ This means that ∇ · E = ∇ · ⋆E cos θ − c∇ · ⋆B sin θ
⋆ e
(1.66)
(1.67)
Furthermore, from the expressions for the transformed charges and currents above, we find that ∇ · ⋆E = 1 ρe ρ = ε0 cos θ ε0 (1.68)
22
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
and ∇ · ⋆B = µ0 ⋆ρ m = 0 so that ∇·E= ρe 1 ρe cos θ − 0 = cos θ ε0 ε0 (1.70) QED ⊳ E ND OF EXAMPLE 1.3 (1.69)
and so on for the other equations.
⊲ C OMPLEX FIELD SIX - VECTOR FORMALISM It is sometimes convenient to introduce the complex field six-vector, also known as the Riemann-Silberstein vector G(t, x) = E(t, x) + icB(t, x)
3 3 3
E XAMPLE 1.4
(1.71)
where E, B ∈ R and hence G ∈ C . One fundamental property of C is that inner (scalar) products in this space are invariant just as they are in R3 . However, as discussed in example M.3 on page 197, the inner (scalar) product in C3 can be defined in two different ways. Considering the special case of the scalar product of G with itself, we have the following two possibilities of defining (the square of) the ‘length’ of G: 1. The inner (scalar) product defined as G scalar multiplied with itself G · G = (E + icB) · (E + icB) = E 2 − c2 B2 + 2icE · B Since this is an invariant scalar quantity, we find that E 2 − c2 B2 = Const (1.73a) (1.73b) (1.72)
E · B = Const
2. The inner (scalar) product defined as G scalar multiplied with the complex conjugate of itself G · G∗ = (E + icB) · (E − icB) = E 2 + c2 B2 (1.74)
which is also an invariant scalar quantity. As we shall see later, this quantity is proportional to the electromagnetic field energy, which indeed is a conserved quantity. 3. As with any vector, the cross product of G with itself vanishes: G × G = (E + icB) × (E + icB) = 0 + 0 + ic(E × B) − ic(E × B) = 0 = E × E − c2 B × B + ic(E × B) + ic(B × E) (1.75)
4. The cross product of G with the complex conjugate of itself
Downloaded from
Version released 1st July 2008 at 20:49.
23
1. Classical Electrodynamics
G × G∗ = (E + icB) × (E − icB)
= E × E + c2 B × B − ic(E × B) + ic(B × E)
(1.76)
= 0 + 0 − ic(E × B) − ic(E × B) = −2ic(E × B)
is proportional to the electromagnetic power flux, to be introduced later. ⊳ E ND OF EXAMPLE 1.4
E XAMPLE 1.5
⊲ D UALITY EXPRESSED IN THE COMPLEX FIELD SIX - VECTOR Expressed in the Riemann-Silberstein complex field vector, introduced in example 1.4 on page 23, the duality transformation equations (1.54) on page 17 become
⋆
G = ⋆E + ic⋆B = E cos θ + cB sin θ − iE sin θ + icB cos θ
= E(cos θ − i sin θ) + icB(cos θ − i sin θ) = e−iθ (E + icB) = e−iθ G
⋆
(1.77)
from which it is easy to see that
⋆
G · ⋆G∗ =
G
2
= e−iθ G · eiθ G∗ = |G|2
(1.78)
while
⋆
G · ⋆G = e−2iθ G · G
(1.79)
Furthermore, assuming that θ = θ(t, x), we see that the spatial and temporal differentiation of ⋆G leads to ∂ t ⋆G ≡
⋆
∂ × G ≡ ∇ × G = −ie ∇θ × G + e ∇ × G
∂ ⋆G = −i(∂t θ)e−iθ G + e−iθ ∂t G ∂t ∂ · ⋆G ≡ ∇ · ⋆G = −ie−iθ ∇θ · G + e−iθ ∇ · G
⋆ −iθ −iθ
(1.80a) (1.80b) (1.80c)
which means that ∂t ⋆G transforms as ⋆G itself only if θ is time-independent, and that ∇ · ⋆G and ∇ × ⋆G transform as ⋆G itself only if θ is space-independent. ⊳ E ND OF EXAMPLE 1.5
24
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
2
E LECTROMAGNETIC WAVES
In this chapter we investigate the dynamical properties of the electromagnetic field by deriving a set of equations which are alternatives to the Maxwell equations. It turns out that these alternative equations are wave equations, indicating that electromagnetic waves are natural and common manifestations of electrodynamics. Maxwell’s microscopic equations [cf. equations (1.45) on page 15] are ρ(t, x) ε0 ∂B ∇×E=− ∂t ∇·B=0 ∇·E= (Gauss’s law) (Faraday’s law) (No free magnetic charges) (Maxwell’s law) (2.1a) (2.1b) (2.1c) (2.1d)
∂E ∇ × B = µ0 j(t, x) + ε0 µ0 ∂t
and can be viewed as an axiomatic basis for classical electrodynamics. They describe, in scalar and vector differential equation form, the electric and magnetic fields E and B produced by given, prescribed charge distributions ρ(t, x) and current distributions j(t, x) with arbitrary time and space dependences. However, as is well known from the theory of differential equations, these four first order, coupled partial differential vector equations can be rewritten as two uncoupled, second order partial equations, one for E and one for B. We shall derive these second order equations which, as we shall see are wave equations, and then discuss the implications of them. We show that for certain media, the B wave field can be easily obtained from the solution of the E wave equation.
25
2. Electromagnetic Waves
2.1 The wave equations
We restrict ourselves to derive the wave equations for the electric field vector E and the magnetic field vector B in an electrically neutral region, i.e., a volume where there is no net charge, ρ = 0, and no electromotive force EEMF = 0.
2.1.1 The wave equation for E
In order to derive the wave equation for E we take the curl of (2.1b) and use (2.1d), to obtain ∇ × (∇ × E) = − ∂ ∂ (∇ × B) = −µ0 ∂t ∂t j + ε0 ∂ E ∂t (2.2)
According to the operator triple product ‘bac-cab’ rule equation (F.64) on page 179 ∇ × (∇ × E) = ∇(∇ · E) − ∇2 E Furthermore, since ρ = 0, equation (2.1a) on page 25 yields ∇·E=0 (2.4) (2.3)
and since EEMF = 0, Ohm’s law, equation (1.28) on page 12, allows us to use the approximation j = σE we find that equation (2.2) above can be rewritten ∇2 E − µ0 ∂ ∂t σE + ε0 ∂ E ∂t =0 (2.6) (2.5)
or, also using equation (1.11) on page 6 and rearranging, ∇2 E − µ0 σ ∂E 1 ∂2 E − 2 2 =0 ∂t c ∂t (2.7)
which is the homogeneous wave equation for E in a uncharged, conducting medium without EMF. For waves propagating in vacuum (no charges, no currents), the wave equation for E is ∇2 E − 1 ∂2 E =− c2 ∂t2
2
E=0
(2.8)
where 2 is the d’Alembert operator, defined according to formula (M.97) on page 199.
26
Version released 1st July 2008 at 20:49.
Downloaded from
The wave equations
2.1.2 The wave equation for B
The wave equation for B is derived in much the same way as the wave equation for E. Take the curl of (2.1d) and use Ohm’s law j = σE to obtain ∇ × (∇ × B) = µ0 ∇ × j + ε0 µ0 ∂ ∂ (∇ × E) = µ0 σ∇ × E + ε0 µ0 (∇ × E) ∂t ∂t (2.9)
which, with the use of equation (F.64) on page 179 and equation (2.1c) on page 25 can be rewritten ∇(∇ · B) − ∇2 B = −µ0 σ ∂B ∂2 − ε0 µ0 2 B ∂t ∂t (2.10)
Using the fact that, according to (2.1c), ∇·B = 0 for any medium and rearranging, we can rewrite this equation as ∇2 B − µ0 σ ∂B 1 ∂2 B − 2 2 =0 ∂t c ∂t (2.11)
This is the wave equation for the magnetic field. For waves propagating in vacuum (no charges, no currents), the wave equation for B is ∇2 B − 1 ∂2 B =− c2 ∂t2
2
B=0
(2.12)
We notice that for the simple propagation media considered here, the wave equations for the magnetic field B has exactly the same mathematical form as the wave equation for the electric field E, equation (2.7) on page 26. Therefore, it suffices to consider only the E field, since the results for the B field follow trivially. For EM waves propagating in more complicated media, containing, eg., inhomogeneities, the wave equation for E and for B do not have the same mathematical form.
2.1.3 The time-independent wave equation for E
If we assume that the temporal dependence of E (and B) is well-behaved enough that it can be represented by a sum of a finite number of temporal spectral (Fourier) components, i.e., in the form of a temporal Fourier series, then it is sufficient to represent the electric field by one of these Fourier components E(t, x) = E0 (x) cos(ωt) = E0 (x)Re e−iωt (2.13)
since the general solution is obtained by a linear superposition (summation) of the result for one such spectral (Fourier) component, often called a time-harmonic
Downloaded from
Version released 1st July 2008 at 20:49.
27
2. Electromagnetic Waves
wave. When we insert this, in complex notation, into equation (2.7) on page 26 we find that ∇2 E0 (x)e−iωt − µ0 σ ∂ 1 ∂2 E0 (x)e−iωt − 2 2 E0 (x)e−iωt ∂t c ∂t 1 2 −iωt = ∇ E0 (x)e − µ0 σ(−iω)E0 (x)e−iωt − 2 (−iω)2 E0 (x)e−iωt c
(2.14)
or, dividing out the common factor e−iωt and rewriting, ∇2 E0 + ω2 c2 1+i σ ε0 ω E0 = 0 (2.15)
Multiplying by e−iωt and introducing the relaxation time τ = ε0 /σ of the medium in question, we see that the differential equation for the time-harmonic wave can be written ∇2 E(t, x) + ω2 c2 1+ i τω E(t, x) = 0 (2.16)
In the limit of very many frequency components the Fourier sum goes over into a Fourier integral. To illustrate this general case, let us introduce the Fourier transform of E(t, x) F [E(t, x)] ≡ Ew (x) =
def
1 2π
∞ −∞
dt E(t, x) eiωt
(2.17)
and the corresponding inverse Fourier transform F −1 [Eω (x)] ≡ E(t, x) =
def ∞ −∞
dω Eω (x) e−iωt
(2.18)
Then we find that the Fourier transform of ∂E(t, x)/∂t becomes F ∂E(t, x) ∂t
def
≡
1 ∞ ∂E(t, x) iωt e dt 2π −∞ ∂t 1 1 ∞ = E(t, x) eiωt −∞ −iω 2π 2π
=0
∞ −∞
dt E(t, x) eiωt
(2.19)
= − iω Eω (x) and that, consequently, F ∂2 E(t, x) ∂t2
def
≡
1 2π
∞ −∞
dt
∂2 E(t, x) ∂t2
eiωt = −ω2 Eω (x)
(2.20)
28
Version released 1st July 2008 at 20:49.
Downloaded from
The wave equations
Fourier transforming equation (2.7) on page 26 and using (2.19) and (2.20), we obtain ∇2 Eω + ω2 c2 1+ i τω Eω = 0 (2.21)
A subsequent inverse Fourier transformation of the solution Eω of this equation leads to the same result as is obtained from the solution of equation (2.16) on page 28. I.e., by considering just one Fourier component we obtain the results which are identical to those that we would have obtained by employing the heavy machinery of Fourier transforms and Fourier integrals. Hence, under the assumption of linearity (superposition principle) there is no need for the heavy, timeconsuming forward and inverse Fourier transform machinery. In the limit of long τ, (2.16) tends to ∇2 E + ω2 E=0 c2 (2.22)
which is a time-independent wave equation for E, representing undamped propagating waves. In the short τ limit we have instead ∇2 E + iωµ0 σE = 0 (2.23)
which is a time-independent diffusion equation for E. For most metals τ ∼ 10−14 s, which means that the diffusion picture is good for all frequencies lower than optical frequencies. Hence, in metallic conductors, the propagation term ∂2 E/c2 ∂t2 is negligible even for VHF, UHF, and SHF signals. Alternatively, we may say that the displacement current ε0 ∂E/∂t is negligible relative to the conduction current j = σE. If we introduce the vacuum wave number k= ω c (2.24)
√ we can write, using the fact that c = 1/ ε0 µ0 according to equation (1.11) on page 6, 1 σ σ 1 σ = = = τω ε0 ω ε0 ck k µ0 σ = R0 ε0 k (2.25)
where in the last step we introduced the characteristic impedance for vacuum R0 = µ0 ≈ 376.7 Ω ε0 (2.26)
Downloaded from
Version released 1st July 2008 at 20:49.
29
2. Electromagnetic Waves
2.2 Plane waves
Consider now the case where all fields depend only on the distance ζ to a given plane with unit normal n. Then the del operator becomes ˆ ∂ ˆ (2.27) ∇ = n = n∇ ˆ ∂ζ and Maxwell’s equations attain the form ∂E n· ˆ =0 (2.28a) ∂ζ ∂E ∂B n× ˆ =− (2.28b) ∂ζ ∂t ∂B =0 (2.28c) n· ˆ ∂ζ ∂E ∂E ∂B = µ0 j(t, x) + ε0 µ0 = µ0 σE + ε0 µ0 (2.28d) n× ˆ ∂ζ ∂t ∂t Scalar multiplying (2.28d) by n, we find that ˆ 0 = n· ˆ n× ˆ ∂B ∂ζ = n · µ0 σ + ε0 µ0 ˆ ∂ ∂t E (2.29)
which simplifies to the first-order ordinary differential equation for the normal component En of the electric field dEn σ + En = 0 (2.30) dt ε0 with the solution En = En0 e−σt/ε0 = En0 e−t/τ (2.31)
This, together with (2.28a), shows that the longitudinal component of E, i.e., the component which is perpendicular to the plane surface is independent of ζ and has a time dependence which exhibits an exponential decay, with a decrement given by the relaxation time τ in the medium. Scalar multiplying (2.28b) by n, we similarly find that ˆ 0 = n· ˆ or ∂B =0 (2.33) ∂t From this, and (2.28c), we conclude that the only longitudinal component of B must be constant in both time and space. In other words, the only non-static solution must consist of transverse components. n· ˆ n× ˆ ∂E ∂ζ = −n · ˆ ∂B ∂t (2.32)
30
Version released 1st July 2008 at 20:49.
Downloaded from
Plane waves
2.2.1 Telegrapher’s equation
In analogy with equation (2.7) on page 26, we can easily derive the equation ∂E 1 ∂2 E ∂2 E − µ0 σ − 2 2 =0 (2.34) ∂ζ 2 ∂t c ∂t This equation, which describes the propagation of plane waves in a conducting medium, is called the telegrapher’s equation. If the medium is an insulator so that σ = 0, then the equation takes the form of the one-dimensional wave equation ∂2 E 1 ∂2 E − =0 (2.35) ∂ζ 2 c2 ∂t2 As is well known, each component of this equation has a solution which can be written Ei = f (ζ − ct) + g(ζ + ct), i = 1, 2, 3 (2.36)
where f and g are arbitrary (non-pathological) functions of their respective arguments. This general solution represents perturbations which propagate along ζ, where the f perturbation propagates in the positive ζ direction and the g perturbation propagates in the negative ζ direction. If we assume that our electromagnetic fields E and B are time-harmonic, i.e., that they can each be represented by a Fourier component proportional to exp{−iωt}, the solution of equation (2.35) above becomes E = E0 e−i(ωt±kζ) = E0 ei(∓kζ−ωt) By introducing the wave vector ωˆ ω ˆ k = kn = n = k ˆ c c this solution can be written as E = E0 ei(k·x−ωt) (2.37)
(2.38)
(2.39)
Let us consider the lower sign in front of kζ in the exponent in (2.37). This corresponds to a wave which propagates in the direction of increasing ζ. Inserting this solution into equation (2.28b) on page 30, gives ∂E = iωB = ik n × E ˆ (2.40) n× ˆ ∂ζ or, solving for B, k 1 1 ˆ √ B = n × E = k × E = k × E = ε0 µ0 n × E ˆ (2.41) ˆ ω ω c Hence, to each transverse component of E, there exists an associated magnetic field given by equation (2.41) above. If E and/or B has a direction in space which is constant in time, we have a plane wave.
Downloaded from
Version released 1st July 2008 at 20:49.
31
2. Electromagnetic Waves
2.2.2 Waves in conductive media
Assuming that our medium has a finite conductivity σ, and making the timeharmonic wave Ansatz in equation (2.34) on page 31, we find that the timeindependent telegrapher’s equation can be written ∂2 E ∂2 E + ε0 µ0 ω2 E + iµ0 σωE = 2 + K 2 E = 0 ∂ζ 2 ∂ζ where K 2 = ε0 µ0 ω2 1 + i σ ε0 ω = ω2 c2 1+i σ ε0 ω = k2 1 + i σ ε0 ω (2.43) (2.42)
where, in the last step, equation (2.24) on page 29 was used to introduce the wave number k. Taking the square root of this expression, we obtain K=k 1+i σ = α + iβ ε0 ω (2.44)
Squaring, one finds that k2 1 + i or β2 = α2 − k2 αβ = k σ 2ε0 ω
2
σ ε0 ω
= (α2 − β2 ) + 2iαβ
(2.45)
(2.46) (2.47)
Squaring the latter and combining with the former, one obtains the second order algebraic equation (in α2 ) α2 (α2 − k2 ) = k4 σ2 4ε2 ω2 0 (2.48)
which can be easily solved and one finds that 1+ α=k
σ ε0 ω 2
+1 (2.49a)
2
2 1+
σ ε0 ω
β=k
−1
2
(2.49b)
32
Version released 1st July 2008 at 20:49.
Downloaded from
Observables and averages
As a consequence, the solution of the time-independent telegrapher’s equation, equation (2.42) on page 32, can be written E = E0 e−βζ ei(αζ−ωt) (2.50)
With the aid of equation (2.41) on page 31 we can calculate the associated magnetic field, and find that it is given by B= 1 ˆ 1 ˆ 1 ˆ K k × E = ( k × E)(α + iβ) = ( k × E) |A| eiγ ω ω ω (2.51)
where we have, in the last step, rewritten α + iβ in the amplitude-phase form |A| exp{iγ}. From the above, we immediately see that E, and consequently also B, is damped, and that E and B in the wave are out of phase. In the limit ε0 ω ≪ σ, we can approximate K as follows: σ K =k 1+i ε0 ω = √
1 2
σ ε0 ω =k i 1−i ε0 ω σ σ = (1 + i) 2ε0 ω
1 2
≈ k(1 + i)
σ 2ε0 ω
(2.52)
ε0 µ0 ω(1 + i)
µ0 σω 2
In this limit we find that when the wave impinges perpendicularly upon the medium, the fields are given, inside the medium, by E′ = E0 exp − B′ = (1 + i) µ0 σω ζ exp i 2 µ0 σω ζ − ωt 2 (2.53a) (2.53b)
µ0 σ ( n × E′ ) ˆ 2ω
Hence, both fields fall off by a factor 1/e at a distance δ= 2 µ0 σω (2.54)
This distance δ is called the skin depth.
2.3 Observables and averages
In the above we have used complex notation quite extensively. This is for mathematical convenience only. For instance, in this notation differentiations are almost trivial to perform. However, every physical measurable quantity is always real
Downloaded from
Version released 1st July 2008 at 20:49.
33
2. Electromagnetic Waves
valued. I.e., ‘Eobservable = Re {Emathematical }’.1 It is particularly important to remember this when one works with products of observable physical quantities. For instance, if we have two physical vectors F and G which both are time-harmonic, i.e., can be represented by Fourier components proportional to exp{−iωt}, then we must make the following interpretation F(t, x) · G(t, x) = Re {F} · Re {G} = Re F0 (x) e−iωt · Re G0 (x) e−iωt (2.55) Furthermore, letting ∗ denote complex conjugate, we can express the real part of the complex vector F as Re {F} = Re F0 (x) e−iωt = 1 [F0 (x) e−iωt + F∗ (x) eiωt ] 0 2 (2.56)
and similarly for G. Hence, the physically acceptable interpretation of the scalar product of two complex vectors, representing physical observables, is F(t, x) · G(t, x) = Re F0 (x) e−iωt · Re G0 (x) e−iωt 1 1 = [F0 (x) e−iωt + F∗ (x) eiωt ] · [G0 (x) e−iωt + G∗ (x) eiωt ] 0 0 2 2 1 = F0 · G∗ + F∗ · G0 + F0 · G0 e−2iωt + F∗ · G∗ e2iωt 0 0 0 0 4 1 = Re F0 · G∗ + F0 · G0 e−2iωt 0 2 1 = Re F0 e−iωt · G∗ eiωt + F0 · G0 e−2iωt 0 2 1 = Re F(t, x) · G∗ (t, x) + F0 · G0 e−2iωt 2 (2.57) Often in physics, we measure temporal averages ( ) of our physical observables. If so, we see that the average of the product of the two physical quantities represented by F and G can be expressed as F · G ≡ Re {F} · Re {G} = 1 Re {F · G∗ } 2 (2.58)
since the temporal average of the oscillating function exp{−2iωt} vanishes.
1 Note
that this is different from quantum physics where Ψobservable = |Ψmathematical |
34
Version released 1st July 2008 at 20:49.
Downloaded from
Bibliography
2.4 Bibliography
[1] J. D. JACKSON, Classical Electrodynamics, third ed., John Wiley & Sons, Inc., New York, NY . . . , 1999, ISBN 0-471-30932-X. [2] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026.
Downloaded from
Version released 1st July 2008 at 20:49.
35
2. Electromagnetic Waves
2.5 Example
E XAMPLE 2.1
⊲ WAVE EQUATIONS IN ELECTROMAGNETODYNAMICS Derive the wave equation for the E field described by the electromagnetodynamic equations (Dirac’s symmetrised Maxwell equations) [cf. equations (1.50) on page 16] ρe ε0 ∂B ∇×E =− − µ0 j m ∂t ∇ · B = µ0 ρ m ∇·E= ∇ × B = ε 0 µ0 (2.59a) (2.59b) (2.59c) (2.59d)
∂E + µ0 j e ∂t
under the assumption of vanishing net electric and magnetic charge densities and in the absence of electromotive and magnetomotive forces. Interpret this equation physically. Taking the curl of (2.59b) and using (2.59d), and assuming, for symmetry reasons, that there exists a linear relation between the magnetic current density jm and the magnetic field B (the magnetic dual of Ohm’s law for electric currents, je = σe E) jm = σm B one finds, noting that ε0 µ0 = 1/c , that ∇ × (∇ × E) = −µ0 ∇ × jm − ∂ ∂ (∇ × B) = −µ0 σm ∇ × B − ∂t ∂t 1 ∂E c2 ∂t − µ0 σe 1 ∂2 E ∂E − 2 2 ∂t c ∂t µ0 j e + 1 ∂E c2 ∂t
2
(2.60)
(2.61)
= −µ0 σm µ0 σe E +
Using the vector operator identity ∇ × (∇ × E) = ∇(∇ · E) − ∇2 E, and the fact that ∇ · E = 0 for a vanishing net electric charge, we can rewrite the wave equation as ∇2 E − µ0 σe + σm c2 ∂E 1 ∂2 E − 2 2 − µ2 σm σe E = 0 0 ∂t c ∂t (2.62)
This is the homogeneous electromagnetodynamic wave equation for E we were after. Compared to the ordinary electrodynamic wave equation for E, equation (2.7) on page 26, we see that we pick up extra terms. In order to understand what these extra terms mean physically, we analyse the time-independent wave equation for a single Fourier component. Then our wave equation becomes ∇2 E + iωµ0 σe + = ∇2 E + ω2 c2 σm c2 1− E+ ω2 E − µ2 σm σe E 0 c2 +i σe + σm /c2 E=0 ε0 ω
1 µ0 m e σ σ ω2 ε0
(2.63)
Realising that, according to formula (2.26) on page 29, µ0 /ε0 is the square of the vacuum radiation resistance R0 , and rearranging a bit, we obtain the time-independent wave equation in
36
Version released 1st July 2008 at 20:49.
Downloaded from
Example
From this equation we conclude that the existence of magnetic charges (magnetic monopoles), and non-vanishing electric and magnetic conductivities would lead to a shift in the effective wave number of the wave. Furthermore, even if the electric conductivity σe vanishes, the imaginary term does not necessarily vanish and the wave might therefore experience damping (or growth) according as σm is positive (or negative). This would happen in a hypothetical medium which is a perfect insulator for electric currents but which can carry magnetic currents. √ Finally, we note that in the particular case that ω = R0 σm σe , the wave equation becomes a (time-independent) diffusion equation ∇2 E + iωµ0 σe + σm c2 E=0 (2.65)
Dirac’s symmetrised electrodynamics R2 m e ω2 σe + σm /c2 0 2 E = 0 ∇ E+ 2 1− 2σ σ 1+i R2 c ω ε0 ω 1 − ω0 σm σe 2
(2.64)
and, hence, no waves exist at all! ⊳ E ND OF EXAMPLE 2.1
Downloaded from
Version released 1st July 2008 at 20:49.
37
Downloaded from
Version released 1st July 2008 at 20:49.
3
E LECTROMAGNETIC P OTENTIALS
As an alternative to expressing the laws of electrodynamics in terms of electric and magnetic fields, it turns out that it is often more convenient to express the theory in terms of potentials. This is particularly true for problems related to radiation and relativity. In this chapter we will introduce and study the properties of such potentials and shall find that they exhibit some remarkable properties which elucidate the fundamental aspects of electromagnetism and lead naturally to the special theory of relativity.
3.1 The electrostatic scalar potential
As we saw in equation (1.8) on page 6, the electrostatic field Estat (x) is irrotational. Hence, it may be expressed in terms of the gradient of a scalar field. If we denote this scalar field by −φstat (x), we get Estat (x) = −∇φstat (x) (3.1) Taking the divergence of this and using equation (1.7) on page 5, we obtain Poisson’s equation ∇2 φstat (x) = −∇ · Estat (x) = − ρ(x) ε0 (3.2)
A comparison with the definition of Estat , namely equation (1.5) on page 4, shows that this equation has the solution φstat (x) = 1 4πε0
V′
d3x′
ρ(x′ ) +α |x − x′ |
(3.3)
39
3. Electromagnetic Potentials
where the integration is taken over all source points x′ at which the charge density ρ(x′ ) is non-zero and α is an arbitrary quantity which has a vanishing gradient. An example of such a quantity is a scalar constant. The scalar function φstat (x) in equation (3.3) on page 39 is called the electrostatic scalar potential.
3.2 The magnetostatic vector potential
Consider the equations of magnetostatics (1.22) on page 9. From equation (F.63) on page 179 we know that any 3D vector a has the property that ∇ · (∇ × a) ≡ 0 and in the derivation of equation (1.17) on page 8 in magnetostatics we found that ∇ · Bstat (x) = 0. We therefore realise that we can always write Bstat (x) = ∇ × Astat (x) (3.4)
where Astat (x) is called the magnetostatic vector potential. We saw above that the electrostatic potential (as any scalar potential) is not unique: we may, without changing the physics, add to it a quantity whose spatial gradient vanishes. A similar arbitrariness is true also for the magnetostatic vector potential. In the magnetostatic case, we may start from Biot-Savart’s law as expressed by equation (1.15) on page 8. Identifying this expression with equation (3.4) allows us to define the static vector potential as Astat (x) = µ0 4π d3x′ j(x′ ) + a(x) |x − x′ | (3.5)
V′
where a(x) is an arbitrary vector field whose curl vanishes. From equation (F.62) on page 179 we know that such a vector can always be written as the gradient of a scalar field.
3.3 The electrodynamic potentials
Let us now generalise the static analysis above to the electrodynamic case, i.e., the case with temporal and spatial dependent sources ρ(t, x) and j(t, x), and corresponding fields E(t, x) and B(t, x), as described by Maxwell’s equations (1.45) on page 15. In other words, let us study the electrodynamic potentials φ(t, x) and A(t, x).
40
Version released 1st July 2008 at 20:49.
Downloaded from
Gauge transformations
From equation (1.45c) on page 15 we note that also in electrodynamics the homogeneous equation ∇ · B(t, x) = 0 remains valid. Because of this divergencefree nature of the time- and space-dependent magnetic field, we can express it as the curl of an electromagnetic vector potential: B(t, x) = ∇ × A(t, x) (3.6)
Inserting this expression into the other homogeneous Maxwell equation (1.32) on page 13, we obtain ∂ ∂ [∇ × A(t, x)] = −∇ × A(t, x) ∂t ∂t or, rearranging the terms, ∇ × E(t, x) = − ∇ × E(t, x) + ∂ A(t, x) ∂t =0 (3.7)
(3.8)
As before we utilise the vanishing curl of a vector expression to write this vector expression as the gradient of a scalar function. If, in analogy with the electrostatic case, we introduce the electromagnetic scalar potential function −φ(t, x), equation (3.8) becomes equivalent to ∂ A(t, x) = −∇φ(t, x) (3.9) ∂t This means that in electrodynamics, E(t, x) is calculated from the potentials according to the formula E(t, x) + ∂ A(t, x) (3.10) ∂t and B(t, x) from formula (3.6) above. Hence, it is a matter of taste whether we want to express the laws of electrodynamics in terms of the potentials φ(t, x) and A(t, x), or in terms of the fields E(t, x) and B(t, x). However, there exists an important difference between the two approaches: in classical electrodynamics the only directly observable quantities are the fields themselves (and quantities derived from them) and not the potentials. On the other hand, the treatment becomes significantly simpler if we use the potentials in our calculations and then, at the final stage, use equation (3.6) and equation (3.10) above to calculate the fields or physical quantities expressed in the fields. E(t, x) = −∇φ(t, x) −
3.4 Gauge transformations
We saw in section 3.1 on page 39 and in section 3.2 on page 40 that in electrostatics and magnetostatics we have a certain mathematical degree of freedom, up to
Downloaded from
Version released 1st July 2008 at 20:49.
41
3. Electromagnetic Potentials
terms of vanishing gradients and curls, to pick suitable forms for the potentials and still get the same physical result. In fact, the way the electromagnetic scalar potential φ(t, x) and the vector potential A(t, x) are related to the physically observables gives leeway for similar ‘manipulation’ of them also in electrodynamics. If we transform φ(t, x) and A(t, x) simultaneously into new ones φ′ (t, x) and ′ A (t, x) according to the mapping scheme ∂Γ(t, x) ∂t A(t, x) → A′ (t, x) = A(t, x) − ∇Γ(t, x) φ(t, x) → φ′ (t, x) = φ(t, x) + (3.11a) (3.11b)
where Γ(t, x) is an arbitrary, differentiable scalar function called the gauge function, and insert the transformed potentials into equation (3.10) on page 41 for the electric field and into equation (3.6) on page 41 for the magnetic field, we obtain the transformed fields ∂(∇Γ) ∂A ∂(∇Γ) ∂A ∂A′ = −∇φ − − + = −∇φ − ∂t ∂t ∂t ∂t ∂t ′ ′ B = ∇ × A = ∇ × A − ∇ × (∇Γ) = ∇ × A E′ = −∇φ′ − (3.12a) (3.12b)
where, once again equation (F.62) on page 179 was used. We see that the fields are unaffected by the gauge transformation (3.11). A transformation of the potentials φ and A which leaves the fields, and hence Maxwell’s equations, invariant is called a gauge transformation. A physical law which does not change under a gauge transformation is said to be gauge invariant. It is only those quantities (expressions) that are gauge invariant that have experimental significance. Of course, the EM fields themselves are gauge invariant.
3.5 Gauge conditions
Inserting (3.10) and (3.6) on page 41 into Maxwell’s equations (1.45) on page 15 we obtain, after some simple algebra and the use of equation (1.11) on page 6 ρ(t, x) ∂ − (∇ · A) ε0 ∂t 2 1 ∂A 1 ∂φ ∇2 A − 2 2 − ∇(∇ · A) = −µ0 j(t, x) + 2 ∇ c ∂t c ∂t ∇2 φ = −
(3.13a) (3.13b)
42
Version released 1st July 2008 at 20:49.
Downloaded from
Gauge conditions
which can be rewritten in the following, more symmetric, form of general inhomogeneous wave equations 1 ∂2 φ ρ(t, x) ∂ 1 ∂φ − ∇2 φ = + ∇·A+ 2 c2 ∂t2 ε0 ∂t c ∂t 1 ∂2 A 1 ∂φ − ∇2 A = µ0 j(t, x) − ∇ ∇ · A + 2 2 ∂t2 c c ∂t (3.14a) (3.14b)
These two second order, coupled, partial differential equations, representing in all four scalar equations (one for φ and one each for the three components Ai , i = 1, 2, 3 of A) are completely equivalent to the formulation of electrodynamics in terms of Maxwell’s equations, which represent eight scalar first-order, coupled, partial differential equations. As they stand, equations (3.13) on page 42 and equations (3.14) look complicated and may seem to be of limited use. However, if we write equation (3.6) on page 41 in the form ∇ × A(t, x) = B(t, x) we can consider this as a specification of ∇ × A. But we know from Helmholtz’ theorem that in order to determine the (spatial) behaviour of A completely, we must also specify ∇ · A. Since this divergence does not enter the derivation above, we are free to choose ∇ · A in whatever way we like and still obtain the same physical results!
3.5.1 Lorenz-Lorentz gauge
If we choose ∇ · A to fulfil the so called Lorenz-Lorentz gauge condition1 ∇·A+ 1 ∂φ =0 c2 ∂t (3.15)
the coupled inhomogeneous wave equation (3.14) on page 43 simplify into the following set of uncoupled inhomogeneous wave equations:
2
φ ≡
def
2
A ≡
def
1 ∂2 1 ∂2 φ ρ(t, x) − ∇2 φ = 2 2 − ∇2 φ = 2 ∂t2 c c ∂t ε0 1 ∂2 A 1 ∂2 − ∇2 A = 2 2 − ∇2 A = µ0 j(t, x) c2 ∂t2 c ∂t
(3.16a) (3.16b)
where 2 is the d’Alembert operator discussed in example M.5 on page 199. Each of these four scalar equations is an inhomogeneous wave equation of the
1 In fact, the Dutch physicist Hendrik Antoon Lorentz, who in 1903 demonstrated the covariance of Maxwell’s equations, was not the original discoverer of this condition. It had been discovered by the Danish physicist Ludvig V. Lorenz already in 1867 [6]. In the literature, this fact has sometimes been overlooked and the condition was earlier referred to as the Lorentz gauge condition.
Downloaded from
Version released 1st July 2008 at 20:49.
43
3. Electromagnetic Potentials
following generic form:
2
Ψ(t, x) = f (t, x)
(3.17)
where Ψ is a shorthand for either φ or one of the components Ai of the vector potential A, and f is the pertinent generic source component, ρ(t, x)/ε0 or µ0 ji (t, x), respectively. We assume that our sources are well-behaved enough in time t so that the Fourier transform pair for the generic source function f F −1 [ fω (x)] ≡ f (t, x) = F [ f (t, x)] ≡ fω (x) =
∞ def def ∞ −∞ ∞
dω fω (x) e−iωt dt f (t, x) eiωt
(3.18a) (3.18b)
1 2π
−∞
exists, and that the same is true for the generic potential component Ψ: Ψ(t, x) = Ψω (x) =
−∞
dω Ψω (x) e−iωt
∞ −∞
(3.19a) (3.19b)
1 2π
dt Ψ(t, x) eiωt
Inserting the Fourier representations (3.18a) and (3.19a) into equation (3.17) above, and using the vacuum dispersion relation for electromagnetic waves ω = ck the generic 3D inhomogeneous wave equation, equation (3.17), turns into ∇2 Ψω (x) + k2 Ψω (x) = − fω (x) (3.21) (3.20)
which is a 3D inhomogeneous time-independent wave equation, often called the 3D inhomogeneous Helmholtz equation. As postulated by Huygen’s principle, each point on a wave front acts as a point source for spherical wavelets of varying amplitude (weight). A new wave front is formed by a linear superposition of the individual wavelets from each of the point sources on the old wave front. The solution of (3.21) can therefore be expressed as a weighted superposition of solutions of an equation where the source term has been replaced by a single point source ∇2G(x, x′ ) + k2G(x, x′ ) = −δ(x − x′ ) (3.22)
and the solution of equation (3.21) above which corresponds to the frequency ω is given by the superposition Ψω (x) =
V′
d3x′ fω (x′ )G(x, x′ )
(3.23)
44
Version released 1st July 2008 at 20:49.
Downloaded from
Gauge conditions
where fω (x′ ) is the wavelet amplitude at the source point x′ . The function G(x, x′ ) is called the Green function or the propagator. Due to translational invariance in space, G(x, x′ ) = G(x − x′ ). Furthermore, in equation (3.22) on page 44, the Dirac generalised function δ(x − x′ ), which represents the point source, depends only on x − x′ and there is no angular dependence in the equation. Hence, the solution can only be dependent on r = |x − x′ | and not on the direction of x − x′ . If we interpret r as the radial coordinate in a spherically polar coordinate system, and recall the expression for the Laplace operator in such a coordinate system, equation (3.22) on page 44 becomes d2 (rG) + k2 (rG) = −rδ(r) dr2 (3.24)
Away from r = |x − x′ | = 0, i.e., away from the source point x′ , this equation takes the form d2 (rG) + k2 (rG) = 0 dr2 with the well-known general solution G = C+ eikr e−ik|x−x | e−ikr eik|x−x | + C− + C− ≡ C+ ′| r r |x − x |x − x′ |
′ ′
(3.25)
(3.26)
where C ± are constants. In order to evaluate the constants C ± , we insert the general solution, equation (3.26), into equation (3.22) on page 44 and integrate over a small volume around r = |x − x′ | = 0. Since G( x − x′ ) ∼ C + 1 1 + C− , |x − x′ | |x − x′ | x − x′ → 0 (3.27)
The volume integrated equation (3.22) on page 44 can under this assumption be approximated by C+ + C− d3x′ ∇2
V′
V′
1 |x − x′ |
+ k2 C + + C −
V′
d3x′
1 |x − x′ |
(3.28)
=−
d3x′ δ( x − x′ )
In virtue of the fact that the volume element d3x′ in spherical polar coordinates is proportional to |x − x′ |2 , the second integral vanishes when |x − x′ | → 0. Furthermore, from equation (F.73) on page 179, we find that the integrand in the first integral can be written as −4πδ(|x − x′ |) and, hence, that C+ + C− = 1 4π (3.29)
Downloaded from
Version released 1st July 2008 at 20:49.
45
3. Electromagnetic Potentials
Insertion of the general solution equation (3.26) on page 45 into equation (3.23) on page 44 gives eik|x−x | e−ik|x−x | Ψω (x) = C d x fω (x ) + C − d3x′ fω (x′ ) (3.30) |x − x′ | |x − x′ | V′ V′ The inverse Fourier transform of this back to the t domain is obtained by inserting the above expression for Ψω (x) into equation (3.19a) on page 44:
+ 3 ′ ′
′ ′
Ψ(t, x) = C
+ V′
dx
3 ′
∞ −∞
dω fω (x )
∞
′
exp −iω t −
k|x−x′ | ω
|x − x′ |
|x − x′ | ′ ′ If we introduce the retarded time tret and the advanced time tadv in the following way [using the fact that in vacuum k/ω = 1/c, according to equation (3.20) on page 44]:
V′ −∞
+ C−
d3x′
dω fω (x′ )
exp −iω t +
k|x−x′ | ω
(3.31)
k |x − x′ | |x − x′ | =t− ω c k |x − x′ | |x − x′ | ′ ′ tadv = tadv (t, x − x′ ) = t + =t+ ω c and use equation (3.18a) on page 44, we obtain
′ ′ tret = tret (t, x − x′ ) = t −
(3.32a) (3.32b)
′ ′ f (tadv , x′ ) f (tret , x′ ) + C − d3x′ (3.33) |x − x′ | |x − x′ | V′ V′ This is a solution to the generic inhomogeneous wave equation for the potential components equation (3.17) on page 44. We note that the solution at time t at the field point x is dependent on the behaviour at other times t′ of the source at x′ and that both retarded and advanced t′ are mathematically acceptable solutions. However, if we assume that causality requires that the potential at (t, x) is set up ′ by the source at an earlier time, i.e., at (tret , x′ ), we must in equation (3.33) above − set C = 0 and therefore, according to equation (3.29) on page 45, C + = 1/(4π).2 From the above discussion on the solution of the inhomogeneous wave equations in the Lorenz-Lorentz gauge we conclude that, under the assumption of causality, the electrodynamic potentials in vacuum can be written
Ψ(t, x) = C +
d3x′
ρ(t′ , x′ ) 1 d3x′ ret ′ 4πε0 V ′ |x − x | ′ j(t , x′ ) µ0 d3x′ ret ′ A(t, x) = 4π V ′ |x − x | φ(t, x) =
(3.34a) (3.34b)
2 In fact, inspired by a discussion by Paul A. M. Dirac, John A. Wheeler and Richard P. Feynman derived in 1945 a fully self-consistent electrodynamics using both the retarded and the advanced potentials [8]; see also [4].
46
Version released 1st July 2008 at 20:49.
Downloaded from
Gauge conditions
Since these retarded potentials were obtained as solutions to the Lorenz-Lorentz equations (3.16) on page 43 they are valid in the Lorenz-Lorentz gauge but may be gauge transformed according to the scheme described in subsection 3.4 on page 41. As they stand, we shall use them frequently in the following. The potentials φ(t, x) and A(t, x) calculated from (3.13a) on page 42, with an arbitrary choice of ∇ · A, can be further gauge transformed according to (3.11) on page 42. If, in particular, we choose ∇ · A according to the Lorenz-Lorentz condition, equation (3.15) on page 43, and apply the gauge transformation (3.11) on the resulting Lorenz-Lorentz potential equations (3.16) on page 43, these equations will be transformed into ∂ 1 ∂2 Γ ρ(t, x) 1 ∂2 φ − ∇2 φ + − ∇2 Γ = 2 ∂t2 2 ∂t2 c ∂t c ε0 2 2 1 ∂Γ 1 ∂A − ∇2 A − ∇ 2 2 − ∇2 Γ = µ0 j(t, x) c2 ∂t2 c ∂t (3.35a) (3.35b)
We notice that if we require that the gauge function Γ(t, x) itself be restricted to fulfil the wave equation 1 ∂2 Γ − ∇2 Γ = 0 (3.36) c2 ∂t2 these transformed Lorenz-Lorentz equations will keep their original form. The set of potentials which have been gauge transformed according to equation (3.11) on page 42 with a gauge function Γ(t, x) restricted to fulfil equation (3.36), or, in other words, those gauge transformed potentials for which the Lorenz-Lorentz equations (3.16) are invariant, comprise the Lorenz-Lorentz gauge.
3.5.2 Coulomb gauge
In Coulomb gauge, often employed in quantum electrodynamics, one chooses ∇ · A = 0 so that equations (3.13) on page 42 or equations (3.14) on page 43 become ρ(t, x) (3.37a) ε0 1 ∂2 A 1 ∂φ ∇2 A − 2 2 = −µ0 j(t, x) + 2 ∇ (3.37b) c ∂t c ∂t The first of these two is the time-dependent Poisson’s equation which, in analogy with equation (3.3) on page 39, has the solution ∇2 φ = − φ(t, x) = 1 4πε0
V′
d3x′
ρ(t, x′ ) +α |x − x′ |
(3.38)
Downloaded from
Version released 1st July 2008 at 20:49.
47
3. Electromagnetic Potentials
where α has vanishing gradient. We note that in the scalar potential expression the charge density source is evaluated at time t. The retardation (and advancement) effects therefore occur only in the vector potential A, which is the solution of the inhomogeneous wave equation equation (3.37b) on page 47. In order to solve this equation, one splits up j in a longitudinal ( ) and transverse (⊥) part, j ≡ j + j⊥ where ∇ · j⊥ = 0 and ∇ × j = 0, and note that the equation of continuity, equation (1.23) on page 10 becomes ∂ρ ∂ +∇·j = −ε0 ∇2 φ + ∇ · j ∂t ∂t =∇· −ε0 ∇ ∂φ ∂t +j =0 (3.39) Furthermore, since ∇ × ∇ = 0 and ∇ × j = 0, one finds that ∇× −ε0 ∇ ∂φ ∂t +j =0 (3.40)
Integrating these two equations, letting f be an arbitrary, well-behaved vector field and g an arbitrary, well-behaved scalar field, one obtains 1 ∂φ ∇ = µ0 j + ∇ × f c2 ∂t 1 ∂φ ∇ = µ0 j + ∇g c2 ∂t From the fact that ∇ × f = ∇g, it is clear that ∇ × (∇ × f) = ∇ × ∇g = 0 ∇ · (∇ × f) = ∇ · ∇g = 0 (3.42a) (3.42b) (3.41a) (3.41b)
which, according to Helmholtz’ theorem, means that ∇ × f = ∇g = 0. The inhomogeneous wave equation equation (3.37b) on page 47 thus becomes ∇2 A − 1 ∂2 A 1 ∂φ = −µ0 j + 2 ∇ = −µ0 j + µ0 j = −µ0 j⊥ 2 ∂t2 c c ∂t (3.43)
which shows that in Coulomb gauge the source of the vector potential A is the transverse part of the current j⊥ . The longitudinal part of the current j does not contribute to the vector potential. The retarded solution is (cf. equation (3.34a) on page 46): A(t, x) = µ0 4π d3x′
′ j⊥ (tret , x′ ) |x − x′ |
(3.44)
V′
The Coulomb gauge condition is therefore also called the transverse gauge.
48
Version released 1st July 2008 at 20:49.
Downloaded from
Bibliography
3.5.3 Velocity gauge
If ∇ · A fulfils the velocity gauge condition, sometimes referred to as the complete α-Lorenz gauge, ∇·A+α 1 ∂φ = 0, c2 ∂t α= c2 v2 (3.45)
we obtain the Lorenz-Lorentz gauge condition in the limit α = 1, and the Coulomb gauge condition in the limit α = 0, respectively. Hence, the velocity gauge is a generalisation of both these gauges. Inserting equation (3.45) into the coupled inhomogeneous wave equation (3.14) on page 43 they become 1 ∂2 φ ρ(t, x) =− v2 ∂t2 ε0 2 1 ∂A 1 − α ∂φ ∇2 A − 2 2 = −µ0 j(t, x) + 2 ∇ c ∂t c ∂t ∇2 φ − or, in a more symmetric form, ∇2 φ − 1 ∂2 φ ρ(t, x) 1 − α ∂ ∂φ =− − 2 c2 ∂t2 ε0 c ∂t ∂t 2 1 − α ∂φ 1 ∂A ∇2 A − 2 2 = −µ0 j(t, x) + 2 ∇ c ∂t c ∂t (3.47a) (3.47b) (3.46a) (3.46b)
Other useful gauges are • The Poincaré gauge (or radial gauge) where [1]
1
φ(t, x) = −x ·
1
dλ E(t, λx)
0
(3.48a) (3.48b)
A(t, x) =
0
dλ B(t, λx) × λx
• The temporal gauge, also known as the Hamilton gauge, defined by φ = 0. • The axial gauge, defined by A3 = 0. The process of choosing a particular gauge condition is known as gauge fixing.
3.6 Bibliography
[1] W. E. B RITTIN , W. R. S MYTHE , AND W. W YSS, Poincaré gauge in electrodynamics, American Journal of Physics, 50 (1982), pp. 693–696. 49
Downloaded from
Version released 1st July 2008 at 20:49.
49
3. Electromagnetic Potentials
[2] L. D. FADEEV AND A. A. S LAVNOV, Gauge Fields: Introduction to Quantum Theory, No. 50 in Frontiers in Physics: A Lecture Note and Reprint Series. Benjamin/Cummings Publishing Company, Inc., Reading, MA . . . , 1980, ISBN 0-8053-9016-2. [3] M. G UIDRY, Gauge Field Theories: An Introduction with Applications, John Wiley & Sons, Inc., New York, NY . . . , 1991, ISBN 0-471-63117-5. [4] [5] J. D. JACKSON, Classical Electrodynamics, third ed., John Wiley & Sons, Inc., New York, NY . . . , 1999, ISBN 0-471-30932-X. [6] L. L ORENZ, Philosophical Magazine (1867), pp. 287–301. 43 [7] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026. [8] J. A. W HEELER AND R. P. F EYNMAN, Interaction with the absorber as a mechanism for radiation, Reviews of Modern Physics, 17 (1945), pp. 157–. 46
50
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
3.7 Examples
⊲ E LECTROMAGNETODYNAMIC POTENTIALS In Dirac’s symmetrised form of electrodynamics (electromagnetodynamics), Maxwell’s equations are replaced by [see also equations (1.50) on page 16]: ∇·E= ρe ε0 ∂B ∂t (3.49a) (3.49b) (3.49c) (3.49d)
E XAMPLE 3.1
∇ × E = −µ0 jm − ∇ · B = µ0 ρ m
∂E ∇ × B = µ0 j e + ε 0 µ0 ∂t
In this theory, one derives the inhomogeneous wave equations for the usual ‘electric’ scalar and vector potentials (φe , Ae ) and their ‘magnetic’ counterparts (φm , Am ) by assuming that the potentials are related to the fields in the following symmetrised form: E = −∇φe (t, x) − ∂ e A (t, x) − ∇ × Am ∂t 1 1 ∂ B = − 2 ∇φm (t, x) − 2 Am (t, x) + ∇ × Ae c c ∂t (3.50a) (3.50b)
In the absence of magnetic charges, or, equivalently for φm ≡ 0 and Am ≡ 0, these formulae reduce to the usual Maxwell theory formula (3.10) on page 41 and formula (3.6) on page 41, respectively, as they should. Inserting the symmetrised expressions (3.50) above into equations (3.49), one obtains [cf., equations (3.13a) on page 42] ρe (t, x) ∂ (∇ · Ae ) = − ∂t ε0 ρm (t, x) ∂ m 2 m ∇ φ + (∇ · A ) = − ∂t ε0 1 ∂ 2 Ae 1 ∂φe 2 e − ∇ A + ∇ ∇ · Ae + 2 2 ∂t 2 c c ∂t ∇2 φe + 1 ∂φm 1 ∂ 2 Am − ∇2 Am + ∇ ∇ · Am + 2 c2 ∂t2 c ∂t (3.51a) (3.51b) = µ0 je (t, x) = µ0 jm (t, x) (3.51c) (3.51d)
By choosing the conditions on the divergence of the vector potentials according to the LorenzLorentz condition [cf. equation (3.15) on page 43] 1 ∂ e φ =0 c2 ∂t 1 ∂ ∇ · Am + 2 φm = 0 c ∂t ∇ · Ae + these coupled wave equations simplify to (3.52) (3.53)
Downloaded from
Version released 1st July 2008 at 20:49.
51
3. Electromagnetic Potentials
1 ∂2 φe − ∇2 φe c2 ∂t2 1 ∂ 2 Ae − ∇2 Ae c2 ∂t2 1 ∂2 φm − ∇2 φm c2 ∂t2 1 ∂ 2 Am − ∇2 Am c2 ∂t2
=
ρe (t, x) ε0
(3.54a) (3.54b) (3.54c) (3.54d)
= µ0 je (t, x) = ρm (t, x) ε0
= µ0 jm (t, x)
exhibiting, once again, the striking properties of Dirac’s symmetrised Maxwell theory. ⊳ E ND OF EXAMPLE 3.1
52
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
4
E LECTROMAGNETIC F IELDS AND M ATTER
The microscopic Maxwell equations (1.45) derived in chapter 1 are valid on all scales where a classical description is good. However, when macroscopic matter is present, it is sometimes convenient to use the corresponding macroscopic Maxwell equations (in a statistical sense) in which auxiliary, derived fields are introduced in order to incorporate effects of macroscopic matter when this is immersed fully or partially in an electromagnetic field.
4.1 Electric polarisation and displacement
In certain cases, for instance in engineering applications, it may be convenient to separate the influence of an external electric field on free charges on the one hand and on neutral matter in bulk on the other. This view, which, as we shall see, has certain limitations, leads to the introduction of (di)electric polarisation and magnetisation which, in turn, justifies the introduction of two help quantities, the electric displacement vector D and the magnetising field H.
4.1.1 Electric multipole moments
The electrostatic properties of a spatial volume containing electric charges and located near a point x0 can be characterized in terms of the total charge or electric
53
4. Electromagnetic Fields and Matter
monopole moment q=
V′
d3x′ ρ(x′ )
(4.1)
where the ρ is the charge density introduced in equation (1.7) on page 5, the electric dipole moment vector p(x0 ) = d3x′ (x′ − x0 ) ρ(x′ ) (4.2)
V′
with components pi , i = 1, 2, 3, the electric quadrupole moment tensor
Q(x0 ) =
V′
d3x′ (x′ − x0 )(x′ − x0 ) ρ(x′ )
(4.3)
with components Qi j , i, j = 1, 2, 3, and higher order electric moments. In particular, the electrostatic potential equation (3.3) on page 39 from a charge distribution located near x0 can be Taylor expanded in the following way: φstat (x) = (x − x0 )i 1 1 q + 2 pi |x − x | 4πε0 |x − x0 | |x − x0 | 0 1 3 (x − x0 )i (x − x0 ) j 1 + Qi j − δi j 2 |x − x0 | |x − x0 | 2 |x − x0 |3
(4.4) + ...
where Einstein’s summation convention over i and j is implied. As can be seen from this expression, only the first few terms are important if the field point (observation point) is far away from x0 . For a normal medium, the major contributions to the electrostatic interactions come from the net charge and the lowest order electric multipole moments induced by the polarisation due to an applied electric field. Particularly important is the dipole moment. Let P denote the electric dipole moment density (electric dipole moment per unit volume; unit: C/m2 ), also known as the electric polarisation, in some medium. In analogy with the second term in the expansion equation (4.4) above, the electric potential from this volume distribution P(x′ ) of electric dipole moments p at the source point x′ can be written φp (x) = 1 4πε0 1 = 4πε0 x − x′ 1 =− |x − x′ |3 4πε0 V′ 1 d3x′ P(x′ ) · ∇′ ′ |x − x′ | V d3x′ P(x′ ) · d3x′ P(x′ ) · ∇ 1 |x − x′ | (4.5)
V′
54
Version released 1st July 2008 at 20:49.
Downloaded from
Electric polarisation and displacement
Using the expression equation (M.101) on page 200 and applying the divergence theorem, we can rewrite this expression for the potential as follows: φp (x) = 1 4πε0 1 = 4πε0 ∇′ · P(x′ ) P(x′ ) − d3x′ ′| |x − x |x − x′ | V′ V′ P(x′ ) ∇′ · P(x′ ) d2x′ n′ · ˆ − d3x′ |x − x′ | |x − x′ | S′ V′ d3x′ ∇′ ·
(4.6)
where the first term, which describes the effects of the induced, non-cancelling dipole moment on the surface of the volume, can be neglected, unless there is a discontinuity in n · P at the surface. Doing so, we find that the contribution from ˆ the electric dipole moments to the potential is given by φp = 1 4πε0 d3x′ −∇′ · P(x′ ) |x − x′ | (4.7)
V′
Comparing this expression with expression equation (3.3) on page 39 for the electrostatic potential from a static charge distribution ρ, we see that −∇ · P(x) has the characteristics of a charge density and that, to the lowest order, the effective charge density becomes ρ(x) − ∇ · P(x), in which the second term is a polarisation term. The version of equation (1.7) on page 5 where free, ‘true’ charges and bound, polarisation charges are separated thus becomes ∇·E= ρtrue (x) − ∇ · P(x) ε0 (4.8)
Rewriting this equation, and at the same time introducing the electric displacement vector (C/m2 ) D = ε0 E + P we obtain ∇ · (ε0 E + P) = ∇ · D = ρtrue (x) (4.10) (4.9)
where ρtrue is the ‘true’ charge density in the medium. This is one of Maxwell’s equations and is valid also for time varying fields. By introducing the notation ρpol = −∇ · P for the ‘polarised’ charge density in the medium, and ρtotal = ρtrue + ρpol for the ‘total’ charge density, we can write down the following alternative version of Maxwell’s equation (4.21a) on page 58 ∇·E= ρtotal (x) ε0 (4.11)
Downloaded from
Version released 1st July 2008 at 20:49.
55
4. Electromagnetic Fields and Matter
Often, for low enough field strengths |E|, the linear and isotropic relationship between P and E P = ε0 χE (4.12)
is a good approximation. The quantity χ is the electric susceptibility which is material dependent. For electromagnetically anisotropic media such as a magnetised plasma or a birefringent crystal, the susceptibility is a tensor. In general, the relationship is not of a simple linear form as in equation (4.12) above but nonlinear terms are important. In such a situation the principle of superposition is no longer valid and non-linear effects such as frequency conversion and mixing can be expected. Inserting the approximation (4.12) into equation (4.9) on page 55, we can write the latter D = εE where, approximately, ε = ε0 (1 + χ) (4.14) (4.13)
4.2 Magnetisation and the magnetising field
An analysis of the properties of stationary magnetic media and the associated currents shows that three such types of currents exist: 1. In analogy with ‘true’ charges for the electric case, we may have ‘true’ currents jtrue , i.e., a physical transport of true charges. 2. In analogy with electric polarisation P there may be a form of charge transport associated with the changes of the polarisation with time. Such currents, induced by an external field, are called polarisation currents and are identified with ∂P/∂t. 3. There may also be intrinsic currents of a microscopic, often atomic, nature that are inaccessible to direct observation, but which may produce net effects at discontinuities and boundaries. These magnetisation currents are denoted jM . No magnetic monopoles have been observed yet. So there is no correspondence in the magnetic case to the electric monopole moment (4.1). The lowest
56
Version released 1st July 2008 at 20:49.
Downloaded from
Magnetisation and the magnetising field
order magnetic moment, corresponding to the electric dipole moment (4.2), is the magnetic dipole moment m= 1 2 d3x′ (x′ − x0 ) × j(x′ ) (4.15)
V′
For a distribution of magnetic dipole moments in a volume, we may describe this volume in terms of the magnetisation, or magnetic dipole moment per unit volume, M. Via the definition of the vector potential one can show that the magnetisation current and the magnetisation is simply related: jM = ∇ × M (4.16)
In a stationary medium we therefore have a total current which is (approximately) the sum of the three currents enumerated above: jtotal = jtrue + ∂P +∇×M ∂t (4.17)
One might then, erroneously, be led to think that LHS = ∇ × B RHS = µ0 jtrue + while (INCORRECT) Moving the term ∇ × M from the right hand side (RHS) to the left hand side (LHS) and introducing the magnetising field (magnetic field intensity, Ampèreturn density) as H= B −M µ0 (4.18) ∂P +∇×M ∂t
and using the definition for D, equation (4.9) on page 55, we can write this incorrect equation in the following form LHS = ∇ × H RHS = jtrue + ∂D ∂E ∂P = jtrue + − ε0 ∂t ∂t ∂t
As we see, in this simplistic view, we would pick up a term which makes the equation inconsistent: the divergence of the left hand side vanishes while the divergence of the right hand side does not! Maxwell realised this and to overcome
Downloaded from
Version released 1st July 2008 at 20:49.
57
4. Electromagnetic Fields and Matter
this inconsistency he was forced to add his famous displacement current term which precisely compensates for the last term in the right hand side. In chapter 1, we discussed an alternative way, based on the postulate of conservation of electric charge, to introduce the displacement current. We may, in analogy with the electric case, introduce a magnetic susceptibility for the medium. Denoting it χm , we can write H= B µ (4.19)
where, approximately, µ = µ0 (1 + χm ) (4.20)
Maxwell’s equations expressed in terms of the derived field quantities D and H are ∇ · D = ρ(t, x) ∂B ∇×E=− ∂t ∇ × H = j(t, x) + ∇·B=0 (4.21a) (4.21b) (4.21c)
∂D (4.21d) ∂t and are called Maxwell’s macroscopic equations. These equations are convenient to use in certain simple cases. Together with the boundary conditions and the constitutive relations, they describe uniquely (but only approximately!) the properties of the electric and magnetic fields in matter.
4.3 Energy and momentum
We shall use Maxwell’s macroscopic equations in the following considerations on the energy and momentum of the electromagnetic field and its interaction with matter.
4.3.1 The energy theorem in Maxwell’s theory
Scalar multiplying (4.21c) by H, (4.21d) by E and subtracting, we obtain H · (∇ × E) − E · (∇ × H) = ∇ · (E × H) ∂B ∂D 1∂ = −H · −E·j−E· =− (H · B + E · D) − j · E ∂t ∂t 2 ∂t (4.22)
58
Version released 1st July 2008 at 20:49.
Downloaded from
Energy and momentum
Integration over the entire volume V and using Gauss’s theorem (the divergence theorem), we obtain − ∂ ∂t 1 d3x′ (H · B + E · D) = 2 d3x′ j · E + d2x′ n′ · (E × H) ˆ (4.23)
V′
V′
S′
We assume the validity of Ohm’s law so that in the presence of an electromotive force field, we make the linear approximation equation (1.28) on page 12: j = σ(E + EEMF ) which means that d3x′ j · E = d3x′ j2 − σ d3x′ j · EEMF (4.25) (4.24)
V′
V′
V′
Inserting this into equation (4.23) above, one obtains d3x′ j · EEMF = d3x′ j2 ∂ + σ ∂t
′
V′
V′
1 d3x′ (E · D + H · B) 2 V′
Field energy
Applied electric power
Joule heat
+
S′
d x n · (E × H) ˆ
Radiated power
2 ′
(4.26)
which is the energy theorem in Maxwell’s theory also known as Poynting’s theorem. It is convenient to introduce the following quantities: 1 d3x′ E · D 2 V′ 1 Um = d3x′ H · B 2 V′ S=E×H Ue = (4.27) (4.28) (4.29)
where Ue is the electric field energy, Um is the magnetic field energy, both measured in J, and S is the Poynting vector (power flux), measured in W/m2 .
4.3.2 The momentum theorem in Maxwell’s theory
Let us now investigate the momentum balance (force actions) in the case that a field interacts with matter in a non-relativistic way. For this purpose we consider
Downloaded from
Version released 1st July 2008 at 20:49.
59
4. Electromagnetic Fields and Matter
the force density given by the Lorentz force per unit volume ρE + j × B. Using Maxwell’s equations (4.21) and symmetrising, we obtain ρE + j × B = (∇ · D)E + ∇ × H − ∂D ∂t ×B ∂D ×B ∂t
= E(∇ · D) + (∇ × H) × B −
= E(∇ · D) − B × (∇ × H) ∂B ∂ − (D × B) + D × ∂t ∂t = E(∇ · D) − B × (∇ × H) ∂ − (D × B) − D × (∇ × E) + H(∇ · B) ∂t
=0
= [E(∇ · D) − D × (∇ × E)] + [H(∇ · B) − B × (∇ × H)] ∂ − (D × B) ∂t (4.30) One verifies easily that the ith vector components of the two terms in square brackets in the right hand member of (4.30) can be expressed as [E(∇ · D) − D × (∇ × E)]i = 1 2 E· ∂E ∂D −D· ∂xi ∂xi + ∂ ∂x j 1 Ei D j − E · D δi j 2 (4.31)
and [H(∇ · B) − B × (∇ × H)]i = 1 2 H· ∂B ∂H −B· ∂xi ∂xi + ∂ ∂x j 1 Hi B j − B · H δi j 2 (4.32)
respectively. Using these two expressions in the ith component of equation (4.30) and reshuffling terms, we get (ρE + j × B)i − = ∂ ∂x j 1 2 E· ∂D ∂E −D· ∂xi ∂xi + H· ∂B ∂H −B· ∂xi ∂xi + ∂ (D × B)i ∂t
1 1 Ei D j − E · D δi j + Hi B j − H · B δi j 2 2 (4.33)
60
Version released 1st July 2008 at 20:49.
Downloaded from
Energy and momentum
Introducing the electric volume force Fev via its ith component (Fev )i = (ρE + j × B)i − 1 2 E· ∂D ∂E −D· ∂xi ∂xi + H· ∂B ∂H −B· ∂xi ∂xi (4.34)
and the Maxwell stress tensor (electromagnetic linear momentum flux) T with components 1 1 T i j = Ei D j − E · D δi j + Hi B j − H · B δi j 2 2 we finally obtain the force equation Fev + ∂ (D × B) ∂t =
i
(4.35)
∂T i j = (∇ · T)i ∂x j
(4.36)
If we introduce the relative electric permittivity κe and the relative magnetic permeability κm as D = κe ε0 E = εE B = κm µ0 H = µH we can rewrite (4.36) as ∂T i j = ∂x j Fev + κe κm ∂S c2 ∂t (4.39)
i
(4.37) (4.38)
where S is the Poynting vector defined in equation (4.29) on page 59. Integration over the entire volume V yields
V′
d3x′ Fev +
d dt
V′
d3x′
κe κm S= c2
S′
d2x′ T n ˆ
(4.40)
Force on the matter
Field momentum
Maxwell stress
which expresses the balance between the force on the matter, the rate of change of the electromagnetic field momentum and the Maxwell stress. This equation is called the momentum theorem in Maxwell’s theory. In vacuum (4.40) becomes
V′
d3x′ ρ(E + v × B) +
1 d c2 dt
V′
d3x′ S =
S′
d2x′ T n ˆ
(4.41)
or d mech d field p + p = dt dt
S′
d2x′ T n ˆ
(4.42)
Downloaded from
Version released 1st July 2008 at 20:49.
61
4. Electromagnetic Fields and Matter
4.4 Bibliography
[1] E. H ALLÉN, Electromagnetic Theory, Chapman & Hall, Ltd., London, 1962. [2] J. D. JACKSON, Classical Electrodynamics, third ed., John Wiley & Sons, Inc., New York, NY . . . , 1999, ISBN 0-471-30932-X. [3] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026. [4] J. A. S TRATTON, Electromagnetic Theory, McGraw-Hill Book Company, Inc., New York, NY and London, 1953, ISBN 07-062150-0.
62
Version released 1st July 2008 at 20:49.
Downloaded from
Example
4.5 Example
⊲ TAYLOR EXPANSION OF THE ELECTROSTATIC POTENTIAL The electrostatic potential is φstat (x) = 1 4πε0
V′
E XAMPLE 4.1
d3x′
For a charge distribution source ρ(x′ ), well localised in a small volume V ′ around x0 , we Taylor expand the inverse distance 1/ |x − x′ | with respect to x0 to obtain 1 1 = |x − x′ | |(x − x0 ) − (x′ − x0 )| =
ρ(x′ ) |x − x′ |
(4.43)
1 3 ∞ ∂n |x−x | 1 1 3 0 ··· ∑ [−(x′1 − x0i1 )] · · · [−(x′n − x0in )] +∑ i i |x − x0 | n=1 n! i∑ in =1 ∂xi1 · · · ∂xin =1 1 1 ∞ ∂n |x−x | 1 (−1)n 0 ′ n1 ′ n2 ′ n3 +∑ ∑ n (x − x01 ) (x2 − x02 ) (x3 − x03 ) n1 n2 |x − x0 | n=1 n1 +n2 +n3 =n n1 !n2 !n3 ! ∂x1 ∂x2 ∂x33 1 ni ≥0
=
(4.44)
Inserting this expansion into the integrand of equation (4.43), we get φstat (x) = +∑
∞
1 4πε0
V′ d
1 ∂n |x−x | (−1)n 0 n3 n1 n2 ∑ n=1 n1 +n2 +n3 =n n1 !n2 !n3 ! ∂x1 ∂x2 ∂x3 ni ≥0
x ρ(x′ ) |x − x0 |
3 ′
V′
d3x′ (x′ − x01 )n1 (x′ − x02 )n2 (x′ − x03 )n3 ρ(x′ ) 1 2 3 (4.45)
Limiting ourselves to the first three terms 1 φ (x) = 4πε0
stat 1 1 3 3 3 ∂2 |x−x | ∂ |x−x | q 1 0 0 + ∑ ∑ Qi j + ... − pi ∂xi 2 ∂xi ∂x j |x − x0 | ∑ i=1 j=1 i=1
(4.46)
and recalling that
1 ∂ |x−x | xi − x0i 0 = − ∂xi |x − x0 |
(4.47)
and
1 ∂2 |x−x | 3(xi − x0i )(x j − x0 j ) − |x − x0 |2 δi j 0 = ∂xi ∂x j |x − x0 |5
(4.48)
we see that equation (4.4) on page 54 follows. ⊳ E ND OF EXAMPLE 4.1
Downloaded from
Version released 1st July 2008 at 20:49.
63
Downloaded from
Version released 1st July 2008 at 20:49.
5
E LECTROMAGNETIC F IELDS FROM A RBITRARY S OURCE D ISTRIBUTIONS
While, in principle, the electric and magnetic fields can be calculated from the Maxwell equations in chapter 1, or even from the wave equations in chapter 2, it is often physically more lucid to calculate them from the electromagnetic potentials derived in chapter 3. In this chapter we will derive the electric and magnetic fields from the potentials. We recall that in order to find the solution (3.33) for the generic inhomogeneous wave equation (3.17) on page 44 we presupposed the existence of a Fourier transform pair (3.18a) on page 44 for the generic source term f (t, x) = fω (x) =
∞ −∞
dω fω (x) e−iωt
∞ −∞
(5.1a) (5.1b)
1 2π
dt f (t, x) eiωt
That such transform pairs exist is true for most physical variables which are neither strictly monotonically increasing nor strictly monotonically decreasing with time. For charge and current densities varying in time we can therefore, without loss of generality, work with individual Fourier components ρω (x) and jω (x), respectively. Strictly speaking, the existence of a single Fourier component assumes a monochromatic source (i.e., a source containing only one single frequency component), which in turn requires that the electric and magnetic fields exist for infinitely long times. However, by taking the proper limits, we may still use this approach even for sources and fields of finite duration.
65
5. Electromagnetic Fields from Arbitrary Source Distributions
This is the method we shall utilise in this chapter in order to derive the electric and magnetic fields in vacuum from arbitrary given charge densities ρ(t, x) and current densities j(t, x), defined by the temporal Fourier transform pairs ρ(t, x) = ρω (x) = and j(t, x) = jω (x) =
∞ −∞ ∞
1 2π
−∞
dω ρω (x) e−iωt
∞ −∞
(5.2a) (5.2b)
dt ρ(t, x) eiωt
dω jω (x) e−iωt
∞ −∞
(5.3a) (5.3b)
1 2π
dt j(t, x) eiωt
under the assumption that only retarded potentials produce physically acceptable solutions. The temporal Fourier transform pair for the retarded scalar potential can then be written φ(t, x) = φω (x) =
∞ −∞
dω φω (x) e−iωt
∞ −∞
(5.4a) 1 4πε0 d3x′ ρω (x′ ) eik|x−x | |x − x′ |
′
1 2π
dt φ(t, x) eiωt =
(5.4b)
V′
where in the last step, we made use of the explicit expression for the temporal Fourier transform of the generic potential component Ψω (x), equation (3.30) on page 46. Similarly, the following Fourier transform pair for the vector potential must exist: A(t, x) = Aω (x) =
∞ −∞
dω Aω (x) e−iωt
∞ −∞
(5.5a) µ0 4π d3x′ jω (x′ ) eik|x−x | |x − x′ |
′
1 2π
dt A(t, x) eiωt =
(5.5b)
V′
Similar transform pairs exist for the fields themselves. In the limit that the sources can be considered monochromatic containing only one single frequency ω0 , we have the much simpler expressions ρ(t, x) = ρ0 (x)e−iω0 t j(t, x) = j0 (x)e
−iω0 t −iω0 t
(5.6a) (5.6b) (5.6c) (5.6d)
φ(t, x) = φ0 (x)e
A(t, x) = A0 (x)e−iω0 t
66
Version released 1st July 2008 at 20:49.
Downloaded from
The magnetic field
where again the real-valuedness of all these quantities is implied. As discussed above, we can safely assume that all formulae derived for a general temporal Fourier representation of the source (general distribution of frequencies in the source) are valid for these simple limiting cases. We note that in this context, we can make the formal identification ρω = ρ0 δ(ω − ω0 ), jω = j0 δ(ω − ω0 ) etc., and that we therefore, without any loss of stringency, let ρ0 mean the same as the Fourier amplitude ρω and so on.
5.1 The magnetic field
Let us now compute the magnetic field from the vector potential, defined by equation (5.5a) and equation (5.5b) on page 66, and formula (3.6) on page 41:
B(t, x) = ∇ × A(t, x)
(5.7)
The calculations are much simplified if we work in ω space and, at the final stage, inverse Fourier transform back to ordinary t space. We are working in the Lorenz-Lorentz gauge and note that in ω space the Lorenz-Lorentz condition, equation (3.15) on page 43, takes the form k ∇ · Aω − i φω = 0 c
(5.8)
which provides a relation between (the Fourier transforms of) the vector and scalar potentials. Using the Fourier transformed version of equation (5.7) and equation (5.5b) on page 66, we obtain
Bω (x) = ∇ × Aω (x) =
µ0 ∇× 4π
V′
d3x′ jω (x′ )
eik|x−x | |x − x′ |
′
(5.9)
Downloaded from
Version released 1st July 2008 at 20:49.
67
5. Electromagnetic Fields from Arbitrary Source Distributions
Utilising formula (F.57) on page 179 and recalling that jω (x′ ) does not depend on x, we can rewrite this as µ0 Bω (x) = − 4π µ0 =− 4π eik|x−x | d x jω (x ) × ∇ |x − x′ | V′ x − x′ ′ d3x′ jω (x′ ) × − eik|x−x | ′ |3 |x − x V′ 1 x − x′ ik|x−x′ | + d3x′ jω (x′ ) × ik e ′ |x − x′ | |x − x′ | V
3 ′ ′
′
(5.10)
=
µ0 4π
jω (x′ )eik|x−x | × (x − x′ ) |x − x′ |3 V′ ′ (−ik)jω (x′ )eik|x−x | × (x − x′ ) + d3x′ |x − x′ |2 V′ d3x′
′
From this expression for the magnetic field in the frequency (ω) domain, we obtain the total magnetic field in the temporal (t) domain by taking the inverse Fourier transform (using the identity −ik = −iω/c): B(t, x) =
∞ −∞
dω Bω (x) e−iωt dx
V′ 3 ′ ∞ ′ −i(ωt−k|x−x′ |) −∞ dω jω (x )e ′3
µ0 = 4π
+ = µ0 4π
1 c
V′
V′
d3x′
dx
′ ′ 3 ′ j(tret , x )
|x − x | ˙ ′ , x′ ) × (x − x′ ) × (x − x ) µ0 j(t + d3x′ ret 3 4πc V ′ |x − x′ | |x − x′ |2
′ Radiation field
∞ ′ −i(ωt−k|x−x′ |) −∞ dω (−iω)jω (x )e ′2
|x − x |
× (x − x′ ) × (x − x′ )
Induction field
(5.11) where ˙ ret , x′ ) def ≡ j(t′ ∂j ∂t (5.12)
′ t=tret
′ and tret is given in equation (3.32) on page 46. The first term, the induction field, dominates near the current source but falls off rapidly with distance from it, is the electrodynamic version of the Biot-Savart law in electrostatics, formula (1.15) on page 8. The second term, the radiation field or the far field, dominates at large distances and represents energy that is transported out to infinity. Note how the spatial derivatives (∇) gave rise to a time derivative (˙)!
68
Version released 1st July 2008 at 20:49.
Downloaded from
The electric field
5.2 The electric field
In order to calculate the electric field, we use the temporally Fourier transformed version of formula (3.10) on page 41, inserting equations (5.4b) and (5.5b) as the explicit expressions for the Fourier transforms of φ and A: Eω (x) = −∇φω (x) + iωAω (x) eik|x−x | iµ0 ω 1 ∇ d3x′ ρω (x′ ) + =− 4πε0 4π |x − x′ | V′ ′ ′ ′ ik|x−x | 1 (x − x ) ρω (x )e = d3x′ ′ |3 ′ 4πε0 V |x − x − ik
V′
′
eik|x−x | d x jω (x ) |x − x′ | V′
3 ′ ′
′
′
d3x′
ρω (x′ )(x − x′ ) jω (x′ ) − c |x − x′ |
eik|x−x | |x − x′ |
(5.13) (5.14)
Using the Fourier transform of the continuity equation (1.23) on page 10 ∇′ · jω (x′ ) − iωρω (x′ ) = 0
we see that we can express ρω in terms of jω as follows i (5.15) ρω (x′ ) = − ∇′ · jω (x′ ) ω Doing so in the last term of equation (5.13) above, and also using the fact that k = ω/c, we can rewrite this equation as 1 Eω (x) = 4πε0 ρω (x′ )eik|x−x | (x − x′ ) dx |x − x′ |3 V′ [∇′ · jω (x′ )](x − x′ ) 1 d3x′ − ikjω (x′ ) − c V′ |x − x′ |
3 ′
′
eik|x−x | |x − x′ |
′
(5.16)
Iω The last vector-valued integral can be further rewritten in the following way: Iω = =
V′ V′
d3x′ d3x′
But, since ∂ ′ ∂xm
eik|x−x | [∇′ · jω (x′ )](x − x′ ) − ikjω (x′ ) |x − x′ | |x − x′ | ′ ∂ jωm xl − xl′ eik|x−x | − ik jωl (x′ ) xl ˆ ′ ∂xm |x − x′ | |x − x′ | = xl − xl′ ik|x−x′ | e |x − x′ |2 ∂ xl − xl′ ik|x−x′ | + jωm ′ e ∂xm |x − x′ |2 ∂ jωm ′ ∂xm
′
(5.17)
jωm
xl − xl′ ik|x−x′ | e |x − x′ |2
(5.18)
Downloaded from
Version released 1st July 2008 at 20:49.
69
5. Electromagnetic Fields from Arbitrary Source Distributions
we can rewrite Iω as ∂ ′ ∂xm xl − xl′ ′ x eik|x−x | ˆ ′ |2 l |x − x xl − xl′ ′ xl eik|x−x | ˆ jωm |x − x′ |2 eik|x−x | |x − x′ |
′
Iω = − +
V′
d3x′ jωm d3x′ ∂ ′ ∂xm
+ ikjω
(5.19)
V′
where, according to Gauss’s theorem, the last term vanishes if jω is assumed to be limited and tends to zero at large distances. Further evaluation of the derivative in the first term makes it possible to write eik|x−x | 2 ′ + jω · (x − x′ ) (x − x′ )eik|x−x | ′ |2 ′ |4 |x − x |x − x jω · (x − x′ ) (x − x′ ) |x − x′ |3 eik|x−x | + jω
′ ′
Iω = −
V′
d3x′ −jω
V′
− ik
d3x′
−
eik|x−x | |x − x′ |
′
(5.20)
Using the triple product ‘bac-cab’ formula (F.51) on page 178 backwards, and inserting the resulting expression for Iω into equation (5.16) on page 69, we arrive at the following final expression for the Fourier transform of the total E field: 1 eik|x−x | iµ0 ω + ∇ d3x′ ρω (x′ ) 4πε0 4π |x − x′ | V′ ′ ρω (x′ )eik|x−x | (x − x′ ) 1 d3x′ = 4πε0 V ′ |x − x′ |3 1 c 1 + c ik − c + d3x′
′ ′
Eω (x) = −
V′
d3x′ jω (x′ )
eik|x−x | |x − x′ |
′
[jω (x′ )eik|x−x | · (x − x′ )](x − x′ ) |x − x′ |4 V′ ′ [jω (x′ )eik|x−x | × (x − x′ )] × (x − x′ ) d3x′ |x − x′ |4 V′ ′ [jω (x′ )eik|x−x | × (x − x′ )] × (x − x′ ) d3x′ |x − x′ |3 V′
(5.21)
Taking the inverse Fourier transform of equation (5.21), once again using the vacuum relation ω = kc, we find, at last, the expression in time domain for the
70
Version released 1st July 2008 at 20:49.
Downloaded from
The radiation fields
total electric field: E(t, x) = =
∞ −∞
dω Eω (x) e−iωt
V′
1 4πε0
d3x′
′ ρ(tret , x′ )(x − x′ ) |x − x′ |3 ′ [j(tret , x′ ) · (x − x′ )](x − x′ ) |x − x′ |4 ′ [j(tret , x′ ) × (x − x′ )] × (x − x′ ) |x − x′ |4
Retarded Coulomb field
+
1 4πε0 c 1 4πε0 c
V′
d3x′
Intermediate field
(5.22)
+
V′
d3x′
Intermediate field
1 + 4πε0 c2
V′
d3x′
˙ ′ [j(tret , x′ ) × (x − x′ )] × (x − x′ ) |x − x′ |3
Radiation field
Here, the first term represents the retarded Coulomb field and the last term represents the radiation field which carries energy over very large distances. The other two terms represent an intermediate field which contributes only in the near zone and must be taken into account there. With this we have achieved our goal of finding closed-form analytic expressions for the electric and magnetic fields when the sources of the fields are completely arbitrary, prescribed distributions of charges and currents. The only assumption made is that the advanced potentials have been discarded; recall the discussion following equation (3.33) on page 46 in chapter 3.
5.3 The radiation fields
In this section we study electromagnetic radiation, i.e., those parts of the electric and magnetic fields, calculated above, which are capable of carrying energy and momentum over large distances. We shall therefore make the assumption that the observer is located in the far zone, i.e., very far away from the source region(s). The fields which are dominating in this zone are by definition the radiation fields. From equation (5.11) on page 68 and equation (5.22) above, which give the
Downloaded from
Version released 1st July 2008 at 20:49.
71
5. Electromagnetic Fields from Arbitrary Source Distributions
total electric and magnetic fields, we obtain Brad (t, x) =
∞ −∞
dω Brad ω (x) e−iωt =
µ0 4πc
V′
d3x′
˙ ret , x′ ) × (x − x′ ) j(t′ |x − x′ |2 (5.23a)
Erad (t, x) =
∞ −∞
dω Erad ω (x) e−iωt [˙ ret , x′ ) × (x − x′ )] × (x − x′ ) j(t′ dx |x − x′ |3 V′
3 ′
1 = 4πε0 c2 where ˙ ret , x′ ) def ≡ j(t′ ∂j ∂t
(5.23b)
(5.24)
′ t=tret
Instead of studying the fields in the time domain, we can often make a spectrum analysis into the frequency domain and study each Fourier component separately. A superposition of all these components and a transformation back to the time domain will then yield the complete solution. The Fourier representation of the radiation fields equation (5.23a) and equation (5.23b) above were included in equation (5.10) on page 68 and equation (5.21) on page 70, respectively and are explicitly given by 1 ∞ dt Brad (t, x) eiωt 2π −∞ kµ0 jω (x′ ) × (x − x′ ) ik|x−x′ | e = −i d3x′ 4π V ′ |x − x′ |2 µ0 jω (x′ ) × k ik|x−x′ | = −i d3x′ e 4π V ′ |x − x′ | 1 ∞ dt Erad (t, x) eiωt Erad (x) = ω 2π −∞ k [jω (x′ ) × (x − x′ )] × (x − x′ ) ik|x−x′ | = −i e d3x′ 4πε0 c V ′ |x − x′ |3 1 [jω (x′ ) × k] × (x − x′ ) ik|x−x′ | = −i d3x′ e 4πε0 c V ′ |x − x′ |2 Brad (x) = ω
(5.25a)
(5.25b)
ˆ where we used the fact that k = k k = k(x − x′ )/ |x − x′ |. If the source is located near a point x0 inside a volume V ′ and has such a limited spatial extent that max |x′ − x0 | ≪ |x − x′ |, and the integration surface S , centred on x0 , has a large enough radius |x − x0 | ≫ max |x′ − x0 |, we see from
72
Version released 1st July 2008 at 20:49.
Downloaded from
The radiation fields
dS = d2x n ˆ k
S (x0 ) x − x′ x − x0 x′ x′ − x0 x0
x
V′ O
F IGURE 5 .1 : Relation between the surface normal and the k vector for radiation generated at source points x′ near the point x0 in the source volume V ′ . At distances much larger than the extent of V ′ , the unit vector n, normal to the surface ˆ ˆ S which has its centre at x0 , and the unit vector k of the radiation k vector from x′ are nearly coincident.
figure 5.1 that we can approximate k x − x′ ≡ k · (x − x′ ) ≡ k · (x − x0 ) − k · (x′ − x0 ) ≈ k |x − x0 | − k · (x′ − x0 )
(5.26)
Recalling from Formula (F.45) and formula (F.46) on page 178 that dS = |x − x0 |2 dΩ = |x − x0 |2 sin θ dθ dϕ ˆ ˆ and noting from figure 5.1 that k and n are nearly parallel, we see that we can approximate ˆ k · dS d2x ˆ ≡ k · n ≈ dΩ ˆ |x − x0 |2 |x − x0 |2
(5.27)
Both these approximations will be used in the following. Within approximation (5.26) the expressions (5.25a) and (5.25b) for the radi-
Downloaded from
Version released 1st July 2008 at 20:49.
73
5. Electromagnetic Fields from Arbitrary Source Distributions
ation fields can be approximated as µ0 ik|x−x0 | jω (x′ ) × k −ik·(x′ −x0 ) e e d3x′ 4π |x − x′ | V′ (5.28a) µ0 eik|x−x0 | ′ ≈ −i d3x′ [jω (x′ ) × k] e−ik·(x −x0 ) 4π |x − x0 | V ′ [jω (x′ ) × k] × (x − x′ ) −ik·(x′ −x0 ) 1 eik|x−x0 | d3x′ Erad (x) ≈ −i e ω 4πε0 c |x − x′ |2 V′ 1 eik|x−x0 | (x − x0 ) ′ ≈i × d3x′ [jω (x′ ) × k] e−ik·(x −x0 ) ′ 4πε0 c |x − x0 | |x − x0 | V (5.28b) Brad (x) ≈ −i ω I.e., if max |x′ − x0 | ≪ |x − x′ |, then the fields can be approximated as spherical waves multiplied by dimensional and angular factors, with integrals over points in the source volume only.
5.4 Radiated energy
Let us consider the energy that is carried in the radiation fields Brad , equation (5.25a), and Erad , equation (5.25b) on page 72. We have to treat signals with limited lifetime and hence finite frequency bandwidth differently from monochromatic signals.
5.4.1 Monochromatic signals
If the source is strictly monochromatic, we can obtain the temporal average of the radiated power P directly, simply by averaging over one period so that S = E×H = 1 1 Re {E × B∗ } = Re Eω e−iωt × (Bω e−iωt )∗ 2µ0 2µ0 1 1 = Re Eω × B∗ e−iωt eiωt = Re Eω × B∗ ω ω 2µ0 2µ0
(5.29)
Using the far-field approximations (5.28a) and (5.28b) and the fact that 1/c = √ √ ε0 µ0 and R0 = µ0 /ε0 according to the definition (2.26) on page 29, we obtain S = 1 1 R 2 0 32π |x − x0 |2
2 V′
d3x′ (jω × k)e−ik·(x −x0 )
′
x − x0 |x − x0 |
(5.30)
74
Version released 1st July 2008 at 20:49.
Downloaded from
Radiated energy
or, making use of (5.27) on page 73, dP 1 = R0 dΩ 32π2
2 V′
d3x′ (jω × k)e−ik·(x −x0 )
′
(5.31)
which is the radiated power per unit solid angle.
5.4.2 Finite bandwidth signals
A signal with finite pulse width in time (t) domain has a certain spread in frequency (ω) domain. To calculate the total radiated energy we need to integrate over the whole bandwidth. The total energy transmitted through a unit area is the time integral of the Poynting vector:
∞ −∞
dt S(t) = =
∞ −∞ ∞ −∞
dt (E × H) dω
∞ −∞
dω
′
∞ −∞
dt (Eω × H ) e
ω′
−i(ω+ω′ )t
(5.32)
If we carry out the temporal integration first and use the fact that
∞ −∞
dt e−i(ω+ω )t = 2πδ(ω + ω′ )
′
(5.33)
equation (5.32) can be written [cf. Parseval’s identity]
∞ −∞
dt S(t) = 2π = 2π
∞ −∞
dω (Eω × H−ω )
∞ ∞ 0
0
dω (Eω × H−ω ) + dω (Eω × H−ω ) − dω (Eω × H−ω ) +
= 2π
0
−∞ −∞ 0 ∞ 0
dω (Eω × H−ω ) dω (Eω × H−ω )
= 2π 2π = µ0 2π = µ0
∞ 0 ∞ 0 ∞ 0
(5.34)
dω (E−ω × Hω )
dω (Eω × B−ω + E−ω × Bω ) dω (Eω × B∗ + E∗ × Bω ) ω ω
where the last step follows from physical requirement of real-valuedness of Eω and Bω . We insert the Fourier transforms of the field components which dominate at large distances, i.e., the radiation fields (5.25a) and (5.25b). The result, after
Downloaded from
Version released 1st July 2008 at 20:49.
75
5. Electromagnetic Fields from Arbitrary Source Distributions
integration over the area S of a large sphere which encloses the source volume V ′ , is U= 1 4π µ0 ε0 d2x n · ˆ
∞ 0
dω
V′
d3x′
S
jω × k ik|x−x′ | e |x − x′ |
2
ˆ k
(5.35)
Inserting the approximations (5.26) and (5.27) into equation (5.35) above and also introducing U=
0 ∞
dωUω
(5.36)
and recalling the definition (2.26) on page 29 for the vacuum resistance R0 we obtain dUω 1 dω ≈ R0 dΩ 4π
2 V′
d3x′ (jω × k)e−ik·(x −x0 )
′
dω
(5.37)
which, at large distances, is a good approximation to the energy that is radiated per unit solid angle dΩ in a frequency band dω. It is important to notice that Formula (5.37) includes only source coordinates. This means that the amount of energy that is being radiated is independent on the distance to the source (as long as it is large).
5.5 Bibliography
[1] [2] J. D. JACKSON, Classical Electrodynamics, third ed., John Wiley & Sons, Inc., New York, NY . . . , 1999, ISBN 0-471-30932-X. [3] L. D. L ANDAU AND E. M. L IFSHITZ, The Classical Theory of Fields, fourth revised English ed., vol. 2 of Course of Theoretical Physics, Pergamon Press, Ltd., Oxford . . . , 1975, ISBN 0-08-025072-6. [4] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026. [5] J. A. S TRATTON, Electromagnetic Theory, McGraw-Hill Book Company, Inc., New York, NY and London, 1953, ISBN 07-062150-0.
76
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
6
E LECTROMAGNETIC R ADIATION AND R ADIATING S YSTEMS
In chapter 3 we were able to derive general expressions for the scalar and vector potentials from which we then, in chapter 5, calculated the total electric and magnetic fields from arbitrary distributions of charge and current sources. The only limitation in the calculation of the fields was that the advanced potentials were discarded. Thus, one can, at least in principle, calculate the radiated fields, Poynting flux, energy and other electromagnetic quantities for an arbitrary current density Fourier component and then add these Fourier components together to construct the complete electromagnetic field at any time at any point in space. However, in practice, it is often difficult to evaluate the source integrals unless the current has a simple distribution in space. In the general case, one has to resort to approximations. We shall consider both these situations.
6.1 Radiation from an extended source volume at rest
Certain radiating systems have a symmetric geometry or are in any other way simple enough that a direct (semi-)analytic calculation of the radiated fields and energy is possible. This is for instance the case when the radiating current flows in a finite, conducting medium of simple geometry at rest such as in a stationary antenna.
77
6. Electromagnetic Radiation and Radiating Systems
6.1.1 Radiation from a one-dimensional current distribution
Let us apply equation (5.31) on page 75 to calculate the radiated EM power from a one-dimensional, time-varying current. Such a current can be set up by feeding the EMF of a generator (eg., a transmitter) onto a stationary, linear, straight, thin, conducting wire across a very short gap at its centre. Due to the EMF the charges in this thin wire of finite length L are set into motion to produce a time-varying antenna current which is the source of the EM radiation. Linear antennas of this type are called dipole antennas. For simplicity, we assume that the conductor resistance and the energy loss due to the electromagnetic radiation are negligible. Choosing our coordinate system such that the x3 axis is along the antenna axis, ′ ′ ′ the antenna current can be represented as j(t′ , x′ ) = δ(x1 )δ(x2 )J(t′ , x3 ) x3 (meaˆ 2 ′ ′ sured in A/m ) where J(t , x3 ) is the current (measured in A) along the antenna wire. Since we can assume that the antenna wire is infinitely thin, the current must vanish at the endpoints −L/2 and L/2 and is equal to the supplied current at the midpoint where the antenna is fed across a very short gap in the antenna wire. ′ For each Fourier frequency component ω0 , the antenna current J(t′ , x3 ) can be ′ ′ written as I(x3 ) exp{−iω0 t } so that the antenna current density can be represented as j(t′ , x′ ) = j0 (x′ ) exp{−iω0 t′ } [cf. equations (5.6) on page 66] where
′ ′ ′ j0 (x′ ) = δ(x1 )δ(x2 )I(x3 )
(6.1)
′ and where the spatially varying Fourier amplitude I(x3 ) of the antenna current fulfils the time-independent wave equation (Helmholtz equation)
d2 I ′ + k2 I(x3 ) = 0 , ′2 dx3
I(−L/2) = I(L/2) = 0 ,
I(0) = I0
(6.2)
This equation has the well-known solution
′ I(x3 ) = I0 ′ sin[k(L/2 − x3 )] sin(kL/2)
(6.3)
where I0 is the amplitude of the antenna current (measured in A), assumed to be constant and supplied by the generator/transmitter at the antenna feed point (in our case the midpoint of the antenna wire) and 1/ sin(kL/2) is a normalisation factor. The antenna current forms a standing wave as indicated in figure 6.1 on page 79. When the antenna is short we can approximate the current distribution for′ mula (6.3) by the first term in its Taylor expansion, i.e., by I0 (1 − 2|x3 |/L). For a half-wave antenna (L = λ/2 ⇔ kL = π) formula (6.3) above simplifies to ′ I0 cos(kx3 ). Hence, in the most general case of a straight, infinitely thin antenna ′ of finite, arbitrary length L directed along the x3 axis, the Fourier amplitude of the
78
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from an extended source volume at rest
sin[k(L/2 − x′ )] 3
−L 2
j(t′ , x′ )
L 2
F IGURE 6 .1 : A linear antenna used for transmission. The current in the feeder and the antenna wire is set up by the EMF of the generator (the transmitter). At the ends of the wire, the current is reflected back with a 180◦ phase shift to produce a antenna current in the form of a standing wave.
antenna current density is
′ ′ j0 (x′ ) = I0 δ(x1 )δ(x2 ) ′ sin[k(L/2 − x3 )] x3 ˆ sin(kL/2)
(6.4)
For a halfwave dipole antenna (L = λ/2), the antenna current density is simply
′ ′ ′ j0 (x′ ) = I0 δ(x1 )δ(x2 ) cos(kx3 )
(6.5)
while for a short antenna (L ≪ λ) it can be approximated by
′ ′ ′ j0 (x′ ) = I0 δ(x1 )δ(x2 )(1 − 2 x3 /L)
(6.6)
In the case of a travelling wave antenna, in which one end of the antenna is connected to ground via a resistance so that the current at this end does not vanish, the Fourier amplitude of the antenna current density is
′ ′ ′ j0 (x′ ) = I0 δ(x1 )δ(x2 ) exp(kx3 )
(6.7)
In order to evaluate formula (5.31) on page 75 with the explicit monochromatic current (6.4) inserted, we use a spherical polar coordinate system as in figure 6.2
Downloaded from
Version released 1st July 2008 at 20:49.
79
6. Electromagnetic Radiation and Radiating Systems
r ˆ x3 = z x
L 2
ϕ ˆ
ˆ θ θ jω (x′ ) ˆ k x2
ϕ x1 −L 2
F IGURE 6 .2 : We choose a spherical polar coordinate system (r = |x| , θ, ϕ) and arrange it so that the linear electric dipole antenna axis (and thus the antenna current density jω ) is along the polar axis with the feed point at the origin.
to evaluate the source integral
2 V′
d3x′ j0 × k e−ik·(x −x0 )
L/2 ′ sin[k(L/2 dx3 I0 ′ − x3 )] ′ k sin θe−ikx3 cos θ eikx0 cos θ sin(kL/2) 2 L/2 2
′
=
−L/2 2 = I0
k2 sin2 θ eikx0 cos θ sin2 (kL/2)
2 ′ ′ ′ dx3 sin[k(L/2 − x3 )] cos(kx3 cos θ) 2
2
0
2 = 4I0
cos[(kL/2) cos θ] − cos(kL/2) sin θ sin(kL/2)
(6.8) Inserting this expression and dΩ = 2π sin θ dθ into formula (5.31) on page 75 and integrating over θ, we find that the total radiated power from the antenna is
2 P(L) = R0 I0
1 4π
π
dθ
0
cos[(kL/2) cos θ] − cos(kL/2) sin θ sin(kL/2)
2
sin θ
(6.9)
80
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from an extended source volume at rest
One can show that
kL→0
lim P(L) =
π 12
L λ
2 2 R0 I0
(6.10)
where λ is the vacuum wavelength. The quantity Rrad (L) = π P(L) P(L) = 1 2 = R0 2 6 Ieff 2 I0 L λ
2
≈ 197
L λ
2
Ω
(6.11)
is called the radiation resistance. For the technologically important case of a half-wave antenna, i.e., for L = λ/2 or kL = π, formula (6.9) on page 80 reduces to 1 π cos2 π cos θ 2 (6.12) dθ 4π 0 sin θ The integral in (6.12) can always be evaluated numerically. But, it can in fact also be evaluated analytically as follows:
2 P(λ/2) = R0 I0 π 0
cos2
1 cos2 π u cos θ 2 dθ = [cos θ → u] = du = 2 sin θ −1 1 − u π 1 + cos(πu) cos2 u = 2 2 1 1 + cos(πu) 1 du = 2 −1 (1 + u)(1 − u) 1 1 1 + cos(πu) 1 1 1 + cos(πu) = du + du 4 −1 (1 + u) 4 −1 (1 − u) v 1 1 1 + cos(πu) du = 1 + u → = 2 −1 (1 + u) π 1 1 2π 1 − cos v dv = [γ + ln 2π − Ci(2π)] = 2 0 v 2 ≈ 1.22 π 2
(6.13)
where in the last step the Euler-Mascheroni constant γ = 0.5772 . . . and the cosine integral Ci(x) were introduced. Inserting this into the expression equation (6.12) we obtain the value Rrad (λ/2) ≈ 73 Ω.
6.1.2 Radiation from a two-dimensional current distribution
As an example of a two-dimensional current distribution we consider a circular loop antenna and calculate the radiated fields from such an antenna. We choose
Downloaded from
Version released 1st July 2008 at 20:49.
81
6. Electromagnetic Radiation and Radiating Systems
r ˆ x3 = z = z ′ x ˆ θ θ ˆ k x2 z′ ˆ jω (x′ ) x1 ϕ′ ρ′ ˆ
F IGURE 6 .3 : For the loop antenna the spherical coordinate system (r, θ, ϕ) describes the field point x (the radiation field) and the cylindrical coordinate system (ρ′ , ϕ′ , z′ ) describes the source point x′ (the antenna current).
ϕ ˆ
x′
ϕ ϕ′ ˆ
the Cartesian coordinate system x1 x2 x3 with its origin at the centre of the loop as in figure 6.3 According to equation (5.28a) on page 74 the Fourier component of the radiation part of the magnetic field generated by an extended, monochromatic current source is Brad = ω −iµ0 eik|x| 4π |x| d3x′ e−ik·x jω × k
′
(6.14)
V′
In our case the generator produces a single frequency ω and we feed the antenna across a small gap where the loop crosses the positive x1 axis. The circumference of the loop is chosen to be exactly one wavelength λ = 2πc/ω. This means that the antenna current oscillates in the form of a sinusoidal standing current wave around the circular loop with a Fourier amplitude jω = I0 cos ϕ′ δ(ρ′ − a)δ(z′ )ϕ′ ˆ (6.15)
For the spherical coordinate system of the field point, we recall from subsec-
82
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from an extended source volume at rest
tion F.4.1 on page 178 that the following relations between the base vectors hold:
ϕ = − sin ϕ x1 + cos ϕ x2 ˆ ˆ ˆ and With the use of the above transformations and trigonometric identities, we obtain for the cylindrical coordinate system which describes the source: ρ′ = cos ϕ′ x1 + sin ϕ′ x2 ˆ ˆ ˆ ϕ′ = − sin ϕ′ x1 + cos ϕ′ x2 ˆ ˆ ˆ ˆ = sin θ cos(ϕ′ − ϕ)ˆ + cos θ cos(ϕ′ − ϕ)θ + sin(ϕ′ − ϕ)ϕ r ˆ (6.16) (6.17) (6.18)
ˆ = − sin θ sin(ϕ′ − ϕ)ˆ − cos θ sin(ϕ′ − ϕ)θ + cos(ϕ′ − ϕ)ϕ r ˆ ˆ z′ = x3 = cos θˆ − sin θθ ˆ ˆ r
This choice of coordinate systems means that k = kˆ and x′ = aρ′ so that r ˆ k · x′ = ka sin θ cos(ϕ′ − ϕ) and ˆ ϕ′ × k = k[cos(ϕ′ − ϕ)θ + cos θ sin(ϕ′ − ϕ)ϕ] ˆ ˆ (6.20) (6.19)
With these expressions inserted, recalling that in cylindrical coordinates d3x′ = ρ′ dρ′ dϕ′ dz′ , the source integral becomes d3x′ e−ik·x jω × k = a
0 2π
′ ˆ e−ika sin θ cos(ϕ −ϕ) cos(ϕ′ − ϕ) cos ϕ′ dϕ′ θ ′
2π
V′
ˆ dϕ′ e−ika sin θ cos(ϕ −ϕ) I0 cos ϕ′ ϕ′ × k (6.21)
′
= I0 ak
0
2π
+ I0 ak cos θ
0
e−ika sin θ cos(ϕ −ϕ) sin(ϕ′ − ϕ) cos ϕ′ dϕ′ ϕ ˆ
′
Utilising the periodicity of the integrands over the integration interval [0, 2π], introducing the auxiliary integration variable ϕ′′ = ϕ′ − ϕ, and utilising standard
Downloaded from
Version released 1st July 2008 at 20:49.
83
6. Electromagnetic Radiation and Radiating Systems
trigonometric identities, the first integral in the RHS of (6.21) can be rewritten
2π 0 2π
e−ika sin θ cos ϕ cos ϕ′′ cos(ϕ′′ + ϕ) dϕ′′ e−ika sin θ cos ϕ cos2 ϕ′′ dϕ′′ + a vanishing integral e−ika sin θ cos ϕ
′′ ′′
′′
= cos ϕ
0 2π
= cos ϕ
0
1 1 + cos 2ϕ′′ 2 2
dϕ′′
(6.22)
=
2π 1 ′′ cos ϕ e−ika sin θ cos ϕ dϕ′′ 2 0 2π 1 ′′ + cos ϕ e−ika sin θ cos ϕ cos(2ϕ′′ ) dϕ′′ 2 0
Analogously, the second integral in the RHS of (6.21) can be rewritten
2π 0
e−ika sin θ cos ϕ sin ϕ′′ cos(ϕ′′ + ϕ) dϕ′′
2π 1 ′′ sin ϕ e−ika sin θ cos ϕ dϕ′′ 2 0 2π 1 ′′ e−ika sin θ cos ϕ cos 2ϕ′′ dϕ′′ − sin ϕ 2 0
′′
=
(6.23)
As is well-known from the theory of Bessel functions, Jn (−ξ) = (−1)n Jn (ξ) Jn (−ξ) = i−n π
π 0
e−iξ cos ϕ cos nϕ dϕ =
i−n 2π
2π 0
e−iξ cos ϕ cos nϕ dϕ
(6.24)
which means that
2π 0 2π 0
e−ika sin θ cos ϕ dϕ′′ = 2πJ0 (ka sin θ) (6.25) e−ika sin θ cos ϕ cos 2ϕ′′ dϕ′′ = −2πJ2 (ka sin θ)
′′
′′
Putting everything together, we find that
V′
′ ˆ ϕˆ d3x′ e−ik·x jω × k = I θ + I ϕ θ
ˆ = I0 akπ cos ϕ [J0 (ka sin θ) − J2 (ka sin θ)] θ so that, in spherical coordinates where |x| = r, Brad (x) = ω −iµ0 eikr ˆ ϕˆ Iθ+I ϕ θ 4πr
(6.26)
+ I0 akπ cos θ sin ϕ [J0 (ka sin θ) + J2 (ka sin θ)] ϕ ˆ
(6.27)
84
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised source volume at rest
To obtain the desired physical magnetic field in the radiation (far) zone we must Fourier transform back to t space and take the real part and evaluate it at the retarded time: B (t, x) = Re =
rad
−iµ0 e(ikr−ωt ) ˆ ϕˆ Iθ+I ϕ θ 4πr
′
µ0 ˆ ϕˆ sin(kr − ωt′ ) I θ + I ϕ θ 4πr I0 akµ0 ˆ = sin(kr − ωt′ ) cos ϕ [J0 (ka sin θ) − J2 (ka sin θ)] θ 4r + cos θ sin ϕ [J0 (ka sin θ) + J2 (ka sin θ)] ϕ ˆ (6.28) From this expression for the radiated B field, we can obtain the radiated E field with the help of Maxwell’s equations.
6.2 Radiation from a localised source volume at rest
In the general case, and when we are interested in evaluating the radiation far from a source at rest and which is localised in a small volume, we can introduce an approximation which leads to a multipole expansion where individual terms can be evaluated analytically. We shall use the Hertz method to obtain this expansion.
6.2.1 The Hertz potential
In section 4.1.1 we introduced the electric polarisation P(t, x) such that the polarisation charge density ρpol = −∇ · P. If we adopt the same idea for the ‘true’ charge density and introduce a vector field π(t, x) such that ρtrue = −∇ · π which means that the associated ‘polarisation current’ becomes ∂π = jtrue (6.29b) ∂t As a consequence, the equation of continuity for ‘true’ charges and currents [cf. expression (1.23) on page 10] is satisfied: ∂ρtrue (t, x) ∂ ∂π + ∇ · jtrue (t, x) = − ∇ · π + ∇ · =0 ∂t ∂t ∂t (6.30) (6.29a)
Downloaded from
Version released 1st July 2008 at 20:49.
85
6. Electromagnetic Radiation and Radiating Systems
Furthermore, if we compare with the electric polarisation [cf. equation (4.9) on page 55], we see that the quantity π is indeed related to the ‘true’ charges in the same way as P is related to polarised charge, namely as a dipole moment density. The quantity π is referred to as the polarisation vector since, formally, it treats also the ‘true’ (free) charges as polarisation charges so that ∇·E= ρtrue + ρpol −∇ · π − ∇ · P = ε0 ε0 (6.31)
We introduce a further potential Πe with the following property ∇ · Πe = −φ 1 ∂Πe =A c2 ∂t (6.32a) (6.32b)
where φ and A are the electromagnetic scalar and vector potentials, respectively. As we see, Πe acts as a ‘super-potential’ in the sense that it is a potential from which we can obtain other potentials. It is called the Hertz vector or polarisation potential. Requiring that the scalar and vector potentials φ and A, respectively, fulfil their inhomogeneous wave equations, equations (3.14) on page 43, one finds, using (6.29) and (6.32), that the Hertz vector must satisfy the inhomogeneous wave equation
2
Πe =
π 1 ∂2 e Π − ∇2 Πe = c2 ∂t2 ε0
(6.33)
This equation is of the same type as equation (3.17) on page 44, and has therefore the retarded solution Πe (t, x) = 1 4πε0
V′
d3x′
′ π(tret , x′ ) |x − x′ |
′
(6.34)
with Fourier components Πe (x) ω 1 = 4πε0 πω (x′ )eik|x−x | dx |x − x′ | V′
3 ′
(6.35)
If we introduce the help vector C such that C = ∇ × Πe (6.36)
we see that we can calculate the magnetic and electric fields, respectively, as follows B= 1 ∂C c2 ∂t (6.37a) (6.37b)
E=∇×C
86
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised source volume at rest
x − x′ x − x0 x x′ Θ x0 V′ O
F IGURE 6 .4 : Geometry of a typical multipole radiation problem where the field point x is located some distance away from the finite source volume V ′ centred around x0 . If k |x′ − x0 | ≪ 1 ≪ k |x − x0 |, then the radiation at x is well approximated by a few terms in the multipole expansion.
x′ − x0
Clearly, the last equation is valid only outside the source volume, where ∇ · E = 0. Since we are mainly interested in the fields in the far zone, a long distance from the source region, this is no essential limitation. Assume that the source region is a limited volume around some central point x0 far away from the field (observation) point x illustrated in figure 6.4. Under these assumptions, we can expand the Hertz vector, expression (6.35) on page 86, ′ due to the presence of non-vanishing π(tret , x′ ) in the vicinity of x0 , in a formal series. For this purpose we recall from potential theory that eik|x−x | eik|(x−x0 )−(x −x0 )| ≡ ′| |x − x |(x − x0 ) − (x′ − x0 )|
∞ n=0
′ ′
= ik ∑ (2n + 1)Pn (cos Θ) jn (k x′ − x0 )h(1) (k |x − x0 |) n
(6.38)
where (see figure 6.4) eik|x−x | is a Green function or propagator |x − x′ | Θ is the angle between x′ − x0 and x − x0
′
Pn (cos Θ) is the Legendre polynomial of order n jn (k x′ − x0 ) is the spherical Bessel function of the first kind of order n
h(1) (k |x − x0 |) is the spherical Hankel function of the first kind of order n n According to the addition theorem for Legendre polynomials Pn (cos Θ) =
m=−n
∑ (−1)m Pm (cos θ)P−m (cos θ′ )eim(ϕ−ϕ ) n n
′
n
(6.39)
Downloaded from
Version released 1st July 2008 at 20:49.
87
6. Electromagnetic Radiation and Radiating Systems
where Pm is an associated Legendre polynomial of the first kind, related to the n m spherical harmonic Yn as
m Yn (θ, ϕ) =
2n + 1 (n − m)! m P (cos θ) eimϕ 4π (n + m)! n
and, in spherical polar coordinates, x′ − x0 = ( x′ − x0 , θ′ , ϕ′ ) x − x0 = (|x − x0 | , θ, ϕ) (6.40a) (6.40b)
Inserting equation (6.38) on page 87, together with formula (6.39) on page 87, into equation (6.35) on page 86, we can in a formally exact way expand the Fourier component of the Hertz vector as Πe = ω ik 4πε0 ×
V′
n=0 m=−n 3 ′
∑ ∑ (2n + 1)(−1)m h(1) (k |x − x0 |) Pm (cos θ) eimϕ n n
′ ′
′ x0 ) P−m (cos θ′ ) e−imϕ n
∞
n
(6.41)
d x πω (x ) jn (k x −
We notice that there is no dependence on x − x0 inside the integral; the integrand is only dependent on the relative source vector x′ − x0 . We are interested in the case where the field point is many wavelengths away from the well-localised sources, i.e., when the following inequalities k x′ − x0 ≪ 1 ≪ k |x − x0 | (6.42)
hold. Then we may to a good approximation replace h(1) with the first term in its n asymptotic expansion: h(1) (k |x − x0 |) ≈ (−i)n+1 n eik|x−x0 | k |x − x0 | (6.43)
and replace jn with the first term in its power series expansion: jn (k x′ − x0 ) ≈ 2n n! k x′ − x0 (2n + 1)!
n
(6.44)
Inserting these expansions into equation (6.41), we obtain the multipole expansion of the Fourier component of the Hertz vector Πe ≈ ω
n=0
∞
(6.45a)
88
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised source volume at rest
ˆ k x3 x Brad Erad
θ p r ˆ x2
ϕ x1
F IGURE 6 .5 : If a spherical polar coordinate system (r, θ, ϕ) is chosen such that the electric dipole moment p (and thus its Fourier transform pω ) is located at the origin and directed along the polar axis, the calculations are simplified.
where Πe (n) = (−i)n ω 1 eik|x−x0 | 2n n! 4πε0 |x − x0 | (2n)! d3x′ πω (x′ ) (k x′ − x0 )n Pn (cos Θ) (6.45b)
V′
This expression is approximately correct only if certain care is exercised; if many Πe (n) terms are needed for an accurate result, the expansions of the spherical Hanω kel and Bessel functions used above may not be consistent and must be replaced by more accurate expressions. Furthermore, asymptotic expansions as the one used in equation (6.43) on page 88 are not unique. Taking the inverse Fourier transform of Πe will yield the Hertz vector in time ω domain, which inserted into equation (6.36) on page 86 will yield C. The resulting expression can then in turn be inserted into equations (6.37) on page 86 in order to obtain the radiation fields. For a linear source distribution along the polar axis, Θ = θ in expression (6.45b) above, and Pn (cos θ) gives the angular distribution of the radiation. In the general case, however, the angular distribution must be computed with the help of formula (6.39) on page 87. Let us now study the lowest order contributions to the expansion of the Hertz vector.
Downloaded from
Version released 1st July 2008 at 20:49.
89
6. Electromagnetic Radiation and Radiating Systems
6.2.2 Electric dipole radiation
Choosing n = 0 in expression (6.45b) on page 89, we obtain Πe (0) = ω eik|x−x0 | 4πε0 |x − x0 | d3x′ πω (x′ ) = 1 eik|x−x0 | pω 4πε0 |x − x0 | (6.46)
V′
Since π represents a dipole moment density for the ‘true’ charges (in the same vein as P does so for the polarised charges), pω = V ′ d3x′ πω (x′ ) is, by definition, the Fourier component of the electric dipole moment p(t, x0 ) = d3x′ π(t′ , x′ ) = d3x′ (x′ − x0 )ρ(t′ , x′ ) (6.47)
V′
V′
[cf. equation (4.2) on page 54 which describes the static dipole moment]. If a spherical coordinate system is chosen with its polar axis along pω as in figure 6.5 on page 89, the components of Πe (0) are ω 1 eik|x−x0 | pω cos θ 4πε0 |x − x0 | def 1 eik|x−x0 | ˆ pω sin θ Πe ≡ Πe (0) · θ = − θ ω 4πε0 |x − x0 | Πe ≡ Πe (0) · r = ˆ r ω
def def
(6.48a) (6.48b) (6.48c)
ˆ Πe ≡ Πe (0) · ϕ = 0 ω ϕ
Evaluating formula (6.36) on page 86 for the help vector C, with the spherically polar components (6.48) of Πe (0) inserted, we obtain ω
(0) Cω = Cω,ϕ ϕ = ˆ
1 4πε0
1 − ik |x − x0 |
eik|x−x0 | pω sin θ ϕ ˆ |x − x0 |
(6.49)
Applying this to equations (6.37) on page 86, we obtain directly the Fourier components of the fields eik|x−x0 | 1 ωµ0 − ik pω sin θ ϕ ˆ 4π |x − x0 | |x − x0 | 1 x − x0 ik 1 Eω = 2 2 − |x − x | cos θ |x − x | 4πε0 |x − x0 | 0 0 ik|x−x0 | ik 1 ˆ e − + − k2 sin θ θ pω |x − x0 | |x − x0 |2 |x − x0 | Bω = −i (6.50a)
(6.50b)
Keeping only those parts of the fields which dominate at large distances (the radiation fields) and recalling that the wave vector k = k(x − x0 )/ |x − x0 | where
90
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised source volume at rest
k = ω/c, we can now write down the Fourier components of the radiation parts of the magnetic and electric fields from the dipole: Brad = − ω Erad ω ωµ0 eik|x−x0 | ωµ0 eik|x−x0 | pω k sin θ ϕ = − ˆ (pω × k) (6.51a) 4π |x − x0 | 4π |x − x0 | 1 eik|x−x0 | 1 eik|x−x0 | ˆ pω k2 sin θ θ = − [(pω × k) × k] (6.51b) =− 4πε0 |x − x0 | 4πε0 |x − x0 |
These fields constitute the electric dipole radiation, also known as E1 radiation.
6.2.3 Magnetic dipole radiation
The next term in the expression (6.45b) on page 89 for the expansion of the Fourier transform of the Hertz vector is for n = 1: Πe (1) = −i ω eik|x−x0 | d3x′ k x′ − x0 πω (x′ ) cos Θ 4πε0 |x − x0 | V ′ 1 eik|x−x0 | = −ik d3x′ [(x − x0 ) · (x′ − x0 )] πω (x′ ) 4πε0 |x − x0 |2 V ′
(6.52)
Here, the term [(x − x0 ) · (x′ − x0 )] πω (x′ ) can be rewritten and introducing η′ i ηi = xi − x0,i = xi′
[(x − x0 ) · (x′ − x0 )] πω (x′ ) = (xi − x0,i )(xi′ − x0,i ) πω (x′ )
(6.53)
(6.54a) (6.54b)
− x0,i 1 ηi πω, j η′ + πω,i η′j i 2 1 + ηi πω, j η′ − πω,i η′j i 2
the jth component of the integrand in Πe (1) can be broken up into ω {[(x − x0 ) · (x′ − x0 )] πω (x′ )} j =
(6.55)
i.e., as the sum of two parts, the first being symmetric and the second antisymmetric in the indices i, j. We note that the antisymmetric part can be written as 1 1 ηi πω, j η′ − πω,i η′j = [πω, j (ηi η′ ) − η′j (ηi πω,i )] i i 2 2 1 = [πω (η · η′ ) − η′ (η · πω )] j 2 1 = (x − x0 ) × [πω × (x′ − x0 )] 2
(6.56)
j
Downloaded from
Version released 1st July 2008 at 20:49.
91
6. Electromagnetic Radiation and Radiating Systems
The utilisation of equations (6.29) on page 85, and the fact that we are considering a single Fourier component, π(t, x) = πω e−iωt allow us to express πω in jω as πω = i jω ω (6.58) (6.57)
Hence, we can write the antisymmetric part of the integral in formula (6.52) on page 91 as 1 (x − x0 ) × d3x′ πω (x′ ) × (x′ − x0 ) 2 V′ 1 = i (x − x0 ) × d3x′ jω (x′ ) × (x′ − x0 ) 2ω V′ 1 = −i (x − x0 ) × mω ω where we introduced the Fourier transform of the magnetic dipole moment mω = 1 2 d3x′ (x′ − x0 ) × jω (x′ ) (6.60)
(6.59)
V′
The final result is that the antisymmetric, magnetic dipole, part of Πe (1) can be ω written Πe,antisym ω
(1)
=−
eik|x−x0 | k (x − x0 ) × mω 4πε0 ω |x − x0 |2
(6.61)
In analogy with the electric dipole case, we insert this expression into equation (6.36) on page 86 to evaluate C, with which equations (6.37) on page 86 then gives the B and E fields. Discarding, as before, all terms belonging to the near fields and transition fields and keeping only the terms that dominate at large distances, we obtain µ0 eik|x−x0 | (mω × k) × k 4π |x − x0 | k eik|x−x0 | mω × k Erad (x) = ω 4πε0 c |x − x0 | Brad (x) = − ω which are the fields of the magnetic dipole radiation (M1 radiation). (6.62a) (6.62b)
92
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
6.2.4 Electric quadrupole radiation
The symmetric part Πe,sym (1) of the n = 1 contribution in the equation (6.45b) on ω page 89 for the expansion of the Hertz vector can be expressed in terms of the electric quadrupole tensor, which is defined in accordance with equation (4.3) on page 54:
Q(t, x0 ) =
′ d3x′ (x′ − x0 )(x′ − x0 )ρ(tret , x′ )
(6.63)
V′
Again we use this expression in equation (6.36) on page 86 to calculate the fields via equations (6.37) on page 86. Tedious, but fairly straightforward algebra (which we will not present here), yields the resulting fields. The radiation components of the fields in the far field zone (wave zone) are given by iµ0 ω eik|x−x0 | (k · Qω ) × k 8π |x − x0 | i eik|x−x0 | Erad (x) = [(k · Qω ) × k] × k ω 8πε0 |x − x0 | Brad (x) = ω (6.64a) (6.64b)
This type of radiation is called electric quadrupole radiation or E2 radiation.
6.3 Radiation from a localised charge in arbitrary motion
The derivation of the radiation fields for the case of the source moving relative to the observer is considerably more complicated than the stationary cases studied above. In order to handle this non-stationary situation, we use the retarded potentials (3.34) on page 46 in chapter 3 φ(t, x) = A(t, x) = 1 4πε0 µ0 4π
V′
V′
d3x′
d3x′
′ ′ j tret , x(tret ) ′ x(t) − x′ (tret )
′ ′ ρ tret , x′ (tret ) ′ x(t) − x′ (tret )
(6.65a) (6.65b)
and consider a source region with such a limited spatial extent that the charges and currents are well localised. Specifically, we consider a charge q′ , for instance an electron, which, classically, can be thought of as a localised, unstructured and rigid ‘charge distribution’ with a small, finite radius. The part of this ‘charge distribution’ dq′ which we are considering is located in dV ′ = d3x′ in the sphere in
Downloaded from
Version released 1st July 2008 at 20:49.
93
6. Electromagnetic Radiation and Radiating Systems
x(t) x − x′
v′ (t′ ) dS′ x (t )
′ ′
dr′ dV ′
dq′ c
F IGURE 6 .6 : Signals that are observed at the field point x at time t were generated at source points x′ (t′ ) on a sphere, centred on x and expanding, as time increases, with the velocity c outward from the centre. The source charge element moves with an arbitrary velocity v′ and gives rise to a source ‘leakage’ out of the source volume dV ′ = d3x′ .
figure 6.6. Since we assume that the electron (or any other other similar electric charge) moves with a velocity v′ whose direction is arbitrary and whose magnitude can even be comparable to the speed of light, we cannot say that the charge ′ ′ and current to be used in (6.65) is V ′ d3x′ ρ(tret , x′ ) and V ′ d3x′ vρ(tret , x′ ), respectively, because in the finite time interval during which the observed signal is generated, part of the charge distribution will ‘leak’ out of the volume element d3x′ .
6.3.1 The Liénard-Wiechert potentials
The charge distribution in figure 6.6 on page 94 which contributes to the field at x(t) is located at x′ (t′ ) on a sphere with radius r = |x − x′ | = c(t − t′ ). The radius interval of this sphere from which radiation is received at the field point x during the time interval (t′ , t′ + dt′ ) is (r′ , r′ + dr′ ) and the net amount of charge in this radial interval is
′ ′ dq′ = ρ(tret , x′ ) dS ′ dr′ − ρ(tret , x′ )
(x − x′ ) · v′ (t′ ) ′ ′ dS dt |x − x′ |
(6.66)
94
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
where the last term represents the amount of ‘source leakage’ due to the fact that the charge distribution moves with velocity v′ (t′ ) = dx′ /dt′ . Since dt′ = dr′ /c and dS ′ dr′ = d3x′ we can rewrite the expression for the net charge as
′ ′ dq′ = ρ(tret , x′ ) d3x′ − ρ(tret , x′ )
or
(x − x′ ) · v′ 3 ′ dx c |x − x′ | (x − x′ ) · v′ ′ d3x′ = ρ(tret , x′ ) 1 − c |x − x′ | dq′ 1−
(x−x′ )·v′ c|x−x′ |
(6.67)
′ ρ(tret , x′ ) d3x′ =
(6.68)
which leads to the expression
′ dq′ ρ(tret , x′ ) 3 ′ dx = ′ ′ ′| |x − x |x − x′ | − (x−x )·v c
(6.69)
This is the expression to be used in the formulae (6.65) on page 93 for the retarded potentials. The result is (recall that j = ρv) φ(t, x) = A(t, x) = 1 4πε0 µ0 4π dq′ ′ ′ |x − x′ | − (x−x )·v c v′ dq′ ′ ′ |x − x′ | − (x−x )·v c (6.70a) (6.70b)
For a sufficiently small and well localised charge distribution we can, assuming that the integrands do not change sign in the integration volume, use the mean value theorem to evaluate these expressions to become q′ 1 1 1 d3x′ dq′ = (6.71a) (x−x′ )·v′ 4πε0 |x − x′ | − c 4πε0 s V′ 1 q′ v′ v′ v′ A(t, x) = d3x′ dq′ = = 2 φ(t, x) ′ )·v′ 4πε0 c2 |x − x′ | − (x−x 4πε0 c2 s c V′ c (6.71b) φ(t, x) = where s = s(t′ , x) = x − x′ (t′ ) − [x − x′ (t′ )] · v′ (t′ ) c x − x′ (t′ ) v′ (t′ ) = x − x′ (t′ ) 1 − · c |x − x′ (t′ )| x − x′ (t′ ) v′ (t′ ) = [x − x′ (t′ )] · − c |x − x′ (t′ )| (6.72a) (6.72b) (6.72c)
Downloaded from
Version released 1st July 2008 at 20:49.
95
6. Electromagnetic Radiation and Radiating Systems
? |x − x′ | ′ v c θ′
q′ x′ (t′ )
x0 (t) θ0
v′ (t′ )
x − x′
x − x0 x(t)
F IGURE 6 .7 : Signals which are observed at the field point x at time t were generated at the source point x′ (t′ ). After time t′ the particle, which moves with nonuniform velocity, has followed a yet unknown trajectory. Extrapolating tangentially the trajectory from x′ (t′ ), based on the velocity v′ (t′ ), defines the virtual simultaneous coordinate x0 (t).
is the retarded relative distance. The potentials (6.71) are the Liénard-Wiechert potentials. In section 7.3.2 on page 146 we shall derive them in a more elegant and general way by using a relativistically covariant formalism. It should be noted that in the complicated derivation presented above, the observer is in a coordinate system which has an ‘absolute’ meaning and the velocity v′ is that of the localised charge q′ , whereas, as we shall see later in the covariant derivation, two reference frames of equal standing are moving relative to each other with v′ . The Liénard-Wiechert potentials are applicable to all problems where a spatially localised charge in arbitrary motion emits electromagnetic radiation, and we shall now study such emission problems. The electric and magnetic fields are calculated from the potentials in the usual way:
B(t, x) = ∇ × A(t, x) E(t, x) = −∇φ(t, x) − ∂A(t, x) ∂t
(6.73a) (6.73b)
96
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
6.3.2 Radiation from an accelerated point charge
Consider a localised charge q′ and assume that its trajectory is known experimentally as a function of retarded time x′ = x′ (t′ ) (6.74)
(in the interest of simplifying our notation, we drop the subscript ‘ret’ on t′ from now on). This means that we know the trajectory of the charge q′ , i.e., x′ , for all times up to the time t′ at which a signal was emitted in order to precisely arrive at the field point x at time t. Because of the finite speed of propagation of the fields, the trajectory at times later than t′ cannot be known at time t. The retarded velocity and acceleration at time t′ are given by v′ (t′ ) = dx′ dt′ (6.75a) dv′ d2 x′ = ′2 dt′ dt (6.75b)
˙ a′ (t′ ) = v′ (t′ ) =
As for the charge coordinate x′ itself, we have in general no knowledge of the velocity and acceleration at times later than t′ , and definitely not at the time of observation t! If we choose the field point x as fixed, the application of (6.75) to the relative vector x − x′ yields d [x − x′ (t′ )] = −v′ (t′ ) dt′ d2 [x − x′ (t′ )] = −˙ ′ (t′ ) v dt′ 2 (6.76a) (6.76b)
The retarded time t′ can, at least in principle, be calculated from the implicit relation t′ = t′ (t, x) = t − |x − x′ (t′ )| c (6.77)
and we shall see later how this relation can be taken into account in the calculations. According to formulae (6.73) on page 96, the electric and magnetic fields are determined via differentiation of the retarded potentials at the observation time t and at the observation point x. In these formulae the unprimed ∇, i.e., the spatial derivative differentiation operator ∇ = xi ∂/∂xi means that we differentiate with ˆ respect to the coordinates x = (x1 , x2 , x3 ) while keeping t fixed, and the unprimed time derivative operator ∂/∂t means that we differentiate with respect to t while keeping x fixed. But the Liénard-Wiechert potentials φ and A, equations (6.71) on page 95, are expressed in the charge velocity v′ (t′ ) given by equation (6.75a)
Downloaded from
Version released 1st July 2008 at 20:49.
97
6. Electromagnetic Radiation and Radiating Systems
on page 97 and the retarded relative distance s(t′ , x) given by equation (6.72) on page 95. This means that the expressions for the potentials φ and A contain terms which are expressed explicitly in t′ , which in turn is expressed implicitly in t via equation (6.77) on page 97. Despite this complication it is possible, as we shall see below, to determine the electric and magnetic fields and associated quantities at the time of observation t. To this end, we need to investigate carefully the action of differentiation on the potentials.
The differential operator method
We introduce the convention that a differential operator embraced by parentheses with an index x or t means that the operator in question is applied at constant x and t, respectively. With this convention, we find that ∂ ∂t′ x − x′ (t′ ) = x − x′ · |x − x′ | ∂ ∂t′ x − x′ (t′ ) = − (x − x′ ) · v′ (t′ ) |x − x′ | (6.78)
x
x
This is an algebraic equation in (∂t′ /∂t)x which we can solve to obtain ∂t′ ∂t =
x
Furthermore, by applying the operator (∂/∂t)x to equation (6.77) on page 97 we find that ∂ ∂t′ |x − x′ (t′ (t, x))| =1− ∂t x ∂t x c ∂ ∂t′ |x − x′ | =1− (6.79) ∂t′ x c ∂t x (x − x′ ) · v′ (t′ ) ∂t′ =1+ c |x − x′ | ∂t x |x − x′ | |x − x′ | = ′ ) · v′ (t′ )/c − (x − x s (6.80)
where s = s(t′ , x) is the retarded relative distance given by equation (6.72) on page 95. Making use of equation (6.80) above, we obtain the following useful operator identity ∂ ∂t =
x
|x −
x′ |
∂t′ ∂t
x
∂ ∂t′
=
x
|x − x′ | s
∂ ∂t′
(6.81)
x
Likewise, by applying (∇)t to equation (6.77) on page 97 we obtain (∇)t t′ = −(∇)t x − x′ |x − x′ (t′ (t, x))| · (∇)t (x − x′ ) =− c c |x − x′ | (x − x′ ) · v′ (t′ ) x − x′ + (∇)t t′ =− ′| c |x − x c |x − x′ |
(6.82)
98
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
This is an algebraic equation in (∇)t t′ with the solution (∇)t t′ = − x − x′ cs (6.83)
which gives the following operator relation when (∇)t is acting on an arbitrary function of t′ and x: (∇)t = (∇)t t′ ∂ ∂t′
x
+ (∇)t′ = −
x − x′ cs
∂ ∂t′
+ (∇)t′
x
(6.84)
With the help of the rules (6.84) and (6.81) we are now able to replace t by t′ in the operations which we need to perform. We find, for instance, that 1 q′ 4πε0 s ′ v′ (t′ ) x − x′ ∂s q x − x′ − =− − 4πε0 s2 |x − x′ | c cs ∂t′ ∂ µ0 q′ v′ (t′ ) ∂A ∂A ≡ = ∂t ∂t x ∂t 4π s x ′ q x − x′ s˙ ′ (t′ ) − x − x′ v′ (t′ ) v = 4πε0 c2 s3 ∇φ ≡ (∇φ)t = ∇
(6.85a)
x
∂s ∂t′
(6.85b)
x
Utilising these relations in the calculation of the E field from the Liénard-Wiechert potentials, equations (6.71) on page 95, we obtain E(t, x) = −∇φ(t, x) − ∂ A(t, x) ∂t q′ [x − x′ (t′ )] − |x − x′ (t′ )| v′ (t′ )/c = 4πε0 s2 (t′ , x) |x − x′ (t′ )| − [x − x′ (t′ )] − |x − x′ (t′ )| v′ (t′ )/c cs(t′ , x) ∂s(t′ , x) ∂t′
x
−
˙ |x − x′ (t′ )| v′ (t′ ) 2 c (6.86)
Starting from expression (6.72a) on page 95 for the retarded relative distance s(t′ , x), we see that we can evaluate (∂s/∂t′ )x in the following way ∂s ∂t′ ∂ (x − x′ ) · v′ (t′ ) x − x′ − ∂t′ x c 1 ∂[x − x′ (t′ )] ′ ′ ∂v′ (t′ ) ∂ · v (t ) + [x − x′ (t′ )] · = ′ x − x′ (t′ ) − ′ ∂t c ∂t ∂t′ ˙ (x − x′ (t′ )) · v′ (t′ ) v′2 (t′ ) (x − x′ (t′ )) · v′ (t′ ) − =− + ′ (t′ )| c c |x − x (6.87) =
x
Downloaded from
Version released 1st July 2008 at 20:49.
99
6. Electromagnetic Radiation and Radiating Systems
where equation (6.78) on page 98 and equations (6.75) on page 97, respectively, were used. Hence, the electric field generated by an arbitrarily moving charged particle at x′ (t′ ) is given by the expression E(t, x) = q′ 4πε0 s3 (t′ , x) [x − x′ (t′ )] − |x − x′ (t′ )| v′ (t′ ) c 1− v′2 (t′ ) c2
q′ x − x′ (t′ ) + × 4πε0 s3 (t′ , x) c2
Coulomb field when v → 0
[x − x′ (t′ )] −
|x − x′ (t′ )| v′ (t′ ) c
˙ × v′ (t′ )
Radiation (acceleration) field
(6.88) The first part of the field, the velocity field, tends to the ordinary Coulomb field when v′ → 0 and does not contribute to the radiation. The second part of the field, the acceleration field, is radiated into the far zone and is therefore also called the radiation field. From figure 6.7 on page 96 we see that the position the charged particle would have had if at t′ all external forces would have been switched off so that the trajectory from then on would have been a straight line in the direction of the tangent at x′ (t′ ) is x0 (t), the virtual simultaneous coordinate. During the arbitrary motion, we interpret x − x0 (t) as the coordinate of the field point x relative to the virtual simultaneous coordinate x0 (t). Since the time it takes for a signal to propagate (in the assumed vacuum) from x′ (t′ ) to x is |x − x′ | /c, this relative vector is given by x − x0 (t) = x − x′ (t′ ) − |x − x′ (t′ )| v′ (t′ ) c (6.89)
This allows us to rewrite equation (6.88) in the following way E(t, x) = q′ 4πε0 s3 x − x0 (t)
′ ′
1−
v′2 (t′ ) c2
˙ x − x0 (t) × v′ (t′ ) + x − x (t ) × 2 c In a similar manner we can compute the magnetic field: B(t, x) = ∇ × A(t, x) ≡ (∇)t × A = (∇)t′ × A − x − x′ × cs x − x′ x − x′ ∂A q′ × v′ − × =− 2 s2 |x − x′ | ′| 4πε0 c c |x − x ∂t x ∂ ∂t′ A
x
(6.90)
(6.91)
100
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
where we made use of equation (6.71) on page 95 and formula (6.81) on page 98. But, according to (6.85a), x − x′ q′ x − x′ × v′ × (∇)t φ = c |x − x′ | 4πε0 c2 s2 |x − x′ | so that B(t, x) = x − x′ × −(∇φ)t − c |x − x′ | x − x′ (t′ ) = × E(t, x) c |x − x′ (t′ )| ∂A ∂t (6.92)
x
(6.93)
The radiation part of the electric field is obtained from the acceleration field in formula (6.88) on page 100 as Erad (t, x) = =
|x−x′ |→∞ ′
lim E(t, x) ˙ × v′ (6.94)
q |x − x′ | v′ (x − x′ ) × (x − x′ ) − 2 s3 4πε0 c c ′ q ˙ = [x − x′ (t′ )] × {[x − x0 (t)] × v′ (t′ )} 4πε0 c2 s3
where in the last step we again used formula (6.89) on page 100. Using this formula and formula (6.93) above, the radiation part of the magnetic field can be written Brad (t, x) = x − x′ (t′ ) × Erad (t, x) c |x − x′ (t′ )| (6.95)
The direct method
An alternative to the differential operator transformation technique just described is to try to express all quantities in the potentials directly in t and x. An example of such a quantity is the retarded relative distance s(t′ , x). According to equation (6.72) on page 95, the square of this retarded relative distance can be written s2 (t′ , x) = x − x′ (t′ ) − 2 x − x′ (t′ ) + [x − x′ (t′ )] · v′ (t′ ) c
2 2
[x − x′ (t′ )] · v′ (t′ ) c
(6.96)
Downloaded from
Version released 1st July 2008 at 20:49.
101
6. Electromagnetic Radiation and Radiating Systems
If we use the following handy identity (x − x′ ) · v′ c =
2
+
(x − x′ ) × v′ c
2
|x − x′ |2 v′2 2 ′ |x − x′ |2 v′2 cos2 θ′ + sin θ c2 c2 |x − x′ |2 v′2 |x − x′ |2 v′2 = (cos2 θ′ + sin2 θ′ ) = c2 c2 we find that (x − x′ ) · v′ c
2
(6.97)
|x − x′ |2 v′2 = − c2
(x − x′ ) × v′ c
2
(6.98)
Furthermore, from equation (6.89) on page 100, we obtain the identity [x − x′ (t′ )] × v′ = [x − x0 (t)] × v′ which, when inserted into equation (6.98), yields the relation (x − x′ ) · v′ c
2
(6.99)
=
|x − x′ |2 v′2 − c2
(x − x0 ) × v′ c
2
(6.100)
Inserting the above into expression (6.96) on page 101 for s2 , this expression becomes s2 = x − x′ =
2
− 2 x − x′ |x − x′ | v′ c
(x − x′ ) · v′ |x − x′ |2 v′2 + − c c2
2
(x − x0 ) × v′ c
2
(x − x′ ) −
−
2
(x − x0 ) × v′ c
2
= (x − x0 )2 − ≡ |x − x0 (t)|2 −
(x − x0 ) × v′ c
[x − x0 (t)] × v′ (t′ ) c
2
(6.101) where in the penultimate step we used equation (6.89) on page 100. What we have just demonstrated is that if the particle velocity at time t can be calculated or projected from its value at the retarded time t′ , the retarded distance s in the Liénard-Wiechert potentials (6.71) can be expressed in terms of the virtual simultaneous coordinate x0 (t), viz., the point at which the particle will have arrived at time t, i.e., when we obtain the first knowledge of its existence at the source
102
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
point x′ at the retarded time t′ , and in the field coordinate x = x(t), where we make our observations. We have, in other words, shown that all quantities in the definition of s, and hence s itself, can, when the motion of the charge is somehow known, be expressed in terms of the time t alone. I.e., in this special case we are able to express the retarded relative distance as s = s(t, x) and we do not have to involve the retarded time t′ or any transformed differential operators in our calculations. Taking the square root of both sides of equation (6.101) on page 102, we obtain the following alternative final expressions for the retarded relative distance s in terms of the charge’s virtual simultaneous coordinate x0 (t) and velocity v′ (t′ ): s(t′ , x) = |x − x0 (t)|2 − 1− [x − x0 (t)] × v′ (t′ ) c v′2 (t′ ) 2 sin θ0 (t) c2 v′2 (t′ ) c2 + [x − x0 (t)] · v′ (t′ ) c
2 2
(6.102a) (6.102b) (6.102c)
= |x − x0 (t)| =
|x − x0 (t)|2 1 −
If we know what velocity the particle will have at time t, expression (6.102) for s will not be dependent on t′ . Using equation (6.102c) above and standard vector analytic formulae, we obtain ∇s2 = ∇ |x − x0 |2 1 − = 2 (x − x0 ) 1 − = 2 (x − x0 ) + v′2 c2 + + (x − x0 ) · v′ c
2
v′2 c2
v′ v′ · (x − x0 ) c2
(6.103)
v′ × c
v′ × (x − x0 ) c
which we shall use in example 6.2 on page 126 for a uniform, unaccelerated motion of the charge.
Radiation for small velocities
If the charge moves at such low speeds that v′ /c ≪ 1, formula (6.72) on page 95 simplifies to s = x − x′ − (x − x′ ) · v′ ≈ x − x′ , c v′ ≪ c (6.104)
Downloaded from
Version released 1st July 2008 at 20:49.
103
6. Electromagnetic Radiation and Radiating Systems
and formula (6.89) on page 100 x − x0 = (x − x′ ) − |x − x′ | v′ ≈ x − x′ , c v′ ≪ c (6.105)
so that the radiation field equation (6.94) on page 101 can be approximated by Erad (t, x) = q′ ˙ (x − x′ ) × [(x − x′ ) × v′ ], 2 |x − x′ |3 4πε0 c v′ ≪ c (6.106)
from which we obtain, with the use of formula (6.93) on page 101, the magnetic field Brad (t, x) = q′ [˙ ′ × (x − x′ )], v 4πε0 c3 |x − x′ |2 v′ ≪ c (6.107)
It is interesting to note the close correspondence which exists between the nonrelativistic fields (6.106) and (6.107) and the electric dipole field equations (6.51) on page 91 if we introduce p = q′ x′ (t′ ) and at the same time make the transitions ˙ ¨ q′ v′ = p → −ω2 pω
′
(6.108)
(6.109a) (6.109b)
x − x = x − x0
The power flux in the far zone is described by the Poynting vector as a function of Erad and Brad . We use the close correspondence with the dipole case to find that it becomes S= µ0 q′ 2 (˙ ′ )2 v x − x′ sin2 θ 2 c |x − x′ |2 |x − x′ | 16π (6.110)
˙ where θ is the angle between v′ and x − x0 . The total radiated power (integrated over a closed spherical surface) becomes P= µ0 q′ 2 (˙ ′ )2 v q′ 2 v′2 ˙ = 6πc 6πε0 c3 (6.111)
which is the Larmor formula for radiated power from an accelerated charge. Note that here we are treating a charge with v′ ≪ c but otherwise totally unspecified motion while we compare with formulae derived for a stationary oscillating dipole. The electric and magnetic fields, equation (6.106) and equation (6.107) above, respectively, and the expressions for the Poynting flux and power derived from them, are here instantaneous values, dependent on the instantaneous position of the charge at x′ (t′ ). The angular distribution is that which is ‘frozen’ to the point from which the energy is radiated.
104
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
v′ = 0.5c v′ = 0.25c v′
v′ = 0
F IGURE 6 .8 : Polar diagram of the energy loss angular distribution factor sin2 θ/(1−v cos θ/c)5 during bremsstrahlung for particle speeds v′ = 0, v′ = 0.25c, and v′ = 0.5c.
6.3.3 Bremsstrahlung
An important special case of radiation is when the velocity v′ and the acceleration ˙ ˙ v′ are collinear (parallel or anti-parallel) so that v′ × v′ = 0. This condition (for an arbitrary magnitude of v′ ) inserted into expression (6.94) on page 101 for the radiation field, yields Erad (t, x) = q′ ˙ (x − x′ ) × [(x − x′ ) × v′ ], 4πε0 c2 s3 v′ ˙ v′ (6.112)
from which we obtain, with the use of formula (6.93) on page 101, the magnetic field Brad (t, x) = q′ |x − x′ | ′ [˙ × (x − x′ )], v 4πε0 c3 s3 v′ ˙ v′ (6.113)
The difference between this case and the previous case of v′ ≪ c is that the approximate expression (6.104) on page 103 for s is no longer valid; instead we must use the correct expression (6.72) on page 95. The angular distribution of the power flux (Poynting vector) therefore becomes S= sin2 θ µ0 q′ 2 v′2 ˙ 2 16π2 c |x − x′ | 1 − v′ cos θ c
6
x − x′ |x − x′ |
(6.114)
It is interesting to note that the magnitudes of the electric and magnetic fields are ˙ the same whether v′ and v′ are parallel or anti-parallel. We must be careful when we compute the energy (S integrated over time). The Poynting vector is related to the time t when it is measured and to a fixed surface
Downloaded from
Version released 1st July 2008 at 20:49.
105
6. Electromagnetic Radiation and Radiating Systems
in space. The radiated power into a solid angle element dΩ, measured relative to the particle’s retarded position, is given by the formula dU rad (θ) sin2 θ ˙ µ0 q′ 2 v′2 dΩ = S · (x − x′ ) x − x′ dΩ = dt 16π2 c 1 − v′ cos θ c dΩ (6.115)
6
On the other hand, the radiation loss due to radiation from the charge at retarded time t′ : dU rad dU rad dΩ = ′ dt dt ∂t ∂t′ dΩ
x
(6.116)
Using formula (6.80) on page 98, we obtain dU rad dU rad s dΩ = S · (x − x′ )s dΩ dΩ = dt′ dt |x − x′ | (6.117)
Inserting equation (6.114) on page 105 for S into (6.117), we obtain the explicit expression for the energy loss due to radiation evaluated at the retarded time dU rad (θ) sin2 θ µ0 q′ 2 v′2 ˙ dΩ = dt′ 16π2 c 1 − v′ cos θ c dΩ (6.118)
5
The angular factors of this expression, for three different particle speeds, are plotted in figure 6.8 on page 105. Comparing expression (6.115) above with expression (6.118), we see that they differ by a factor 1 − v′ cos θ/c which comes from the extra factor s/ |x − x′ | introduced in (6.117). Let us explain this in geometrical terms. During the interval (t′ , t′ + dt′ ) and within the solid angle element dΩ the particle radiates an energy [dU rad (θ)/dt′ ] dt′ dΩ. As shown in figure 6.9 on page 107 this energy is at time t located between two spheres, one outer with its origin at x′ (t′ ) and radius c(t −t′ ), and one inner with its origin at x′ (t′ +dt′ ) = x′ (t′ )+v′ dt′ 1 2 1 and radius c[t − (t′ + dt′ )] = c(t − t′ − dt′ ). From Figure 6.9 we see that the volume element subtending the solid angle element dΩ = is d3x = dS dr = x − x′ 2
2
dS x − x′ 2
2
(6.119)
dΩ dr
(6.120)
106
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
dS dr x dΩ ′ θ q ′ ′ x′ v dt x′ 2 1 x − x′ + c dt′ 2
F IGURE 6 .9 : Location of radiation between two spheres as the charge moves with velocity v′ from x′ to x′ during the time interval (t′ , t′ +dt′ ). The observation 1 2 point (field point) is at the fixed location x.
Here, dr denotes the differential distance between the two spheres and can be evaluated in the following way dr = x − x′ + c dt′ − x − x′ − 2 2 x′ 2 x′ 2 x − x′ 2 · v′ dt′ x − x′ 2 v′ cos θ = c− x− x− · v′ dt′ = cs dt′ x − x′ 2 (6.121)
where formula (6.72) on page 95 was used in the last step. Hence, the volume element under consideration is d3x = dS dr = s dS cdt′ x − x′ 2 (6.122)
We see that the energy which is radiated per unit solid angle during the time interval (t′ , t′ + dt′ ) is located in a volume element whose size is θ dependent. This explains the difference between expression (6.115) on page 106 and expression (6.118) on page 106. ˜ Let the radiated energy, integrated over Ω, be denoted U rad . After tedious, but
Downloaded from
Version released 1st July 2008 at 20:49.
107
6. Electromagnetic Radiation and Radiating Systems
relatively straightforward integration of formula (6.118) on page 106, one obtains ˜ dU rad µ0 q′ 2 v′2 ˙ = dt′ 6πc 1 1−
v′2 c2 3
=
v′2 ˙ 2 q′ 2 v′2 1− 2 3 3 4πε0 c c
−3
(6.123)
If we know v′ (t′ ), we can integrate this expression over t′ and obtain the total energy radiated during the acceleration or deceleration of the particle. This way we obtain a classical picture of bremsstrahlung (braking radiation, free-free radiation). Often, an atomistic treatment is required for obtaining an acceptable result.
6.3.4 Cyclotron and synchrotron radiation (magnetic bremsstrahlung)
Formula (6.93) and formula (6.94) on page 101 for the magnetic field and the radiation part of the electric field are general, valid for any kind of motion of the localised charge. A very important special case is circular motion, i.e., the case ˙ v′ ⊥ v′ . With the charged particle orbiting in the x1 x2 plane as in figure 6.10 on page 109, an orbit radius a, and an angular frequency ω0 , we obtain ϕ(t′ ) = ω0 t′ x (t ) = a[ x1 cos ϕ(t ) + x2 sin ϕ(t )] ˆ ˆ ˙ v (t ) = x′ (t′ ) = aω0 [− x1 sin ϕ(t′ ) + x2 cos ϕ(t′ )] ˆ ˆ v = v = aω0 ˙ v (t ) = v = ˙
′ ′ ′ ′ ′ ′ ′ ′ ′ ′ ′
(6.124a) (6.124b) (6.124c) (6.124d) cos ϕ(t ) + x2 sin ϕ(t )] ˆ
′ ′
¨ x (t ) = −aω2 [ x1 0 ˆ ′ 2 ˙ v = aω0
′ ′
(6.124e) (6.124f)
Because of the rotational symmetry we can, without loss of generality, rotate our coordinate system around the x3 axis so the relative vector x − x′ from the source point to an arbitrary field point always lies in the x2 x3 plane, i.e., x − x′ = x − x′ ( x2 sin α + x3 cos α) ˆ ˆ (6.125)
where α is the angle between x − x′ and the normal to the plane of the particle orbit (see Figure 6.10). From the above expressions we obtain (x − x′ ) · v′ = x − x′ v′ sin α cos ϕ
′ ′ ′ ′
(6.126a)
′ ′
˙ (x − x ) · v = − x − x v sin α sin ϕ = x − x v cos θ ˙ ˙
(6.126b)
where in the last step we simply used the definition of a scalar product and the ˙ fact that the angle between v′ and x − x′ is θ.
108
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
x2 x(t) x v′ (t′ ) a α 0 q′ ′ ′ x (t ) θ ˙ v′ ϕ(t′ ) x1 x − x′
x3
F IGURE 6 .10 : Coordinate system for the radiation from a charged particle at x′ (t′ ) in circular motion with velocity v′ (t′ ) along the tangent and constant accel˙ eration v′ (t′ ) toward the origin. The x1 x2 axes are chosen so that the relative field point vector x − x′ makes an angle α with the x3 axis which is normal to the plane of the orbital motion. The radius of the orbit is a.
The power flux is given by the Poynting vector, which, with the help of formula (6.93) on page 101, can be written S= 1 1 x − x′ (E × B) = |E|2 µ0 cµ0 |x − x′ | (6.127)
Inserting this into equation (6.117) on page 106, we obtain dU rad (α, ϕ) |x − x′ | s 2 = |E| dt′ cµ0 (6.128)
where the retarded distance s is given by expression (6.72) on page 95. With the radiation part of the electric field, expression (6.94) on page 101, inserted, and using (6.126a) and (6.126b) on page 108, one finds, after some algebra, that dU rad (α, ϕ) µ0 q′ 2 v′2 1 − ˙ = dt′ 16π2 c
v′ c
sin α cos ϕ 1−
v′ c
2
− 1−
v′2 c2 5
sin2 α sin2 ϕ (6.129)
sin α cos ϕ
The angles θ and ϕ vary in time during the rotation, so that θ refers to a moving coordinate system. But we can parametrise the solid angle dΩ in the angle ϕ
Downloaded from
Version released 1st July 2008 at 20:49.
109
6. Electromagnetic Radiation and Radiating Systems
and the (fixed) angle α so that dΩ = sin α dα dϕ. Integration of equation (6.129) on page 109 over this dΩ gives, after some cumbersome algebra, the angular integrated expression ˜ ˙ dU rad µ0 q′ 2 v′2 = ′ dt 6πc 1 1−
v′2 c2 2
(6.130)
In equation (6.129) on page 109, two limits are particularly interesting: 1. v′ /c ≪ 1 which corresponds to cyclotron radiation. 2. v′ /c 1 which corresponds to synchrotron radiation.
Cyclotron radiation
For a non-relativistic speed v′ ≪ c, equation (6.129) on page 109 reduces to dU rad (α, ϕ) µ0 q′ 2 v′2 ˙ = (1 − sin2 α sin2 ϕ) dt′ 16π2 c But, according to equation (6.126b) on page 108 sin2 α sin2 ϕ = cos2 θ (6.132) (6.131)
where θ is defined in figure 6.10 on page 109. This means that we can write ˙ ˙ µ0 q′ 2 v′2 dU rad (θ) µ0 q′ 2 v′2 = (1 − cos2 θ) = sin2 θ ′ 2c 2c dt 16π 16π (6.133)
Consequently, a fixed observer near the orbit plane (α ≈ π/2) will observe cyclotron radiation twice per revolution in the form of two equally broad pulses of radiation with alternating polarisation.
Synchrotron radiation
When the particle is relativistic, v′ c, the denominator in equation (6.129) on page 109 becomes very small if sin α cos ϕ ≈ 1, which defines the forward direction of the particle motion (α ≈ π/2, ϕ ≈ 0). The equation (6.129) on page 109 becomes dU rad (π/2, 0) µ0 q′ 2 v′2 ˙ 1 = dt′ 16π2 c 1 − v′ c
3
(6.134)
which means that an observer near the orbit plane sees a very strong pulse followed, half an orbit period later, by a much weaker pulse.
110
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
x(t) x − x′ ∆θ
x2
v′ (t′ ) a 0 q′ ′ ′ ∆θ x (t ) ˙ v′ ϕ(t′ ) x1
x3
F IGURE 6 .11 :
When the observation point is in the plane of the particle orbit, i.e., α = π/2 the lobe width is given by ∆θ.
The two cases represented by equation (6.133) on page 110 and equation (6.134) on page 110 are very important results since they can be used to determine the characteristics of the particle motion both in particle accelerators and in astrophysical objects where a direct measurement of particle velocities are impossible. In the orbit plane (α = π/2), equation (6.129) on page 109 gives ˙ dU rad (π/2, ϕ) µ0 q′ 2 v′2 1 − = ′ 2c dt 16π
v′ c
cos ϕ
2
− 1− cos ϕ
v′2 c2 5
sin2 ϕ (6.135)
1−
v′ c
which vanishes for angles ϕ0 such that cos ϕ0 = sin ϕ0 = v′ c 1− v′2 c2 (6.136a) (6.136b)
Hence, the angle ϕ0 is a measure of the synchrotron radiation lobe width ∆θ; see figure 6.11. For ultra-relativistic particles, defined by γ= 1 1−
v′2 c2
≫ 1,
1−
v′2 ≪ 1, c2
(6.137)
Downloaded from
Version released 1st July 2008 at 20:49.
111
6. Electromagnetic Radiation and Radiating Systems
one can approximate ϕ0 ≈ sin ϕ0 = 1− v′2 1 = c2 γ (6.138)
Hence, synchrotron radiation from ultra-relativistic charges is characterized by a radiation lobe width which is approximately ∆θ ≈ 1 γ (6.139)
This angular interval is swept by the charge during the time interval ∆t′ = ∆θ ω0 (6.140)
during which the particle moves a length interval ∆l′ = v′ ∆t′ = v′ ∆θ ω0 (6.141)
in the direction toward the observer who therefore measures a compressed pulse width of length ∆t = ∆t′ − = 1− v′ ∆t′ ∆l′ = ∆t′ − = c c 1+ v′ 1+ c ≈2
v′ c v′ c
1− 1−
v′ c
∆t′ =
1−
v′ c
∆θ ≈ ω0
1−
v′ c
1 γω0
1 ≈ γω0
v′2 c2
1 1 1 = 3 2γω0 2γ ω0
1/γ2 (6.142)
1/∆t. In the ultraTypically, the spectral width of a pulse of length ∆t is ∆ω relativistic synchrotron case one can therefore expect frequency components up to ωmax ≈ 1 = 2γ3 ω0 ∆t (6.143)
A spectral analysis of the radiation pulse will therefore exhibit a (broadened) line spectrum of Fourier components nω0 from n = 1 up to n ≈ 2γ3 . When many charged particles, N say, contribute to the radiation, we can have three different situations depending on the relative phases of the radiation fields from the individual particles:
112
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
1. All N radiating particles are spatially much closer to each other than a typical wavelength. Then the relative phase differences of the individual electric and magnetic fields radiated are negligible and the total radiated fields from all individual particles will add up to become N times that from one particle. This means that the power radiated from the N particles will be N 2 higher than for a single charged particle. This is called coherent radiation. 2. The charged particles are perfectly evenly distributed in the orbit. In this case the phases of the radiation fields cause a complete cancellation of the fields themselves. No radiation escapes. 3. The charged particles are somewhat unevenly distributed in the orbit. This happens for an open ring current, carried initially by evenly distributed charged particles, which is subject to thermal fluctuations. From statistical mechanics we know that this happens for all open systems and that the √ particle densities√ exhibit fluctuations of order N. This means that out of the N particles, N will exhibit deviation from perfect randomness—and thereby perfect radiation field cancellation—and give rise to net radiation √ fields which are proportional to N. As a result, the radiated power will be proportional to N, and we speak about incoherent radiation. Examples of this can be found both in earthly laboratories and under cosmic conditions.
Radiation in the general case
We recall that the general expression for the radiation E field from a moving charge concentration is given by expression (6.94) on page 101. This expression in equation (6.128) on page 109 yields the general formula dU rad (θ, ϕ) µ0 q′ 2 |x − x′ | = dt′ 16π2 cs5 (x − x′ ) × (x − x′ ) − |x − x′ | v′ c
2
˙ × v′ (6.144)
Integration over the solid angle Ω gives the totally radiated power as ˜ ˙ dU rad µ0 q′ 2 v′2 1 − v 2 sin2 ψ c = 3 ′ ′2 dt 6πc 1 − v2 c
′2
(6.145)
˙ where ψ is the angle between v′ and v′ . ˙ ˙ If v′ is collinear with v′ , then sin ψ = 0, we get bremsstrahlung. For v′ ⊥ v′ , sin ψ = 1, which corresponds to cyclotron radiation or synchrotron radiation.
Downloaded from
Version released 1st July 2008 at 20:49.
113
6. Electromagnetic Radiation and Radiating Systems
vt q′ b θ0 |x − x0 | B E⊥ x3 ˆ
F IGURE 6 .12 :
v′ = v′ x1 ˆ
The perpendicular electric field of a charge q′ moving with velocity v′ = v′ x is E⊥ z. ˆ ˆ
Virtual photons
Let us consider a charge q′ moving with constant, high velocity v′ (t′ ) along the x1 axis. According to formula (6.204) on page 127 and figure 6.12, the perpendicular component along the x3 axis of the electric field from this moving charge is E⊥ = E3 = q′ 4πε0 s3 1− v′2 c2 (x − x0 ) · x3 ˆ (6.146)
Utilising expression (6.102) on page 103 and simple geometrical relations, we can rewrite this as E⊥ = b q′ 4πε0 γ2 (v′ t′ )2 + b2 /γ2
3/2
(6.147)
This represents a contracted Coulomb field, approaching the field of a plane wave. The passage of this field ‘pulse’ corresponds to a frequency distribution of the field energy. Fourier transforming, we obtain Eω,⊥ = 1 2π
∞ −∞
dt E⊥ (t) eiωt =
q′ 4π2 ε0 bv′
bω v′ γ
K1
bω v′ γ
(6.148)
Here, K1 is the Kelvin function (Bessel function of the second kind with imaginary argument) which behaves in such a way for small and large arguments that Eω,⊥ ∼ q′ 4π2 ε
′ 0 bv
,
bω ≪ v′ γ ⇔
b ω≪1 v′ γ
(6.149a) (6.149b)
Eω,⊥ ∼ 0,
bω ≫ v′ γ ⇔
b ω≫1 v′ γ
114
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
showing that the ‘pulse’ length is of the order b/(v′ γ). Due to the equipartitioning of the field energy into the electric and magnetic fields, the total field energy can be written ˜ U = ε0
V 2 d3x E⊥ = ε0 bmax
db 2πb
bmin
∞ −∞
2 dt v′ E⊥
(6.150)
where the volume integration is over the plane perpendicular to v′ . With the use of Parseval’s identity for Fourier transforms, formula (5.34) on page 75, we can rewrite this as ˜ U=
0 ∞
˜ dω Uω = 4πε0 v′
∞ −∞
bmax
db 2πb
0
∞
q′2 ≈ 2 ′ 2π ε0 v
dω
bmin v′ γ/ω db bmin
2 dω Eω,⊥
(6.151)
b
from which we conclude that ˜ Uω ≈ q′2 ln 2π2 ε0 v′ v′ γ bmin ω (6.152)
where an explicit value of bmin can be calculated in quantum theory only. As in the case of bremsstrahlung, it is intriguing to quantise the energy into photons [cf. equation (6.234) on page 131]. Then we find that Nω dω ≈ 2α ln π cγ bmin ω dω ω (6.153)
where α = e2 /(4πε0 c) ≈ 1/137 is the fine structure constant. Let us consider the interaction of two (classical) electrons, 1 and 2. The result of this interaction is that they change their linear momenta from p1 to p′ and p2 to 1 p′ , respectively. Heisenberg’s uncertainty principle gives bmin ∼ / p1 − p′ so 1 2 that the number of photons exchanged in the process is of the order cγ dω 2α ln (6.154) p1 − p′ 1 π ω ω ′ Since this change in momentum corresponds to a change in energy ω = E1 − E1 2 and E1 = m0 γc , we see that Nω dω ≈ Nω dω ≈ 2α ln π E1 cp1 − cp′ 1 ′ m0 c2 E1 − E1 dω ω (6.155)
a formula which gives a reasonable semi-classical account of a photon-induced electron-electron interaction process. In quantum theory, including only the lowest order contributions, this process is known as Møller scattering. A diagrammatic representation of (a semi-classical approximation of) this process is given in figure 6.13 on page 116.
Downloaded from
Version released 1st July 2008 at 20:49.
115
6. Electromagnetic Radiation and Radiating Systems
p2
p1
F IGURE 6 .13 :
Diagrammatic representation of the semi-classical electronelectron interaction (Møller scattering).
6.3.5 Radiation from charges moving in matter
When electromagnetic radiation is propagating through matter, new phenomena may appear which are (at least classically) not present in vacuum. As mentioned earlier, one can under certain simplifying assumptions include, to some extent, the influence from matter on the electromagnetic fields by introducing new, derived field quantities D and H according to D = ε(t, x)E = κe ε0 E B = µ(t, x)H = κm µ0 H (6.156) (6.157)
¡
γ
Version released 1st July 2008 at 20:49.
p′ 2
p′ 1
Expressed in terms of these derived field quantities, the Maxwell equations, often called macroscopic Maxwell equations, take the form ∇ · D = ρ(t, x) ∂B ∇×E=− ∂t ∇·B=0 ∂D ∇×H= + j(t, x) ∂t (6.158a) (6.158b) (6.158c) (6.158d)
Assuming for simplicity that the electric permittivity ε and the magnetic permeability µ, and hence the relative permittivity κe and the relative permeability κm all have fixed values, independent on time and space, for each type of material we consider, we can derive the general telegrapher’s equation [cf. equation (2.34) on page 31] ∂E ∂2 E ∂2 E − σµ − εµ 2 = 0 2 ∂ζ ∂t ∂t (6.159)
116
Downloaded from
Radiation from a localised charge in arbitrary motion
describing (1D) wave propagation in a material medium. In chapter 2 we concluded that the existence of a finite conductivity, manifesting itself in a collisional interaction between the charge carriers, causes the waves to decay exponentially with time and space. Let us therefore assume that in our medium σ = 0 so that the wave equation simplifies to ∂2 E ∂2 E − εµ 2 = 0 ∂ζ 2 ∂t If we introduce the phase velocity in the medium as 1 c 1 = √ vϕ = √ = √ εµ κe ε0 κm µ0 κe κm (6.161) (6.160)
√ where, according to equation (1.11) on page 6, c = 1/ ε0 µ0 is the speed of light, i.e., the phase speed of electromagnetic waves in vacuum, then the general solution to each component of equation (6.160) Ei = f (ζ − vϕ t) + g(ζ + vϕ t), √ c √ def = κe κm = c εµ ≡ n vϕ i = 1, 2, 3 (6.162)
The ratio of the phase speed in vacuum and in the medium (6.163)
is called the refractive index of the medium. In general n is a function of both time and space as are the quantities ε, µ, κe , and κm themselves. If, in addition, the medium is anisotropic or birefringent, all these quantities are rank-two tensor fields. Under our simplifying assumptions, in each medium we consider n = Const for each frequency component of the fields. Associated with the phase speed of a medium for a wave of a given frequency ω we have a wave vector, defined as def ω vϕ ˆ (6.164) k ≡ k k = kˆ ϕ = v vϕ vϕ As in the vacuum case discussed in chapter 2, assuming that E is time-harmonic, i.e., can be represented by a Fourier component proportional to exp{−iωt}, the solution of equation (6.160) can be written E = E0 ei(k·x−ωt) (6.165)
where now k is the wave vector in the medium given by equation (6.164) above. With these definitions, the vacuum formula for the associated magnetic field, equation (2.41) on page 31, B= √ ˆ εµ k × E = 1 ˆ 1 k×E= k×E vϕ ω (6.166)
Downloaded from
Version released 1st July 2008 at 20:49.
117
6. Electromagnetic Radiation and Radiating Systems
is valid also in a material medium (assuming, as mentioned, that n has a fixed constant scalar value). A consequence of a κe 1 is that the electric field will, in general, have a longitudinal component. It is important to notice that depending on the electric and magnetic properties of a medium, and, hence, on the value of the refractive index n, the phase speed in the medium can be smaller or larger than the speed of light: vϕ = c ω = n k (6.167)
where, in the last step, we used equation (6.164) on page 117. If the medium has a refractive index which, as is usually the case, dependent on frequency ω, we say that the medium is dispersive. Because in this case also k(ω) and ω(k), so that the group velocity vg = ∂ω ∂k (6.168)
has a unique value for each frequency component, and is different from vϕ . Except in regions of anomalous dispersion, vg is always smaller than c. In a gas of free charges, such as a plasma, the refractive index is given by the expression n2 (ω) = 1 − where ω2 = ∑ p
σ
ω2 p ω2
(6.169)
Nσ q2 σ ε0 mσ
(6.170)
is the square of the plasma frequency ωp . Here mσ and Nσ denote the mass and number density, respectively, of charged particle species σ. In an inhomogeneous plasma, Nσ = Nσ (x) so that the refractive index and also the phase and group velocities are space dependent. As can be easily seen, for each given frequency, the phase and group velocities in a plasma are different from each other. If the frequency ω is such that it coincides with ωp at some point in the medium, then at that point vϕ → ∞ while vg → 0 and the wave Fourier component at ω is reflected there.
ˇ Vavilov-Cerenkov radiation
As we saw in subsection 6.2, a charge in uniform, rectilinear motion in vacuum does not give rise to any radiation; see in particular equation (6.202a) on page 126. Let us now consider a charge in uniform, rectilinear motion in a medium with electric properties which are different from those of a (classical) vacuum. Specifically,
118
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
consider a medium where ε = Const > ε0 µ = µ0 This implies that in this medium the phase speed is vϕ = c 1 = √ <c n εµ0 (6.172) (6.171a) (6.171b)
Hence, in this particular medium, the speed of propagation of (the phase planes of) electromagnetic waves is less than the speed of light in vacuum, which we know is an absolute limit for the motion of anything, including particles. A medium of this kind has the interesting property that particles, entering into the medium at high speeds |v′ |, which, of course, are below the phase speed in vacuum, can experience that the particle speeds are higher than the phase speed in the medium. ˇ This is the basis for the Vavilov-Cerenkov radiation, more commonly known as Cerenkov radiation, that we shall now study. If we recall the general derivation, in the vacuum case, of the retarded (and advanced) potentials in chapter 3 and the Liénard-Wiechert potentials, equations (6.71) on page 95, we realise that we obtain the latter in the medium by a simple formal replacement c → c/n in the expression (6.72) on page 95 for s. Hence, the Liénard-Wiechert potentials in a medium characterized by a refractive index n, are 1 q′ q′ 1 = ′ )·v′ 4πε0 |x − x′ | − n (x−x 4πε0 s c ′ ′ qv q′ v′ 1 1 = A(t, x) = ′ )·v′ 4πε0 c2 |x − x′ | − n (x−x 4πε0 c2 s c φ(t, x) = where now s = x − x′ − n (x − x′ ) · v′ c (6.174) (6.173a) (6.173b)
The need for the absolute value of the expression for s is obvious in the case when v′ /c ≥ 1/n because then the second term can be larger than the first term; if v′ /c ≪ 1/n we recover the well-known vacuum case but with modified phase speed. We also note that the retarded and advanced times in the medium are [cf. equation (3.32) on page 46]
′ ′ tret = tret (t, x − x′ ) = t − ′ tadv
k |x − x′ | |x − x′ | n =t− ω c k |x − x′ | |x − x′ | n ′ = tadv (t, x − x′ ) = t + =t+ ω c
(6.175a) (6.175b)
Downloaded from
Version released 1st July 2008 at 20:49.
119
6. Electromagnetic Radiation and Radiating Systems
x(t)
θc x′ (t′ )
αc
q′
v′
F IGURE 6 .14 : Instantaneous picture of the expanding field spheres from a point charge moving with constant speed v′ /c > 1/n in a medium where n > 1. This ˇ generates a Vavilov-Cerenkov shock wave in the form of a cone.
so that the usual time interval t − t′ between the time measured at the point of observation and the retarded time in a medium becomes t − t′ = |x − x′ | n c (6.176)
For v′ /c ≥ 1/n, the retarded distance s, and therefore the denominators in equations (6.173) on page 119, vanish when n(x − x′ ) · v′ nv′ = x − x′ cos θc = x − x′ c c (6.177)
or, equivalently, when c cos θc = ′ nv
(6.178)
In the direction defined by this angle θc , the potentials become singular. During the time interval t − t′ given by expression (6.176) above, the field exists within a sphere of radius |x − x′ | around the particle while the particle moves a distance l′ = (t − t′ )v′ (6.179) along the direction of v′ . In the direction θc where the potentials are singular, all field spheres are tangent to a straight cone with its apex at the instantaneous position of the particle and with the apex half angle αc defined according to c (6.180) sin αc = cos θc = ′ nv
120
Version released 1st July 2008 at 20:49.
Downloaded from
Radiation from a localised charge in arbitrary motion
This cone of potential singularities and field sphere circumferences propagates ˇ with speed c/n in the form of a shock front, called Vavilov-Cerenkov radiation.1 ˇ The Vavilov-Cerenkov cone is similar in nature to the Mach cone in acoustics. In order to make some quantitative estimates of this radiation, we note that we can describe the motion of each charged particle q′ as a current density: j = q′ v′ δ(x′ − v′ t′ ) = q′ v′ δ(x′ − v′ t′ )δ(y′ )δ(z′ ) x1 ˆ which has the trivial Fourier transform jω = q′ iωx′ /v′ e δ(y′ )δ(z′ ) x1 ˆ 2π (6.182) (6.181)
This Fourier component can be used in the formulae derived for a linear current in subsection 6.1.1 if only we make the replacements ε0 → ε = n2 ε0 nω k→ c (6.183a) (6.183b)
In this manner, using jω from equation (6.182), the resulting Fourier transforms ˇ of the Vavilov-Cerenkov magnetic and electric radiation fields can be calculated from the expressions (5.10) on page 68) and (5.21) on page 70, respectively. The total energy content is then obtained from equation (5.34) on page 75 (integrated over a closed sphere at large distances). For a Fourier component one obtains [cf. equation (5.37) on page 76]
rad Uω dΩ
1 ≈ 4πε0 nc q′ 2 nω2 = 16π3 ε0 c3
2 V′
d x (jω × k)e
∞ −∞
3 ′
−ik·x′
dΩ
2
(6.184) sin θ dΩ
2
exp ix
′
ω − k cos θ v′
dx
′
1 The first systematic exploration of this radiation was made by P. A. Cerenkov in 1934, who was then ˇ a post-graduate student in S. I. Vavilov’s research group at the Lebedev Institute in Moscow. Vavilov wrote ˇ a manuscript with the experimental findings, put Cerenkov as the author, and submitted it to Nature. In the manuscript, Vavilov explained the results in terms of radioactive particles creating Compton electrons which gave rise to the radiation (which was the correct interpretation), but the paper was rejected. The paper was then sent to Physical Review and was, after some controversy with the American editors who claimed the results to be wrong, eventually published in 1937. In the same year, I. E. Tamm and I. M. Frank published the theory for the effect (‘the singing electron’). In fact, predictions of a similar effect had been made as early as 1888 by Heaviside, and by Sommerfeld in his 1904 paper ‘Radiating body moving with velocity of light’. On May 8, 1937, Sommerfeld sent a letter to Tamm via Austria, saying that he was ˇ surprised that his old 1904 ideas were now becoming interesting. Tamm, Frank and Cerenkov received ˇ the Nobel Prize in 1958 ‘for the discovery and the interpretation of the Cerenkov effect’ [V. L. Ginzburg, private communication]. The first observation of this type of radiation was reported by Marie Curie in 1910, but she never pursued the exploration of it [8].
Downloaded from
Version released 1st July 2008 at 20:49.
121
6. Electromagnetic Radiation and Radiating Systems
where θ is the angle between the direction of motion, x′ , and the direction to the ˆ1 ˆ observer, k. The integral in (6.184) is singular of a ‘Dirac delta type’. If we limit the spatial extent of the motion of the particle to the closed interval [−X, X] on the x′ axis we can evaluate the integral to obtain
rad Uω dΩ
q′ 2 nω2 sin2 θ sin2 1 − nv cos θ c = ′ ω 4π3 ε0 c3 1 − nv cos θ v′ c
′
Xω v′ 2
dΩ
(6.185)
which has a maximum in the direction θc as expected. The magnitude of this maximum grows and its width narrows as X → ∞. The integration of (6.185) over Ω therefore picks up the main contributions from θ ≈ θc . Consequently, we can set sin2 θ ≈ sin2 θc and the result of the integration is ˜ rad Uω = 2π
π 0 rad Uω (θ) sin θ dθ = ⌈cos θ = −ξ⌋ = 2π 1 −1 1 −1 rad Uω (ξ) dξ
q′ 2 nω2 sin2 θc ≈ 2π2 ε0 c3
sin2
1+ 1+
nv′ ξ c
nv′ ξ c
Xω v′ ω 2 v′
(6.186)
dξ
The integrand in (6.186) is strongly peaked near ξ = −c/(nv′ ), or, equivalently, near cos θc = c/(nv′ ). This means that the integrand function is practically zero outside the integration interval ξ ∈ [−1, 1]. Consequently, one may extend the ξ integration interval to (−∞, ∞) without introducing too much an error. Via yet another variable substitution we can therefore approximate sin θc
2 1 −1
sin2
1+ 1+
nv′ ξ c
nv′ ξ c
Xω v′ ω 2 v′
dξ ≈ =
1− cXπ ωn
c2 n2 v′2 1−
cX ωn c2 n2 v′2
∞ −∞
sin2 x dx x2
(6.187) leading to the final approximate result for the total energy loss in the frequency interval (ω, ω + dω) q′ 2 X ˜ rad Uω dω = 2πε0 c2 1− c2 n2 v′2 ω dω (6.188)
As mentioned earlier, the refractive index is usually frequency dependent. Realising this, we find that the radiation energy per frequency unit and per unit length is ˜ rad q′ 2 ω Uω dω = 2X 4πε0 c2 1− c2 n2 (ω)v′2 dω (6.189)
122
Version released 1st July 2008 at 20:49.
Downloaded from
Bibliography
This result was derived under the assumption that v′ /c > 1/n(ω), i.e., under the condition that the expression inside the parentheses in the right hand side is positive. For all media it is true that n(ω) → 1 when ω → ∞, so there exist always ˇ a highest frequency for which we can obtain Vavilov-Cerenkov radiation from a fast charge in a medium. Our derivation above for a fixed value of n is valid for each individual Fourier component.
6.4 Bibliography
[1] [2] [3]
H. A LFVÉN AND N. H ERLOFSON, Cosmic radiation and radio stars, Physical Review, 78
(1950), p. 616.
R. B ECKER, Electromagnetic Fields and Interactions, Dover Publications, Inc., New York, NY, 1982, ISBN 0-486-64290-9. M. B ORN AND E. W OLF, Principles of Optics. Electromagnetic Theory of Propagation, Interference and Diffraction of Light, sixth ed., Pergamon Press, Oxford,. . . , 1980, ISBN 0-08-026481-6.. J. D. JACKSON, Classical Electrodynamics, third ed., John Wiley & Sons, Inc., New York, NY . . . , 1999, ISBN 0-471-30932-X. J. B. M ARION AND M. A. H EALD, Classical Electromagnetic Radiation, second ed., Academic Press, Inc. (London) Ltd., Orlando, . . . , 1980, ISBN 0-12-472257-1. W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026. J. S CHWINGER , L. L. D E R AAD , J R ., K. A. M ILTON , AND W. T SAI, Classical Electrodynamics, Perseus Books, Reading, MA, 1998, ISBN 0-7382-0056-5. 18, 121 J. A. S TRATTON, Electromagnetic Theory, McGraw-Hill Book Company, Inc., New York, NY and London, 1953, ISBN 07-062150-0.
[4]
[5] [6] [7]
[8] [9]
[10] J. VANDERLINDE, Classical Electromagnetic Theory, John Wiley & Sons, Inc., New York, Chichester, Brisbane, Toronto, and Singapore, 1993, ISBN 0-471-57269-1.
Downloaded from
Version released 1st July 2008 at 20:49.
123
6. Electromagnetic Radiation and Radiating Systems
6.5 Examples
E XAMPLE 6.1
⊲ L INEAR AND ANGULAR MOMENTA RADIATED FROM AN ELECTRIC DIPOLE IN VACUUM The Fourier amplitudes of the fields generated by an electric dipole, pω , oscillating at the angular frequency ω, are given by formulae (6.50) on page 90. Inverse Fourier transforming to the time domain, and using a spherical coordinate system (r, θ, ϕ), the physically observable fields are found to be B(t, x) = E(t, x) = ωµ0 pω sin θ 4π 1 k sin(kr − ωt′ ) − cos(kr − ωt′ ) ϕ ˆ r2 r (6.190a)
1 k k2 1 ˆ pw sin θ 3 cos(kr − ωt′ ) + 2 sin(kr − ωt′ ) − cos(kr − ωt′ ) θ 4πε0 r r r k 1 1 pw cos θ 3 cos(kr − ωt′ ) + 2 sin(kr − ωt′ ) r ˆ (6.190b) + 2πε0 r r
where t′ = t − r/c is the retarded time. From equation (4.41) on page 61 we see that, in vacuum, the power flux (Poynting vector) is S = E × B/µ0 and, hence, that the linear momentum density is g(t, x) = B 1 E× = ε0 E × B c2 µ0 (6.191)
Inserting the fields from a pure electric dipole, equations (6.190) above, into this expression, one obtains g(t, x) = − 1 ωµ0 2 p sin θ cos θ 5 sin(kr − ωt′ ) cos(kr − ωt′ ) 8π2 ω r +
k k2 ˆ sin2 (kr − ωt′ ) − cos2 (kr − ωt′ ) − 3 sin(kr − ωt′ ) cos(kr − ωt′ ) θ 4 r r 1 ωµ0 2 + p sin2 θ 5 sin(kr − ωt′ ) cos(kr − ωt′ ) 16π2 ω r + k2 k sin2 (kr − ωt′ ) − cos2 (kr − ωt′ ) − 2 3 sin(kr − ωt′ ) cos(kr − ωt′ ) 4 r r k3 2 ′ + 2 cos (kr − ωt ) r ˆ (6.192) r
Using well-known trigonometric relations, this can be put in the form g(t, x) = − 1 k ωµ0 2 p sin θ cos θ 5 sin[2(kr − ωt′ )] − 2 4 cos[2(kr − ωt′ )] 16π2 ω r r −
k2 ˆ sin[2(kr − ωt′ )] θ r3 k ωµ0 2 1 p sin2 θ 5 sin[2(kr − ωt′ )] − 2 4 cos[2(kr − ωt′ )] + 2 ω 32π r r −2 k2 k3 sin[2(kr − ωt′ )] + 2 1 + cos[2(kr − ωt′ )] 3 r r r ˆ (6.193)
124
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
which shows that the linear momentum density, and hence the Poynting vector, is strictly radial only at infinity. Defining the angular momentum density in analogy with classical mechanics, h(t, x) = x × g and using equation (6.193) on page 124, we find that for a pure electric dipole h(t, x) = − 1 ωµ0 2 p sin θ cos θ 4 sin(kr − ωt′ ) cos(kr − ωt′ ) 8π2 ω r + k k2 ˆ sin2 (kr − ωt′ ) − cos2 (kr − ωt′ ) − 2 sin(kr − ωt′ ) cos(kr − ωt′ ) ϕ 3 r r (6.195) (6.194)
or h(t, x) = − ωµ0 2 1 p sin θ cos θ 4 sin[2(kr − ωt′ )] 2 ω 16π r −2 k k2 cos[2(kr − ωt′ )] − 2 sin[2(kr − ωt′ )] ϕ ˆ 3 r r (6.196)
The total electromagnetic linear momentum is (cf. formula (4.41) on page 61) pfield =
V′
d3x′ g(t′ , x′ )
(6.197)
and the total electromagnetic angular momentum is Jfield =
V′
d3x′ h(t′ , x′ )
(6.198)
We note that in the far zone these densities tend to gfarzone (t, x) ≈ ωµ0 2 k3 p sin2 θ cos2 (kr − ωt′ )ˆ r 16π2 ω r2 3 ωµ0 2 k p sin2 θ 1 + cos[2(kr − ωt′ )] r ˆ = 32π2 ω r2 ωµ0 2 k2 p sin θ cos θ sin(kr − ωt′ ) cos(kr − ωt′ )ϕ ˆ 8π2 ω r2 2 ωµ0 2 k p sin θ cos θ sin[2(kr − ωt′ )]ϕ ˆ = 16π2 ω r2 (6.200) respectively. I.e., to leading order, both the linear momentum density g and the angular momentum density h fall off as ∼ 1/r2 far away from the source region. This means that when they are integrated over a spherical surface ∝ r2 located at a large distance from the source (cf. the last term in formula (4.26) on page 59), there is a net flux so that the integrated momenta do not fall off with distance and can therefore be transported all the way to infinity. ⊳ E ND OF EXAMPLE 6.1
(6.199)
and hfarzone (t, x) ≈
Downloaded from
Version released 1st July 2008 at 20:49.
125
6. Electromagnetic Radiation and Radiating Systems
E XAMPLE 6.2
⊲ T HE FIELDS FROM A UNIFORMLY MOVING CHARGE In the special case of uniform motion, the localised charge moves in a field-free, isolated space and we know that it will not be affected by any external forces. It will therefore move uniformly in a straight line with the constant velocity v′ . This gives us the possibility to extrapolate its position at the observation time, x′ (t), from its position at the retarded time, x′ (t′ ). Since the ˙ particle is not accelerated, v′ ≡ 0, the virtual simultaneous coordinate x0 will be identical to the actual simultaneous coordinate of the particle at time t, i.e., x0 (t) = x′ (t). As depicted in figure 6.7 on page 96, the angle between x − x0 and v′ is θ0 while then angle between x − x′ and v′ is θ′ . We note that in the case of uniform velocity v′ , time and space derivatives are closely related in the following way when they operate on functions of x(t) [cf. equation (1.33) on page 13]: ∂ → −v′ · ∇ ∂t
(6.201)
Hence, the E and B fields can be obtained from formulae (6.73) on page 96, with the potentials given by equations (6.71) on page 95 as follows: 1 ∂v′ φ v′ ∂φ ∂A = −∇φ − 2 = −∇φ − 2 ∂t c ∂t c ∂t v′ v′ v′ v′ · ∇φ = − 1 − 2 · ∇φ = −∇φ + c c c v′ v′ = − 1 · ∇φ c2 v′ v′ v′ φ = ∇φ × 2 = − 2 × ∇φ B=∇×A=∇× c2 c c v′ v′ v′ v′ v′ v′ = 2 × · ∇φ − ∇φ = 2 × − 1 · ∇φ c c c c c2 v′ = 2 ×E c
E = −∇φ −
(6.202a)
(6.202b)
Here 1 = xi xi is the unit dyad and we used the fact that v′ × v′ ≡ 0. What remains is just to ˆ ˆ express ∇φ in quantities evaluated at t and x. From equation (6.71a) on page 95 and equation (6.103) on page 103 we find that 1 q′ q′ ∇ ∇s2 =− 4πε0 s 8πε0 s3 v′ v′ q′ (x − x0 ) + × × (x − x0 ) =− 4πε0 s3 c c
∇φ =
(6.203)
When this expression for ∇φ is inserted into equation (6.202a) above, the following result
126
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
E(t, x) = =
q′ v′ v′ − 1 · ∇φ = − c2 8πε0 s3 v′ q′ (x − x0 ) + × 3 4πε0 s c − v′ c
v′ v′ − 1 · ∇s2 c2
v′ × (x − x0 ) c v′ × (x − x0 ) c
v′ v′ v′ v′ · (x − x0 ) − 2 · × c c c
q′ v′ = (x − x0 ) + 4πε0 s3 c − = v′ c v′ · (x − x0 ) c
v′2 v′ · (x − x0 ) − (x − x0 ) 2 c c
(6.204)
q′ v′2 (x − x0 ) 1 − 2 3 4πε0 s c
˙ follows. Of course, the same result also follows from equation (6.90) on page 100 with v′ ≡ 0 inserted. From equation (6.204) above we conclude that E is directed along the vector from the simultaneous coordinate x0 (t) to the field (observation) coordinate x(t). In a similar way, the magnetic field can be calculated and one finds that B(t, x) = µ0 q ′ 4πs3 1− v′2 c2 v′ × (x − x0 ) = 1 ′ v ×E c2 (6.205)
From these explicit formulae for the E and B fields and formula (6.102b) on page 103 for s, we can discern the following cases: 1. v′ → 0 ⇒ E goes over into the Coulomb field ECoulomb
2. v′ → 0 ⇒ B goes over into the Biot-Savart field 3. v′ → c ⇒ E becomes dependent on θ0 4. v′ → c, sin θ0 ≈ 0 ⇒ E → (1 − v′2 /c2 )ECoulomb
5. v′ → c, sin θ0 ≈ 1 ⇒ E → (1 − v′2 /c2 )−1/2 ECoulomb ⊳ E ND OF EXAMPLE 6.2
⊲ T HE CONVECTION POTENTIAL AND THE CONVECTION FORCE Let us consider in more detail the treatment of the radiation from a uniformly moving rigid charge distribution. If we return to the original definition of the potentials and the inhomogeneous wave equation, formula (3.17) on page 44, for a generic potential component Ψ(t, x) and a generic source component f (t, x),
2
E XAMPLE 6.3
Ψ(t, x) =
1 ∂2 − ∇2 Ψ(t, x) = f (t, x) c2 ∂t2
(6.206)
Downloaded from
Version released 1st July 2008 at 20:49.
127
6. Electromagnetic Radiation and Radiating Systems
we find that under the assumption that v′ = v′ x1 , this equation can be written ˆ 1− v′2 c2 ∂2 Ψ ∂2 Ψ ∂2 Ψ + 2 + 2 = − f (x) ∂x2 ∂x2 ∂x3 1 (6.207)
i.e., in a time-independent form. Transforming x1 ξ1 = √ 1 − v′2 /c2 ξ2 = x2 ξ3 = x3 (6.208a) (6.208b) (6.208c)
and introducing the vectorial nabla operator in ξ space, ∇ξ ≡def (∂/∂ξ1 , ∂/∂ξ2 , ∂/∂ξ3 ), the timeindependent equation (??) reduces to an ordinary Poisson equation ∇ξ2 Ψ(ξ) = − f ( 1 4π 1 − v′2 /c2 ξ1 , ξ2 , ξ3 ) ≡ − f (ξ) f (ξ′ ) 3 ′ dξ |ξ − ξ ′ | f (x′ ) 3 ′ dx s
1 2
(6.209)
in this space. This equation has the well-known Coulomb potential solution Ψ(ξ) = (6.210)
V
After inverse transformation back to the original coordinates, this becomes Ψ(x) = 1 4π (6.211)
V
where, in the denominator, s = (x1 − x′ )2 + 1 − 1 v′2 c2 [(x2 − x′ )2 + (x3 − x′ )2 ] 2 3 (6.212)
Applying this to the explicit scalar and vector potential components, realising that for a rigid charge distribution ρ moving with velocity v′ the current is given by j = ρv′ , we obtain 1 ρ(x′ ) 3 ′ dx 4πε0 V s v′ ρ(x′ ) 3 ′ v′ 1 A(t, x) = d x = 2 φ(t, x) 2 4πε0 c V s c φ(t, x) = For a localised charge where ρ d3x′ = q′ , these expressions reduce to q′ 4πε0 s q′ v′ A(t, x) = 4πε0 c2 s φ(t, x) = (6.214a) (6.214b) (6.213a) (6.213b)
which we recognise as the Liénard-Wiechert potentials; cf. equations (6.71) on page 95. We notice, however, that the derivation here, based on a mathematical technique which in fact is a Lorentz transformation, is of more general validity than the one leading to equations (6.71) on page 95. Let us now consider the action of the fields produced from a moving, rigid charge distribution represented by q′ moving with velocity v′ , on a charged particle q, also moving with velocity v′ . This force is given by the Lorentz force
128
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
F = q(E + v′ × B)
(6.215)
With the help of equation (6.205) on page 127 and equations (6.213) on page 128, and the fact that ∂t = −v′ ·∇ [cf. formula (6.201) on page 126], we can rewrite expression (6.215) above as F = q E + v′ × v′ ×E c2 =q v′ · ∇φ c v′ v′ − ∇φ − × c c v′ × ∇φ c (6.216)
Applying the ‘bac-cab’ rule, formula (F.51) on page 178, on the last term yields v′ × c v′ × ∇φ c = v′ · ∇φ c v′ v′2 − 2 ∇φ c c (6.217)
which means that we can write F = −q∇ψ where ψ= 1− v′2 c2 φ (6.219) (6.218)
The scalar function ψ is called the convection potential or the Heaviside potential. When the rigid charge distribution is well localised so that we can use the potentials (6.214) the convection potential becomes ψ= 1− v′2 c2 q′ 4πε0 s (6.220)
The convection potential from a point charge is constant on flattened ellipsoids of revolution, defined through equation (6.212) on page 128 as x1 − x′ 1 √ + (x2 − x′ )2 + (x3 − x′ )2 2 3 1 − v′2 /c2 = γ2 (x1 − x′ )2 + (x2 − x′ )2 + (x3 − x′ )2 = Const 3 2 1
2
(6.221)
These Heaviside ellipsoids are equipotential surfaces, and since the force is proportional to the gradient of ψ, which means that it is perpendicular to the ellipsoid surface, the force between two charges is in general not directed along the line which connects the charges. A consequence of this is that a system consisting of two co-moving charges connected with a rigid bar, will experience a torque. This is the idea behind the Trouton-Noble experiment, aimed at measuring the absolute speed of the earth or the galaxy. The negative outcome of this experiment is explained by the special theory of relativity which postulates that mechanical laws follow the same rules as electromagnetic laws, so that a compensating torque appears due to mechanical stresses within the charge-bar system. ⊳ E ND OF EXAMPLE 6.3
Downloaded from
Version released 1st July 2008 at 20:49.
129
6. Electromagnetic Radiation and Radiating Systems
E XAMPLE 6.4
⊲ B REMSSTRAHLUNG FOR LOW SPEEDS AND SHORT ACCELERATION TIMES Calculate the bremsstrahlung when a charged particle, moving at a non-relativistic speed, is accelerated or decelerated during an infinitely short time interval. We approximate the velocity change at time t′ = t0 by a delta function: ˙ v′ (t′ ) = ∆v′ δ(t′ − t0 ) which means that ∆v′ (t0 ) =
∞ −∞
(6.222)
˙ dt′ v′
(6.223)
Also, we assume v/c ≪ 1 so that, according to formula (6.72) on page 95, s ≈ |x − x′ | and, according to formula (6.89) on page 100, x − x0 ≈ x − x′ (6.225) (6.224)
From the general expression (6.93) on page 101 we conclude that E ⊥ B and that it suffices to consider E ≡ Erad . According to the ‘bremsstrahlung expression’ for Erad , equation (6.112) on page 105, E= q′ sin θ′ ∆v′ δ(t′ − t0 ) 4πε0 c2 |x − x′ | E c (6.226)
In this simple case B ≡ Brad is given by B= (6.227)
Fourier transforming expression (6.226) for E is trivial, yielding Eω = q′ sin θ′ ∆v′ eiωt0 8π2 ε0 c2 |x − x′ | (6.228)
We note that the magnitude of this Fourier component is independent of ω. This is a consequence of the infinitely short ‘impulsive step’ δ(t′ − t0 ) in the time domain which produces an infinite spectrum in the frequency domain. The total radiation energy is given by the expression ˜ U rad =
∞ −∞ S′
dt′
˜ dU rad = dt′ dx
2 ′ ∞ ′ −∞ ∞ −∞
∞ −∞
dt′
S′
d2x′ n′ · E × ˆ
S′
B µ0 (6.229)
1 = µ0
dt EB = dt′ E 2
1 µ0 c
d2x′
∞ −∞
dt′ E 2
= ε0 c
S′
d2x′
According to Parseval’s identity [cf. equation (5.34) on page 75] the following equality holds:
130
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
∞ −∞
dt′ E 2 = 4π
0
∞
dω |Eω |2
(6.230)
which means that the radiated energy in the frequency interval (ω, ω + dω) is ˜ rad Uω dω = 4πε0 c d2x′ |Eω |2 dω (6.231)
S′
For our infinite spectrum, equation (6.228) on page 130, we obtain q′2 (∆v′ )2 ˜ rad Uω dω = 16π3 ε0 c3 = = q′ 2 (∆v′ )2 16π3 ε0 c3 q′2 3πε0 c d2x′ dϕ′
0 2
S′
2π 0
sin2 θ′ dω |x − x′ |2
π
dθ′ sin θ′ sin2 θ′ dω
(6.232)
∆v′ c
dω 2π
˜ rad We see that the energy spectrum Uω is independent of frequency ω. This means that if we would integrate it over all frequencies ω ∈ [0, ∞), a divergent integral would result. In reality, all spectra have finite widths, with an upper cutoff limit set by the quantum condition ωmax = 1 1 m(v′ + ∆v′ )2 − mv′2 2 2 (6.233)
which expresses that the highest possible frequency ωmax in the spectrum is that for which all kinetic energy difference has gone into one single field quantum (photon) with energy ωmax . If we adopt the picture that the total energy is quantised in terms of Nω photons radiated during the process, we find that ˜ rad Uω dω = dNω ω or, for an electron where q′ = − |e|, where e is the elementary charge, dNω = e2 2 4πε0 c 3π ∆v′ c
2 2
(6.234)
1 2 dω ≈ ω 137 3π
∆v′ c
dω ω
(6.235)
where we used the value of the fine structure constant α = e2 /(4πε0 c) ≈ 1/137. Even if the number of photons becomes infinite when ω → 0, these photons have negligible energies so that the total radiated energy is still finite. ⊳ E ND OF EXAMPLE 6.4
Downloaded from
Version released 1st July 2008 at 20:49.
131
Downloaded from
Version released 1st July 2008 at 20:49.
7
R ELATIVISTIC E LECTRODYNAMICS
We saw in chapter 3 how the derivation of the electrodynamic potentials led, in a most natural way, to the introduction of a characteristic, finite speed of propa√ gation in vacuum that equals the speed of light c = 1/ ε0 µ0 and which can be considered as a constant of nature. To take this finite speed of propagation of information into account, and to ensure that our laws of physics be independent of any specific coordinate frame, requires a treatment of electrodynamics in a relativistically covariant (coordinate independent) form. This is the object of this chapter.
7.1 The special theory of relativity
An inertial system, or inertial reference frame, is a system of reference, or rigid coordinate system, in which the law of inertia (Galileo’s law, Newton’s first law) holds. In other words, an inertial system is a system in which free bodies move uniformly and do not experience any acceleration. The special theory of relativity1 describes how physical processes are interrelated when observed in different
1 The Special Theory of Relativity, by the American physicist and philosopher David Bohm, opens with the following paragraph [4]:
‘The theory of relativity is not merely a scientific development of great importance in its own right. It is even more significant as the first stage of a radical change in our basic concepts, which began in physics, and which is spreading into other fields of science, and indeed, even into a great deal of thinking outside of science. For as is well known,
133
7. Relativistic Electrodynamics
inertial systems in uniform, rectilinear motion relative to each other and is based on two postulates: Postulate 7.1 (Relativity principle; Poincaré, 1905). All laws of physics (except the laws of gravitation) are independent of the uniform translational motion of the system on which they operate. Postulate 7.2 (Einstein, 1905). The velocity of light in empty space is independent of the motion of the source that emits the light. A consequence of the first postulate is that all geometrical objects (vectors, tensors) in an equation describing a physical process must transform in a covariant manner, i.e., in the same way.
7.1.1 The Lorentz transformation
Let us consider two three-dimensional inertial systems Σ and Σ′ in vacuum which are in rectilinear motion relative to each other in such a way that Σ′ moves with constant velocity v along the x axis of the Σ system. The times and the spatial coordinates as measured in the two systems are t and (x, y, z), and t′ and (x′ , y′ , z′ ), respectively. At time t = t′ = 0 the origins O and O′ and the x and x′ axes of the two inertial systems coincide and at a later time t they have the relative location as depicted in figure 7.1 on page 135, referred to as the standard configuration. For convenience, let us introduce the two quantities β= γ= v c 1 1 − β2 (7.1) (7.2)
where v = |v|. In the following, we shall make frequent use of these shorthand notations. As shown by Einstein, the two postulates of special relativity require that the spatial coordinates and times as measured by an observer in Σ and Σ′ , respectively,
the modern trend is away from the notion of sure ‘absolute’ truth, (i.e., one which holds independently of all conditions, contexts, degrees, and types of approximation etc..) and toward the idea that a given concept has significance only in relation to suitable broader forms of reference, within which that concept can be given its full meaning.’
134
Version released 1st July 2008 at 20:49.
Downloaded from
The special theory of relativity
vt y Σ Σ
′
y′ v P(t, x, y, z) P(t′ , x′ , y′ , z′ )
O z
x z′
O′
x′
F IGURE 7 .1 : Two inertial systems Σ and Σ′ in relative motion with velocity v along the x = x′ axis. At time t = t′ = 0 the origin O′ of Σ′ coincided with the origin O of Σ. At time t, the inertial system Σ′ has been translated a distance vt along the x axis in Σ. An event represented by P(t, x, y, z) in Σ is represented by P(t′ , x′ , y′ , z′ ) in Σ′ .
are connected by the following transformation: ct′ = γ(ct − xβ) y =y z =z
′
(7.3a) (7.3b) (7.3c) (7.3d)
x = γ(x − vt)
′
′
Taking the difference between the square of (7.3a) and the square of (7.3b) we find that c2 t′2 − x′2 = γ2 c2 t2 − 2xcβt + x2 β2 − x2 + 2xvt − v2 t2 = 1 v2 c2 2 2 = c t − x2 1− c2 t2 1 − v2 c2 − x2 1 − v2 c2 (7.4)
From equations (7.3) we see that the y and z coordinates are unaffected by the translational motion of the inertial system Σ′ along the x axis of system Σ. Using this fact, we find that we can generalise the result in equation (7.4) above to c2 t2 − x2 − y2 − z2 = c2 t′2 − x′2 − y′2 − z′2 (7.5)
which means that if a light wave is transmitted from the coinciding origins O and O′ at time t = t′ = 0 it will arrive at an observer at (x, y, z) at time t in Σ and an observer at (x′ , y′ , z′ ) at time t′ in Σ′ in such a way that both observers conclude that the speed (spatial distance divided by time) of light in vacuum is c. Hence, the
Downloaded from
Version released 1st July 2008 at 20:49.
135
7. Relativistic Electrodynamics
speed of light in Σ and Σ′ is the same. A linear coordinate transformation which has this property is called a (homogeneous) Lorentz transformation.
7.1.2 Lorentz space
Let us introduce an ordered quadruple of real numbers, enumerated with the help of upper indices µ = 0, 1, 2, 3, where the zeroth component is ct (c is the speed of light and t is time), and the remaining components are the components of the ordinary R3 radius vector x defined in equation (M.1) on page 182: xµ = (x0 , x1 , x2 , x3 ) = (ct, x, y, z) ≡ (ct, x) (7.6)
We want to interpret this quadruple xµ as (the component form of) a radius fourvector in a real, linear, four-dimensional vector space.2 We require that this fourdimensional space be a Riemannian space, i.e., a metric space where a ‘distance’ and a scalar product are defined. In this space we therefore define a metric tensor, also known as the fundamental tensor, which we denote by gµν .
Radius four-vector in contravariant and covariant form
The radius four-vector xµ = (x0 , x1 , x2 , x3 ) = (ct, x), as defined in equation (7.6) above, is, by definition, the prototype of a contravariant vector (or, more accurately, a vector in contravariant component form). To every such vector there exists a dual vector. The vector dual to xµ is the covariant vector xµ , obtained as xµ = gµν xν (7.7)
where the upper index µ in xµ is summed over and is therefore a dummy index and may be replaced by another dummy index ν This summation process is an example of index contraction and is often referred to as index lowering.
Scalar product and norm
The scalar product of xµ with itself in a Riemannian space is defined as gµν xν xµ = xµ xµ (7.8)
2 The British mathematician and philosopher Alfred North Whitehead writes in his book The Concept of Nature [13]:
‘I regret that it has been necessary for me in this lecture to administer a large dose of four-dimensional geometry. I do not apologise, because I am really not responsible for the fact that nature in its most fundamental aspect is four-dimensional. Things are what they are. . . .’
136
Version released 1st July 2008 at 20:49.
Downloaded from
The special theory of relativity
This scalar product acts as an invariant ‘distance’, or norm, in this space. To describe the physical property of Lorentz transformation invariance, described by equation (7.5) on page 135, in mathematical language it is convenient to perceive it as the manifestation of the conservation of the norm in a 4D Riemannian space. Then the explicit expression for the scalar product of xµ with itself in this space must be xµ xµ = c2 t2 − x2 − y2 − z2 (7.9)
We notice that our space will have an indefinite norm which means that we deal with a non-Euclidean space. We call the four-dimensional space (or space-time) with this property Lorentz space and denote it L4 . A corresponding real, linear 4D space with a positive definite norm which is conserved during ordinary rotations is a Euclidean vector space. We denote such a space R4 .
Metric tensor
By choosing the metric tensor in L4 as 1 if µ = ν = 0 gµν = −1 if µ = ν = i = j = 1, 2, 3 0 if µ ν or, in matrix notation, 1 0 0 0 0 −1 0 0 (gµν ) = 0 0 −1 0 0 0 0 −1
(7.10)
(7.11)
i.e., a matrix with a main diagonal that has the sign sequence, or signature, {+, −, −, −}, the index lowering operation in our chosen flat 4D space becomes nearly trivial: xµ = gµν xν = (ct, −x) Using matrix algebra, this can be written 0 0 x0 x 1 0 0 0 x x1 0 −1 0 0 x1 −x1 = x2 0 0 −1 0 x2 = −x2 −x3 x3 x3 0 0 0 −1 (7.12)
(7.13)
Hence, if the metric tensor is defined according to expression (7.10) above the covariant radius four-vector xµ is obtained from the contravariant radius four-vector
Downloaded from
Version released 1st July 2008 at 20:49.
137
7. Relativistic Electrodynamics
xµ simply by changing the sign of the last three components. These components are referred to as the space components; the zeroth component is referred to as the time component. As we see, for this particular choice of metric, the scalar product of xµ with itself becomes xµ xµ = (ct, x) · (ct, −x) = c2 t2 − x2 − y2 − z2 (7.14)
which indeed is the desired Lorentz transformation invariance as required by equation (7.9) on page 137. Without changing the physics, one can alternatively choose a signature {−, +, +, +}. The latter has the advantage that the transition from 3D to 4D becomes smooth, while it will introduce some annoying minus signs in the theory. In current physics literature, the signature {+, −, −, −} seems to be the most commonly used one. The L4 metric tensor equation (7.10) on page 137 has a number of interesting properties: firstly, we see that this tensor has a trace Tr gµν = −2 whereas in R4 , as in any vector space with definite norm, the trace equals the space dimensionality. Secondly, we find, after trivial algebra, that the following relations between the contravariant, covariant and mixed forms of the metric tensor hold: gµν = gνµ g
νκ µν κµ
(7.15a) (7.15b) = = δµ ν ν δµ (7.15c) (7.15d)
= gµν = gµ ν ν gµ
gνκ g
g gκµ =
Here we have introduced the 4D version of the Kronecker delta δµ , a mixed fourν tensor of rank 2 which fulfils δµ = δν = ν µ 1 if µ = ν 0 if µ ν (7.16)
Invariant line element and proper time
The differential distance ds between the two points xµ and xµ + dxµ in L4 can be calculated from the Riemannian metric, given by the quadratic differential form ds2 = gµν dxν dxµ = dxµ dxµ = (dx0 )2 − (dx1 )2 − (dx2 )2 − (dx3 )2 (7.17)
where the metric tensor is as in equation (7.10) on page 137. As we see, this form is indefinite as expected for a non-Euclidean space. The square root of this
138
Version released 1st July 2008 at 20:49.
Downloaded from
The special theory of relativity
expression is the invariant line element 1 c2 dx 1 dt
2
ds = c dt
1− 1−
+
dx 2 dt
2
+
dx 3 dt
2
= c dt = c dt
1 (v x )2 + (vy )2 + (vz )2 = c dt c2 dt 1 − β2 = c = c dτ γ
1−
v2 c2
(7.18)
where we introduced dτ = dt/γ (7.19)
Since dτ measures the time when no spatial changes are present, it is called the proper time. Expressing the property of the Lorentz transformation described by equations (7.5) on page 135 in terms of the differential interval ds and comparing with equation (7.17) on page 138, we find that ds2 = c2 dt2 − dx2 − dy2 − dz2 (7.20)
is invariant, i.e., remains unchanged, during a Lorentz transformation. Conversely, we may say that every coordinate transformation which preserves this differential interval is a Lorentz transformation. If in some inertial system dx2 + dy2 + dz2 < c2 dt2 ds is a time-like interval, but if dx2 + dy2 + dz2 > c2 dt2 ds is a space-like interval, whereas dx2 + dy2 + dz2 = c2 dt2 (7.23) (7.22) (7.21)
is a light-like interval; we may also say that in this case we are on the light cone. A vector which has a light-like interval is called a null vector. The time-like, space-like or light-like aspects of an interval ds are invariant under a Lorentz transformation. I.e., it is not possible to change a time-like interval into a spacelike one or vice versa via a Lorentz transformation.
Downloaded from
Version released 1st July 2008 at 20:49.
139
7. Relativistic Electrodynamics
Four-vector fields
Any quantity which relative to any coordinate system has a quadruple of real numbers and transforms in the same way as the radius four-vector xµ does, is called a four-vector. In analogy with the notation for the radius four-vector we introduce the notation aµ = (a0 , a) for a general contravariant four-vector field in L4 and find that the ‘lowering of index’ rule, formula (7.7) on page 136, for such an arbitrary four-vector yields the dual covariant four-vector field aµ (xκ ) = gµν aν (xκ ) = (a0 (xκ ), −a(xκ )) The scalar product between this four-vector field and another one bµ (xκ ) is gµν aν (xκ )bµ (xκ ) = (a0 , −a) · (b0 , b) = a0 b0 − a · b (7.25) (7.24)
which is a scalar field, i.e., an invariant scalar quantity α(xκ ) which depends on time and space, as described by xκ = (ct, x, y, z).
The Lorentz transformation matrix
Introducing the transformation matrix γ −βγ 0 0 −βγ γ 0 0 Λµν = 0 0 1 0 0 0 0 1
(7.26)
the linear Lorentz transformation (7.3) on page 135, i.e., the coordinate transformation xµ → x′µ = x′µ (x0 , x1 , x2 , x3 ), from one inertial system Σ to another inertial system Σ′ in the standard configuration, can be written x′µ = Λµν xν (7.27)
The Lorentz group
It is easy to show, by means of direct algebra, that two successive Lorentz transformations of the type in equation (7.27) above, and defined by the speed parameters β1 and β2 , respectively, correspond to a single transformation with speed parameter β= β1 + β2 1 + β1 β2 (7.28)
This means that the nonempty set of Lorentz transformations constitutes a closed algebraic structure with a binary operation which is associative. Furthermore,
140
Version released 1st July 2008 at 20:49.
Downloaded from
The special theory of relativity
X0 X
′0
θ x′1 θ x1
F IGURE 7 .2 : Minkowski space can be considered an ordinary Euclidean space where a Lorentz transformation from (x1 , X 0 = ict) to (x′1 , X ′0 = ict′ ) corresponds to an ordinary rotation through an angle θ. This rotation leaves the Euclidean 2 2 distance x1 + X 0 = x2 − c2 t2 invariant.
one can show that this set possesses at least one identity element and at least one inverse element. In other words, this set of Lorentz transformations constitutes a mathematical group. However tempting, we shall not make any further use of group theory.
7.1.3 Minkowski space
Specifying a point xµ = (x0 , x1 , x2 , x3 ) in 4D space-time is a way of saying that ‘something takes place at a certain time t = x0 /c and at a certain place (x, y, z) = (x1 , x2 , x3 )’. Such a point is therefore called an event. The trajectory for an event as a function of time and space is called a world line. For instance, the world line for a light ray which propagates in vacuum is the trajectory x0 = x1 . Introducing X 0 = ix0 = ict X =x X =x X =x
3 2 1 1 2 3
(7.29a) (7.29b) (7.29c) (7.29d) (7.29e)
dS = ids where i = √ −1, we see that equation (7.17) on page 138 transforms into
dS 2 = (dX 0 )2 + (dX 1 )2 + (dX 2 )2 + (dX 3 )2
(7.30)
Downloaded from
Version released 1st July 2008 at 20:49.
141
7. Relativistic Electrodynamics
Σ x = ct
0
w x′0 x0 = x1
ϕ
P′ ϕ O=O
′
x′1 ct
P
x1 = x
F IGURE 7 .3 : Minkowski diagram depicting geometrically the transformation (7.33) from the unprimed system to the primed system. Here w denotes the world line for an event and the line x0 = x1 ⇔ x = ct the world line for a light ray in vacuum. Note that the event P is simultaneous with all points on the x1 axis (t = 0), including the origin O. The event P′ , which is simultaneous with all points on the x′ axis, including O′ = O, to an observer at rest in the primed system, is not simultaneous with O in the unprimed system but occurs there at time |P − P′ | /c.
i.e., into a 4D differential form which is positive definite just as is ordinary 3D Euclidean space R3 . We shall call the 4D Euclidean space constructed in this way the Minkowski space M4 .3 As before, it suffices to consider the simplified case where the relative motion between Σ and Σ′ is along the x axes. Then dS 2 = (dX 0 )2 + (dX 1 )2 = (dX 0 )2 + (dx1 )2 (7.31)
and we consider the X 0 and X 1 = x1 axes as orthogonal axes in a Euclidean space. As in all Euclidean spaces, every interval is invariant under a rotation of the X 0 x1 plane through an angle θ into X ′0 x′1 : X ′0 = −x1 sin θ + X 0 cos θ x = x cos θ + X sin θ
′1 1 0
(7.32a) (7.32b)
See figure 7.2 on page 141. If we introduce the angle ϕ = −iθ, often called the rapidity or the Lorentz boost parameter, and transform back to the original space and time variables by
fact that our Riemannian space can be transformed in this way into a Euclidean one means that it is, strictly speaking, a pseudo-Riemannian space.
3 The
142
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant classical mechanics
using equation (7.29) on page 141 backwards, we obtain ct′ = −x sinh ϕ + ct cosh ϕ x = x cosh ϕ − ct sinh ϕ
′
(7.33a) (7.33b)
which are identical to the transformation equations (7.3) on page 135 if we let sinh ϕ = γβ cosh ϕ = γ tanh ϕ = β (7.34a) (7.34b) (7.34c)
It is therefore possible to envisage the Lorentz transformation as an ‘ordinary’ rotation in the 4D Euclidean space M4 . Such a rotation in M4 corresponds to a coordinate change in L4 as depicted in figure 7.3 on page 142. equation (7.28) on page 140 for successive Lorentz transformation then corresponds to the tanh addition formula tanh(ϕ1 + ϕ2 ) = tanh ϕ1 + tanh ϕ2 1 + tanh ϕ1 tanh ϕ2 (7.35)
The use of ict and M4 , which leads to the interpretation of the Lorentz transformation as an ‘ordinary’ rotation, may, at best, be illustrative, but is not very physical. Besides, if we leave the flat L4 space and enter the curved space of general relativity, the ‘ict’ trick will turn out to be an impasse. Let us therefore immediately return to L4 where all components are real valued.
7.2 Covariant classical mechanics
The invariance of the differential ‘distance’ ds in L4 , and the associated differential proper time dτ [see equation (7.18) on page 139] allows us to define the four-velocity µ c dx v = (u0 , u) uµ = = γ(c, v) = , (7.36) 2 dτ v v2 1− 1−
c2 c2
which, when multiplied with the scalar invariant m0 yields the four-momentum m0 c m0 v dx µ = m0 γ(c, v) = = (p0 , p) (7.37) , pµ = m0 dτ v2 v2 1− 1−
c2 c2
Downloaded from
Version released 1st July 2008 at 20:49.
143
7. Relativistic Electrodynamics
From this we see that we can write p = mv where m = γm0 = m0 1−
v2 c2
(7.38)
(7.39)
We can interpret this such that the Lorentz covariance implies that the mass-like term in the ordinary 3D linear momentum is not invariant. A better way to look at this is that p = mv = γm0 v is the covariantly correct expression for the kinetic three-momentum. Multiplying the zeroth (time) component of the four-momentum pµ with the scalar invariant c, we obtain cp0 = γm0 c2 = m0 c2 1−
v2 c2
= mc2
(7.40)
Since this component has the dimension of energy and is the result of a covariant description of the motion of a particle with its kinetic momentum described by the spatial components of the four-momentum, equation (7.37) on page 143, we interpret cp0 as the total energy E. Hence, cpµ = (cp0 , cp) = (E, cp) Scalar multiplying this four-vector with itself, we obtain cpµ cpµ = c2 gµν pν pµ = c2 [(p0 )2 − (p1 )2 − (p2 )2 − (p3 )2 ] (m0 c2 )2 = v2 1 − c2 = (E, −cp) · (E, cp) = E 2 − c2 p2 v2 1− 2 c = (m0 c )
2 2
(7.41)
(7.42)
Since this is an invariant, this equation holds in any inertial frame, particularly in the frame where p = 0 and there we have E = m0 c2 This is probably the most famous formula in physics history. (7.43)
144
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant classical electrodynamics
7.3 Covariant classical electrodynamics
Let us consider a charge density which in its rest inertial system is denoted by ρ0 . The four-vector (in contravariant component form) dxµ = ρ0 uµ = ρ0 γ(c, v) = (ρc, ρv) dτ where we introduced jµ = ρ0 ρ = γρ0 (7.44)
(7.45)
is called the four-current. The contravariant form of the four-del operator ∂µ = ∂/∂xµ is defined in equation (M.37) on page 189 and its covariant counterpart ∂µ = ∂/∂xµ in equation (M.38) on page 189, respectively. As is shown in example M.5 on page 199, the d’Alembert operator is the scalar product of the four-del with itself: 1 ∂2 − ∇2 (7.46) c2 ∂t2 Since it has the characteristics of a four-scalar, the d’Alembert operator is invariant and, hence, the homogeneous wave equation 2 f (t, x) = 0 is Lorentz covariant.
2
= ∂µ ∂µ = ∂µ ∂µ =
7.3.1 The four-potential
If we introduce the four-potential Aµ = φ ,A c (7.47)
where φ is the scalar potential and A the vector potential, defined in section 3.3 on page 40, we can write the uncoupled inhomogeneous wave equations, equations (3.16) on page 43, in the following compact (and covariant) way:
2 µ
A = µ0 jµ
(7.48)
With the help of the above, we can formulate our electrodynamic equations covariantly. For instance, the covariant form of the equation of continuity, equation (1.23) on page 10 is ∂µ jµ = 0 (7.49)
and the Lorenz-Lorentz gauge condition, equation (3.15) on page 43, can be written ∂µ Aµ = 0 (7.50)
Downloaded from
Version released 1st July 2008 at 20:49.
145
7. Relativistic Electrodynamics
The gauge transformations (3.11) on page 42 in covariant form are Aµ → A′µ = Aµ + ∂µ Γ(xν ) (7.51)
If only one dimension Lorentz contracts (for instance, due to relative motion along the x direction), a 3D spatial volume element transforms according to dV = d3x = 1 dV0 = dV0 γ 1 − β2 = dV0 1− v2 c2 (7.52)
where dV0 denotes the volume element as measured in the rest system, then from equation (7.45) on page 145 we see that ρdV = ρ0 dV0 (7.53)
i.e., the charge in a given volume is conserved. We can therefore conclude that the elementary charge is a universal constant.
7.3.2 The Liénard-Wiechert potentials
Let us now solve the the inhomogeneous wave equations (3.16) on page 43 in vacuum for the case of a well-localised charge q′ at a source point defined by the radius four-vector x′µ ≡ (x′0 = ct′ , x′1 , x′2 , x′3 ). The field point (observation point) is denoted by the radius four-vector xµ = (x0 = ct, x1 , x2 , x3 ). In the rest system we know that the solution is simply (Aµ )0 = φ ,A c =
v=0
1 q′ ,0 4πε0 c |x − x′ |0
(7.54)
where |x − x′ |0 is the usual distance from the source point to the field point, evaluated in the rest system (signified by the index ‘0’). Let us introduce the relative radius four-vector between the source point and the field point: Rµ = xµ − x′µ = (c(t − t′ ), x − x′ ) Scalar multiplying this relative four-vector with itself, we obtain Rµ Rµ = (c(t − t′ ), x − x′ ) · (c(t − t′ ), −(x − x′ )) = c2 (t − t′ )2 − x − x′
2
(7.55)
(7.56)
We know that in vacuum the signal (field) from the charge q′ at x′µ propagates to xµ with the speed of light c so that x − x′ = c(t − t′ ) (7.57)
146
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant classical electrodynamics
Inserting this into equation (7.56) on page 146, we see that Rµ Rµ = 0 or that equation (7.55) on page 146 can be written Rµ = ( x − x′ , x − x′ ) (7.59) (7.58)
Now we want to find the correspondence to the rest system solution, equation (7.54) on page 146, in an arbitrary inertial system. We note from equation (7.36) on page 143 that in the rest system c v = (c, 0) (uµ )0 = , (7.60) v2 v2 1 − c2 1 − c2
v=0
and
(Rµ )0 = ( x − x′ , x − x′ )0 = ( x − x′ 0 , (x − x′ )0 )
(7.61)
As all scalar products, uµ Rµ is invariant, which means that we can evaluate it in any inertial system and it will have the same value in all other inertial systems. If we evaluate it in the rest system the result is: uµ Rµ = uµ Rµ
0
= (uµ )0 (Rµ )0
0
= (c, 0) · ( x − x′ 0 , −(x − x′ )0 ) = c x − x′ We therefore see that the expression Aµ = q′ uµ 4πε0 cuν Rν
(7.62)
(7.63)
subject to the condition Rµ Rµ = 0 has the proper transformation properties (proper tensor form) and reduces, in the rest system, to the solution equation (7.54) on page 146. It is therefore the correct solution, valid in any inertial system. According to equation (7.36) on page 143 and equation (7.59) uν Rν = γ(c, v) ·
def
x − x′ , −(x − x′ ) = γ c x − x′ − v · (x − x′ )
(7.64)
Generalising expression (7.1) on page 134 to vector form: β = βv ≡ ˆ and introducing s ≡ x − x′ −
def
v c v · (x − x′ ) ≡ x − x′ − β · (x − x′ ) c
(7.65)
(7.66)
Downloaded from
Version released 1st July 2008 at 20:49.
147
7. Relativistic Electrodynamics
we can write uν Rν = γcs and uµ = cuν Rν 1 v , cs c2 s (7.68) (7.67)
from which we see that the solution (7.63) can be written Aµ (xκ ) = q′ 4πε0 1 v , cs c2 s = φ ,A c (7.69)
where in the last step the definition of the four-potential, equation (7.47) on page 145, was used. Writing the solution in the ordinary 3D way, we conclude that for a very localised charge volume, moving relative an observer with a velocity v, the scalar and vector potentials are given by the expressions q′ 1 q′ 1 = ′ | − β · (x − x′ ) 4πε0 s 4πε0 |x − x q′ v q′ v = A(t, x) = 2 s 2 |x − x′ | − β · (x − x′ ) 4πε0 c 4πε0 c φ(t, x) = (7.70a) (7.70b)
These potentials are the Liénard-Wiechert potentials that we derived in a more complicated and restricted way in subsection 6.3.1 on page 94.
7.3.3 The electromagnetic field tensor
Consider a vectorial (cross) product c between two ordinary vectors a and b: c = a × b = ǫi jk ai b j xk ˆ = (a2 b3 − a3 b2 ) x1 + (a3 b1 − a1 b3 ) x2 + (a1 b2 − a2 b1 ) x3 ˆ ˆ ˆ We notice that the kth component of the vector c can be represented as ck = ai b j − a j bi = ci j = −c ji , i, j k (7.72) (7.71)
In other words, the pseudovector c = a × b can be considered as an antisymmetric tensor of rank two. The same is true for the curl operator ∇× operating on a polar vector. For instance, the Maxwell equation ∇×E=− ∂B ∂t (7.73)
148
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant classical electrodynamics
can in this tensor notation be written ∂E j ∂Ei ∂Bi j − j =− ∂xi ∂x ∂t (7.74)
We know from chapter 3 that the fields can be derived from the electromagnetic potentials in the following way: B=∇×A E = −∇φ − ∂A ∂t (7.75a) (7.75b)
In component form, this can be written Bi j = ∂A j ∂Ai − = ∂i A j − ∂ j Ai ∂xi ∂x j ∂φ ∂Ai = −∂i φ − ∂t Ai Ei = − i − ∂x ∂t (7.76a) (7.76b)
From this, we notice the clear difference between the axial vector (pseudovector) B and the polar vector (‘ordinary vector’) E. Our goal is to express the electric and magnetic fields in a tensor form where the components are functions of the covariant form of the four-potential, equation (7.47) on page 145: Aµ = φ ,A c (7.77)
Inspection of (7.77) and equation (7.76) above makes it natural to define the fourtensor F µν = ∂Aν ∂Aµ − = ∂µ Aν − ∂ν Aµ ∂xµ ∂xν (7.78)
This anti-symmetric (skew-symmetric), four-tensor of rank 2 is called the electromagnetic field tensor. In matrix representation, the contravariant field tensor can be written 0 −E x /c −Ey /c −Ez /c E /c 0 −Bz By (F µν ) = x (7.79) Ey /c Bz 0 −Bx Ez /c −By Bx 0 We note that the field tensor is a sort of four-dimensional curl of the four-potential vector Aµ .
Downloaded from
Version released 1st July 2008 at 20:49.
149
7. Relativistic Electrodynamics
The covariant field tensor is obtained from the contravariant field tensor in the usual manner by index lowering Fµν = gµκ gνλ F κλ = ∂µ Aν − ∂ν Aµ which in matrix representation becomes 0 E x /c Ey /c −E x /c 0 −Bz Fµν = −Ey /c Bz 0 −Ez /c −By Bx Ez /c By −Bx 0 (7.80)
(7.81)
Comparing formula (7.81) with formula (7.79) on page 149 we see that the covariant field tensor is obtained from the contravariant one by a transformation E → −E. That the two Maxwell source equations can be written ∂µ F µν = µ0 jν (7.82)
is immediately observed by explicitly solving this covariant equation. Setting ν = 0, corresponding to the first/leftmost column in the matrix representation of the covariant component form of the electromagnetic field tensor, F µν , i.e., equation (7.79) on page 149, we see that 1 ∂F 00 ∂F 10 ∂F 20 ∂F 30 + + + =0+ 0 1 2 3 ∂x ∂x ∂x ∂x c 1 = ∇ · E = µ0 j0 = µ0 cρ c or, equivalently (recalling that ε0 µ0 = 1/c2 ), ∇·E= ρ ε0 (7.84) ∂E x ∂Ey ∂Ez + + ∂x ∂y ∂z
(7.83)
which we recognise at the Maxwell source equation for the electric field, equation (1.45a) on page 15. For ν = 1 (the second column in equation (7.79) on page 149), equation (7.82) above yields ∂F 01 ∂F 11 ∂F 21 ∂F 31 1 ∂E x ∂Bz ∂By + + + =− 2 +0+ − = µ0 j1 = µ0 ρv x ∂x0 ∂x1 ∂x2 ∂x3 c ∂t ∂y ∂z (7.85) This result can be rewritten as ∂Bz ∂By ∂E x − − ε0 µ0 = µ0 j x ∂y ∂z ∂t (7.86)
150
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant classical electrodynamics
or, equivalently, as (∇ × B) x = µ0 j x + ε0 µ0 ∂E x ∂t (7.87)
and similarly for ν = 2, 3. In summary, we can write the result in three-vector form as ∇ × B = µ0 j(t, x) + ε0 µ0 ∂E ∂t (7.88)
which can be viewed as a generalisation of the Levi-Civita tensor, formula (M.18) on page 185, we can introduce the dual electromagnetic tensor
⋆ µν
which we recognise as the Maxwell source equation for the magnetic field, equation (1.45d) on page 15. With the help of the fully antisymmetric rank-4 pseudotensor 1 if µ, ν, κ, λ is an even permutation of 0,1,2,3 µνκλ (7.89) ǫ = 0 if at least two of µ, ν, κ, λ are equal −1 if µ, ν, κ, λ is an odd permutation of 0,1,2,3 F = ǫ µνκλ Fκλ (7.90)
In matrix form the dual field tensor is 0 −cBx −cBy cBx 0 Ez ⋆ µν F = cBy −Ez 0 cBz Ey −E x
i.e., the dual field tensor is obtained from the ordinary field tensor by the duality transformation E → c2 B and B → −E. The covariant form of the two Maxwell field equations ∇×E=− ∇·B=0 ∂B ∂t (7.92) (7.93)
−cBz −Ey Ex 0
(7.91)
can then be written ∂µ ⋆F µν = 0 Explicit evaluation shows that this corresponds to (no summation!) ∂κ Fµν + ∂µ Fνκ + ∂ν Fκµ = 0 (7.95) (7.94)
Downloaded from
Version released 1st July 2008 at 20:49.
151
7. Relativistic Electrodynamics
sometimes referred to as the Jacobi identity. Hence, equation (7.82) on page 150 and equation (7.95) on page 151 constitute Maxwell’s equations in four-dimensional formalism. It is interesting to note that equation (7.82) on page 150 and ∂µ ⋆F µν = µ0 jν m (7.96)
where jm is the magnetic four-current, represent the covariant form of Dirac’s symmetrised Maxwell equations (1.50) on page 16.
7.4 Bibliography
[1] [2] [3] [4] [5] [6]
J. A HARONI, The Special Theory of Relativity, second, revised ed., Dover Publications, Inc., New York, 1985, ISBN 0-486-64870-2. A. O. B ARUT, Electrodynamics and Classical Theory of Fields and Particles, Dover Publications, Inc., New York, NY, 1980, ISBN 0-486-64038-8. R. B ECKER, Electromagnetic Fields and Interactions, Dover Publications, Inc., New York, NY, 1982, ISBN 0-486-64290-9. D. B OHM, The Special Theory of Relativity, Routledge, New York, NY, 1996, ISBN 0415-14809-X. 133 W. T. G RANDY, Introduction to Electrodynamics and Radiation, Academic Press, New York and London, 1970, ISBN 0-12-295250-2.. H. M UIRHEAD, The Special Theory of Relativity, The Macmillan Press Ltd., London, Beccles and Colchester, 1973, ISBN 333-12845-1. C. M ØLLER, The Theory of Relativity, second ed., Oxford University Press, Glasgow . . . ,
[7] [8] [9]
1972. [10] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026. [11] J. J. S AKURAI, Advanced Quantum Mechanics, Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1967, ISBN 0-201-06710-2.
152
Version released 1st July 2008 at 20:49.
Downloaded from
Bibliography
[12] B. S PAIN, Tensor Calculus, third ed., Oliver and Boyd, Ltd., Edinburgh and London, 1965, ISBN 05-001331-9. [13] A. N. W HITEHEAD, Concept of Nature, Cambridge University Press, Cambridge . . . , 1920, ISBN 0-521-09245-0. 136
Downloaded from
Version released 1st July 2008 at 20:49.
153
Downloaded from
Version released 1st July 2008 at 20:49.
8
E LECTROMAGNETIC F IELDS AND PARTICLES
In previous chapters, we calculated the electromagnetic fields and potentials from arbitrary, but prescribed distributions of charges and currents. In this chapter we study the general problem of interaction between electric and magnetic fields and electrically charged particles. The analysis is based on Lagrangian and Hamiltonian methods, is fully covariant, and yields results which are relativistically correct.
8.1 Charged particles in an electromagnetic field
We first establish a relativistically correct theory describing the motion of charged particles in prescribed electric and magnetic fields. From these equations we may then calculate the charged particle dynamics in the most general case.
8.1.1 Covariant equations of motion
We will show that for our problem we can derive the correct equations of motion by using in four-dimensional L4 a function with similar properties as a Lagrange function in 3D and then apply a variational principle. We will also show that we can find a Hamiltonian-type function in 4D and solve the corresponding Hamilton-type equations to obtain the correct covariant formulation of classical electrodynamics.
155
8. Electromagnetic Fields and Particles
Lagrangian formalism
Let us now introduce a generalised action S4 = L4 (xµ , uµ ) dτ (8.1)
where dτ is the proper time defined via equation (7.18) on page 139, and L4 acts as a kind of generalisation to the common 3D Lagrangian so that the variational principle
τ1
δS 4 = δ
τ0
L4 (xµ , uµ ) dτ = 0
(8.2)
with fixed endpoints τ0 , τ1 is fulfilled. We require that L4 is a scalar invariant which does not contain higher than the second power of the four-velocity uµ in order that the equations of motion be linear. According to formula (M.48) on page 191 the ordinary 3D Lagrangian is the difference between the kinetic and potential energies. A free particle has only kinetic energy. If the particle mass is m0 then in 3D the kinetic energy is m0 v2 /2. This suggests that in 4D the Lagrangian for a free particle should be
free L4 =
1 m0 uµ uµ 2
(8.3)
For an interaction with the electromagnetic field we can introduce the interaction with the help of the four-potential given by equation (7.77) on page 149 in the following way L4 = 1 m0 uµ uµ + quµ Aµ (xν ) 2 (8.4)
We call this the four-Lagrangian and shall now show how this function, together with the variation principle, formula (8.2) above, yields covariant results which are physically correct. The variation principle (8.2) with the 4D Lagrangian (8.4) inserted, leads to δS 4 = δ m0 µ u uµ + quµ Aµ (xν ) dτ 2 τ0 τ1 m ∂(uµ u ) ∂Aµ µ 0 δuµ + q Aµ δuµ + uµ ν δxν = µ 2 ∂u ∂x τ0
τ1 τ1
dτ
(8.5)
=
τ0
m0 uµ δuµ + q Aµ δuµ + uµ ∂ν Aµ δxν
dτ = 0
According to equation (7.36) on page 143, the four-velocity is uµ = dx µ dτ (8.6)
156
Version released 1st July 2008 at 20:49.
Downloaded from
Charged particles in an electromagnetic field
which means that we can write the variation of uµ as a total derivative with respect to τ : δuµ = δ dx µ dτ = d (δxµ ) dτ (8.7)
Inserting this into the first two terms in the last integral in equation (8.5) on page 156, we obtain
τ1
δS 4 =
τ0
m0 uµ
d d (δxµ ) + qAµ (δxµ ) + quµ ∂ν Aµ δxν dτ dτ dτ
(8.8)
Partial integration in the two first terms in the right hand member of (8.8) gives
τ1
δS 4 =
τ0
−m0
duµ µ dAµ µ δx − q δx + quµ ∂ν Aµ δxν dτ dτ dτ
(8.9)
where the integrated parts do not contribute since the variations at the endpoints vanish. A change of irrelevant summation index from µ to ν in the first two terms of the right hand member of (8.9) yields, after moving the ensuing common factor δxν outside the parenthesis, the following expression:
τ1
δS 4 =
τ0
−m0
dAν duν −q + quµ ∂ν Aµ δxν dτ dτ dτ
(8.10)
Applying well-known rules of differentiation and the expression (7.36) for the four-velocity, we can express dAν /dτ as follows: dAν ∂Aν dxµ = µ = ∂µ Aν uµ dτ ∂x dτ (8.11)
By inserting this expression (8.11) into the second term in right-hand member of equation (8.10), and noting the common factor quµ of the resulting term and the last term, we obtain the final variational principle expression
τ1
δS 4 =
τ0
−m0
duν + quµ ∂ν Aµ − ∂µ Aν dτ
δxν dτ
(8.12)
Since, according to the variational principle, this expression shall vanish and δxν is arbitrary between the fixed end points τ0 and τ1 , the expression inside in the integrand in the right hand member of equation (8.12) above must vanish. In other words, we have found an equation of motion for a charged particle in a prescribed electromagnetic field: m0 duν = quµ ∂ν Aµ − ∂µ Aν dτ (8.13)
Downloaded from
Version released 1st July 2008 at 20:49.
157
8. Electromagnetic Fields and Particles
With the help of formula (7.80) on page 150 for the covariant component form of the field tensor, we can express this equation in terms of the electromagnetic field tensor in the following way: m0 duν = quµ Fνµ dτ (8.14)
This is the sought-for covariant equation of motion for a particle in an electromagnetic field. It is often referred to as the Minkowski equation. As the reader can easily verify, the spatial part of this 4-vector equation is the covariant (relativistically correct) expression for the Newton-Lorentz force equation.
Hamiltonian formalism
The usual Hamilton equations for a 3D space are given by equation (M.59) on page 192 in appendix M. These six first-order partial differential equations are ∂H dqi = ∂pi dt dpi ∂H =− ∂qi dt (8.15a) (8.15b)
where H(pi , qi , t) = pi qi − L(qi , qi , t) is the ordinary 3D Hamiltonian, qi is a gen˙ ˙ eralised coordinate and pi is its canonically conjugate momentum. We seek a similar set of equations in 4D space. To this end we introduce a canonically conjugate four-momentum pµ in an analogous way as the ordinary 3D conjugate momentum: pµ = ∂L4 ∂uµ (8.16)
and utilise the four-velocity uµ , as given by equation (7.36) on page 143, to define the four-Hamiltonian H4 = pµ uµ − L4 (8.17)
With the help of these, the radius four-vector xµ , considered as the generalised four-coordinate, and the invariant line element ds, defined in equation (7.18) on page 139, we introduce the following eight partial differential equations: ∂H4 dxµ = ∂pµ dτ dpµ ∂H4 =− µ ∂x dτ (8.18a) (8.18b)
158
Version released 1st July 2008 at 20:49.
Downloaded from
Charged particles in an electromagnetic field
which form the four-dimensional Hamilton equations. Our strategy now is to use equation (8.16) on page 158 and equations (8.18) on page 158 to derive an explicit algebraic expression for the canonically conjugate momentum four-vector. According to equation (7.41) on page 144, c times a fourmomentum has a zeroth (time) component which we can identify with the total energy. Hence we require that the component p0 of the conjugate four-momentum vector defined according to equation (8.16) on page 158 be identical to the ordinary 3D Hamiltonian H divided by c and hence that this cp0 solves the Hamilton equations, equations (8.15) on page 158. This later consistency check is left as an exercise to the reader. Using the definition of H4 , equation (8.17) on page 158, and the expression for L4 , equation (8.4) on page 156, we obtain 1 (8.19) H4 = pµ uµ − L4 = pµ uµ − m0 uµ uµ − quµ Aµ (xν ) 2 Furthermore, from the definition (8.16) of the canonically conjugate four-momentum pµ , we see that pµ = ∂L4 ∂ = ∂uµ ∂uµ 1 m0 uµ uµ + quµ Aµ (xν ) 2 = m0 uµ + qAµ (8.20)
Inserting this into (8.19), we obtain 1 1 H4 = m0 uµ uµ + qAµ uµ − m0 uµ uµ − quµ Aµ (xν ) = m0 uµ uµ 2 2 (8.21)
Since the four-velocity scalar-multiplied by itself is uµ uµ = c2 , we clearly see from equation (8.21) above that H4 is indeed a scalar invariant, whose value is simply m0 c2 2 However, at the same time (8.20) provides the algebraic relationship H4 = uµ = 1 µ (p − qAµ ) m0 1 1 µ (p − qAµ ) pµ − qAµ m0 m0 (pµ − qAµ ) pµ − qAµ pµ pµ − 2qAµ pµ + q2 Aµ Aµ (8.24) (8.22)
(8.23)
and if this is used in (8.21) to eliminate uµ , one gets H4 = m0 2 1 = 2m0 1 = 2m0
Downloaded from
Version released 1st July 2008 at 20:49.
159
8. Electromagnetic Fields and Particles
That this four-Hamiltonian yields the correct covariant equation of motion can be seen by inserting it into the four-dimensional Hamilton’s equations (8.18) and using the relation (8.23): ∂H4 q ∂Aν = − (pν − qAν ) µ µ ∂x m0 ∂x q ν ∂Aν = − m0 u m0 ∂xµ ∂Aν = −quν µ ∂x dpµ duµ ∂Aµ =− = −m0 − q ν uν dτ dτ ∂x
(8.25)
where in the last step equation (8.20) on page 159 was used. Rearranging terms, and using equation (7.80) on page 150, we obtain m0 duµ = quν ∂µ Aν − ∂ν Aµ = quν Fµν dτ (8.26)
which is identical to the covariant equation of motion equation (8.14) on page 158. We can then safely conclude that the Hamiltonian in question is correct. Recalling expression (7.47) on page 145 for the four-potential, and representing the canonically conjugate four-momentum as pµ = (p0 , p), we obtain the following scalar products: pµ pµ = (p0 )2 − (p)2 1 Aµ pµ = φp0 − (p · A) c 1 µ A Aµ = 2 φ2 − (A)2 c (8.27a) (8.27b) (8.27c)
Inserting these explicit expressions into equation (8.24) on page 159, and using the fact that for H4 is equal to the scalar value m0 c2 /2, as derived in equation (8.22) on page 159, we obtain the equation m0 c2 1 = 2 2m0 2 q2 (p0 )2 − (p)2 − qφp0 + 2q(p · A) + 2 φ2 − q2 (A)2 c c (8.28)
which is the second order algebraic equation in p0 : (p0 )2 − q2 2q 0 φp − (p)2 − 2qp · A + q2 (A)2 + 2 φ2 − m2 c2 = 0 0 c c
(p−qA)2
(8.29)
160
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant field theory
with two possible solutions q (8.30) φ ± (p − qA)2 + m2 c2 0 c Since the zeroth component (time component) p0 of a four-momentum vector pµ multiplied by c represents the energy [cf. equation (7.41) on page 144], the positive solution in equation (8.30) above must be identified with the ordinary Hamilton function H divided by c. Consequently, p0 = H ≡ cp0 = qφ + c (p − qA)2 + m2 c2 0 (8.31)
is the ordinary 3D Hamilton function for a charged particle moving in scalar and vector potentials associated with prescribed electric and magnetic fields. The ordinary Lagrange and Hamilton functions L and H are related to each other by the 3D transformation [cf. the 4D transformation (8.17) between L4 and H4 ] L =p·v−H (8.32)
Using the explicit expressions (equation (8.31)) and (equation (8.32) above), we obtain the explicit expression for the ordinary 3D Lagrange function L = p · v − qφ − c (p − qA)2 + m2 c2 0 (8.33)
and if we make the identification m0 v p − qA = = mv v2 1 − c2
(8.34)
where the quantity mv is the usual kinetic momentum, we can rewrite this expression for the ordinary Lagrangian as follows: L = qA · v + mv2 − qφ − c m2 v2 + m2 c2 0 1−
(8.35) v2 c2 What we have obtained is the relativistically correct (covariant) expression for the Lagrangian describing the motion of a charged particle in scalar and vector potentials associated with prescribed electric and magnetic fields. = mv2 − q(φ − A · v) − mc2 = −qφ + qA · v − m0 c2
8.2 Covariant field theory
So far, we have considered two classes of problems. Either we have calculated the fields from given, prescribed distributions of charges and currents, or we have
Downloaded from
Version released 1st July 2008 at 20:49.
161
8. Electromagnetic Fields and Particles
ηi−1 m m m
ηi
ηi+1 m m x
k a
k a
k a
k a
F IGURE 8 .1 : A one-dimensional chain consisting of N discrete, identical mass points m, connected to their neighbours with identical, ideal springs with spring constants k. The equilibrium distance between the neighbouring mass points is a and ηi−1 (t), ηi (t), ηi+1 (t) are the instantaneous deviations, along the x axis, of positions of the (i − 1)th, ith, and (i + 1)th mass point, respectively.
derived the equations of motion for charged particles in given, prescribed fields. Let us now put the fields and the particles on an equal footing and present a theoretical description which treats the fields, the particles, and their interactions in a unified way. This involves transition to a field picture with an infinite number of degrees of freedom. We shall first consider a simple mechanical problem whose solution is well known. Then, drawing inferences from this model problem, we apply a similar view on the electromagnetic problem.
8.2.1 Lagrange-Hamilton formalism for fields and interactions
Consider the situation, illustrated in figure 8.1, with N identical mass points, each with mass m and connected to its neighbour along a one-dimensional straight line, which we choose to be the x axis, by identical ideal springs with spring constants k (Hooke’s law). At equilibrium the mass points are at rest, distributed evenly with a distance a to their two nearest neighbours so that the coordinate for the ith particle is xi = ia x . After perturbation, the motion of mass point i will be a ˆ one-dimensional oscillatory motion along x. Let us denote the deviation for mass ˆ point i from its equilibrium position by ηi (t) x. ˆ The solution to this mechanical problem can be obtained if we can find a Lagrangian (Lagrange function) L which satisfies the variational equation δ L(ηi , ηi , t) dt = 0 ˙ (8.36)
According to equation (M.48) on page 191, the Lagrangian is L = T − V where T denotes the kinetic energy and V the potential energy of a classical mechanical
162
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant field theory
system with conservative forces. In our case the Lagrangian is L= 1 N m˙ 2 − k(ηi+1 − ηi )2 ηi 2∑ i=1 (8.37)
Let us write the Lagrangian, as given by equation (8.37) above, in the following way: L = ∑ aLi
i=1 N
(8.38)
Here,
Li =
ηi+1 − ηi 1 m 2 η − ka ˙ 2 a i a
2
(8.39)
is the so called linear Lagrange density. If we now let N → ∞ and, at the same time, let the springs become infinitesimally short according to the following scheme: a → dx m dm → =µ a dx ka → Y ∂η ηi+1 − ηi → a ∂x we obtain L= where (8.40a) linear mass density Young’s modulus (8.40b) (8.40c) (8.40d)
L dx
(8.41)
L
η,
∂η ∂η , ,t ∂t ∂x
=
1 µ 2
∂η ∂t
2
−Y
∂η ∂x
2
(8.42)
Notice how we made a transition from a discrete description, in which the mass points were identified by a discrete integer variable i = 1, 2, . . . , N, to a continuous description, where the infinitesimal mass points were instead identified by a continuous real parameter x, namely their position along x. ˆ A consequence of this transition is that the number of degrees of freedom for the system went from the finite number N to infinity! Another consequence is that L has now become dependent also on the partial derivative with respect to
Downloaded from
Version released 1st July 2008 at 20:49.
163
8. Electromagnetic Fields and Particles
x of the ‘field coordinate’ η. But, as we shall see, the transition is well worth the cost because it allows us to treat all fields, be it classical scalar or vectorial fields, or wave functions, spinors and other fields that appear in quantum physics, on an equal footing. Under the assumption of time independence and fixed endpoints, the variation principle (8.36) on page 162 yields: δ L dt =δ = =0 ∂η ∂η L η, , dx dt ∂t ∂x ∂L δη + ∂L δ ∂η ∂η ∂t ∂ ∂η
∂t
+ ∂
∂L
∂η ∂x
∂η δ dx dt ∂x
(8.43)
The last integral can be integrated by parts. This results in the expression ∂L ∂ ∂L ∂ ∂L − − δη dx dt = 0 (8.44) ∂η ∂t ∂ ∂η ∂x ∂ ∂η
∂t ∂x
which is the one-dimensional Euler-Lagrange equation. Inserting the linear mass point chain Lagrangian density, equation (8.42) on page 163, into equation (8.46), we obtain the equation of motion for our onedimensional linear mechanical structure. It is: µ ∂2 η ∂2 η −Y 2 = ∂t2 ∂x ∂2 µ ∂2 − 2 Y ∂t2 ∂x η=0 (8.47)
we can express this as δL ∂L ∂ =0 − δη ∂t ∂ ∂η
∂t
where the variation is arbitrary (and the endpoints fixed). This means that the integrand itself must vanish. If we introduce the functional derivative δL ∂L ∂ ∂L (8.45) = − δη ∂η ∂x ∂ ∂η
∂x
(8.46)
i.e., the one-dimensional wave equation for compression waves which propagate √ with phase speed vφ = Y/µ along the linear structure.
164
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant field theory
A generalisation of the above 1D results to a three-dimensional continuum is straightforward. For this 3D case we get the variational principle δ L dt = δ
L d3x dt
η, ∂η ∂xµ d4x
=δ L = =0
∂L − ∂ ∂L δη d4x ∂η ∂xµ ∂ ∂ηµ ∂x
(8.48)
where the variation δη is arbitrary and the endpoints are fixed. This means that the integrand itself must vanish: ∂L ∂ ∂L − µ =0 (8.49) ∂η ∂x ∂ ∂ηµ
∂x
This constitutes the four-dimensional Euler-Lagrange equations. Introducing the three-dimensional functional derivative ∂L ∂L ∂ δL = − i δη ∂η ∂x ∂ ∂ηi
∂x
(8.50)
we can express this as δL ∂ ∂L − =0 δη ∂t ∂ ∂η
∂t
(8.51)
In analogy with particle mechanics (finite number of degrees of freedom), we may introduce the canonically conjugate momentum density π(xµ ) = π(t, x) = ∂ ∂L
∂η ∂t
(8.52)
and define the Hamilton density
H
π, η,
∂η ;t ∂xi
=π
∂η −L ∂t
η,
∂η ∂η , ∂t ∂xi
(8.53)
Downloaded from
Version released 1st July 2008 at 20:49.
165
8. Electromagnetic Fields and Particles
If, as usual, we differentiate this expression and identify terms, we obtain the following Hamilton density equations ∂η ∂H = ∂π ∂t δH ∂π =− δη ∂t (8.54a) (8.54b)
The Hamilton density functions are in many ways similar to the ordinary Hamilton functions and lead to similar results.
The electromagnetic field
Above, when we described the mechanical field, we used a scalar field η(t, x). If we want to describe the electromagnetic field in terms of a Lagrange density L and Euler-Lagrange equations, it comes natural to express L in terms of the four-potential Aµ (xκ ). The entire system of particles and fields consists of a mechanical part, a field part and an interaction part. We therefore assume that the total Lagrange density L tot for this system can be expressed as
L tot = L mech + L inter + L field
(8.55)
where the mechanical part has to do with the particle motion (kinetic energy). It is given by L4 /V where L4 is given by equation (8.3) on page 156 and V is the volume. Expressed in the rest mass density ̺0 , the mechanical Lagrange density can be written 1 L mech = ̺0 uµ uµ 2 (8.56)
The L inter part describes the interaction between the charged particles and the external electromagnetic field. A convenient expression for this interaction Lagrange density is
L inter = jµ Aµ
(8.57)
For the field part L field we choose the difference between magnetic and electric energy density (in analogy with the difference between kinetic and potential energy in a mechanical field). Using the field tensor, we express this field Lagrange density as
L field =
1 µν F Fµν 4µ0
(8.58)
166
Version released 1st July 2008 at 20:49.
Downloaded from
Covariant field theory
so that the total Lagrangian density can be written 1 1 µν L tot = ̺0 uµ uµ + jµ Aµ + F Fµν (8.59) 2 4µ0 From this we can calculate all physical quantities. Using L tot in the 3D Euler-Lagrange equations, equation (8.49) on page 165 (with η replaced by Aν ), we can derive the dynamics for the whole system. For instance, the electromagnetic part of the Lagrangian density
L EM = L inter + L field = jν Aν +
1 µν F Fµν 4µ0
(8.60)
inserted into the Euler-Lagrange equations, expression (8.49) on page 165, yields two of Maxwell’s equations. To see this, we note from equation (8.60) and the results in Example 8.1 that ∂L EM = jν ∂Aν Furthermore, ∂µ 1 ∂ ∂L EM = ∂µ F κλ Fκλ ∂(∂µ Aν ) 4µ0 ∂(∂µ Aν ) ∂ 1 ∂µ = (∂κ Aλ − ∂λ Aκ )(∂κ Aλ − ∂λ Aκ ) 4µ0 ∂(∂µ Aν ) = ∂ 1 ∂µ ∂κ Aλ ∂κ Aλ − ∂κ Aλ ∂λ Aκ 4µ0 ∂(∂µ Aν ) − ∂λ Aκ ∂κ Aλ + ∂λ Aκ ∂λ Aκ = But ∂ ∂ ∂ ∂κ Aλ + ∂κ Aλ ∂κ Aλ ∂κ Aλ ∂κ Aλ = ∂κ Aλ ∂(∂µ Aν ) ∂(∂µ Aν ) ∂(∂µ Aν ) ∂ ∂ = ∂κ Aλ ∂κ Aλ + ∂κ Aλ gκα ∂α gλβ Aβ ∂(∂µ Aν ) ∂(∂µ Aν ) ∂ ∂ ∂κ Aλ + gκα gλβ ∂κ Aλ ∂α Aβ = ∂κ Aλ ∂(∂µ Aν ) ∂(∂µ Aν ) ∂ ∂ ∂κ Aλ + ∂α Aβ ∂α Aβ = ∂κ Aλ ∂(∂µ Aν ) ∂(∂µ Aν ) = 2∂µ Aν (8.63) 1 ∂ ∂µ ∂κ Aλ ∂κ Aλ − ∂κ Aλ ∂λ Aκ 2µ0 ∂(∂µ Aν ) (8.62) (8.61)
Downloaded from
Version released 1st July 2008 at 20:49.
167
8. Electromagnetic Fields and Particles
Similarly, ∂ ∂κ Aλ ∂λ Aκ = 2∂ν Aµ ∂(∂µ Aν ) so that ∂µ 1 1 ∂L EM = ∂µ (∂µ Aν − ∂ν Aµ ) = ∂µ F µν ∂(∂µ Aν ) µ0 µ0 (8.65) (8.64)
This means that the Euler-Lagrange equations, expression (8.49) on page 165, for the Lagrangian density L EM and with Aν as the field quantity become ∂L EM ∂L EM 1 − ∂µ = jν − ∂µ F µν = 0 ∂Aν ∂(∂µ Aν ) µ0 or ∂µ F µν = µ0 jν (8.67) (8.66)
which, according to equation (7.82) on page 150, is the covariant formulation of Maxwell’s source equations.
Other fields
In general, the dynamic equations for most any fields, and not only electromagnetic ones, can be derived from a Lagrangian density together with a variational principle (the Euler-Lagrange equations). Both linear and non-linear fields are studied with this technique. As a simple example, consider a real, scalar field η which has the following Lagrange density:
L =
1 ∂µ η∂µ η − m2 η2 2
(8.68)
Insertion into the 1D Euler-Lagrange equation, equation (8.46) on page 164, yields the dynamic equation (
2
− m2 )η = 0 e−m|x| |x|
(8.69)
with the solution η = ei(k·x−ωt) (8.70)
which describes the Yukawa meson field for a scalar meson with mass m. With π= 1 ∂η c2 ∂t (8.71)
168
Version released 1st July 2008 at 20:49.
Downloaded from
Bibliography
we obtain the Hamilton density
H =
1 2 2 c π + (∇η)2 + m2 η2 2
(8.72)
which is positive definite. Another Lagrangian density which has attracted quite some interest is the Proca Lagrangian
L EM = L inter + L field = jν Aν +
which leads to the dynamic equation ∂µ F µν − m2 Aν = µ0 jν
1 µν F Fµν + m2 Aµ Aµ 4µ0
(8.73)
(8.74)
This equation describes an electromagnetic field with a mass, or, in other words, massive photons. If massive photons would exist, large-scale magnetic fields, including those of the earth and galactic spiral arms, would be significantly modified to yield measurable discrepancies from their usual form. Space experiments of this kind on board satellites have led to stringent upper bounds on the photon mass. If the photon really has a mass, it will have an impact on electrodynamics as well as on cosmology and astrophysics.
8.3 Bibliography
[1] A. O. BARUT, Electrodynamics and Classical Theory of Fields and Particles, Dover Publications, Inc., New York, NY, 1980, ISBN 0-486-64038-8. [2]. [3] H. G OLDSTEIN, Classical Mechanics, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1981, ISBN 0-201-02918-9. [4] W. T. G RANDY, Introduction to Electrodynamics and Radiation, Academic Press, New York and London, 1970, ISBN 0-12-295250-2. [5] L. D. L ANDAU AND E. M. L IFSHITZ, The Classical Theory of Fields, fourth revised English ed., vol. 2 of Course of Theoretical Physics, Pergamon Press, Ltd., Oxford . . . , 1975, ISBN 0-08-025072-6. [6] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026.
Downloaded from
Version released 1st July 2008 at 20:49.
169
8. Electromagnetic Fields and Particles
[7] J. J. S AKURAI, Advanced Quantum Mechanics, Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1967, ISBN 0-201-06710-2. [8] D. E. S OPER, Classical Field Theory, John Wiley & Sons, Inc., New York, London, Sydney and Toronto, 1976, ISBN 0-471-81368-0.
170
Version released 1st July 2008 at 20:49.
Downloaded from
Example
8.4 Example
⊲ F IELD ENERGY DIFFERENCE EXPRESSED IN THE FIELD TENSOR Show, by explicit calculation, that 1 µν 1 F Fµν = 4µ0 2 B2 − ε0 E 2 µ0 (8.75)
E XAMPLE 8.1
i.e., the difference between the magnetic and electric field energy densities. From formula (7.79) on page 149 we recall that 0 −E x /c −Ey /c −Ez /c E /c 0 −Bz By (F µν ) = x Ey /c Bz 0 −B x Ez /c −By Bx 0
(8.76)
where µ denotes the row number and ν the column number. Then, Einstein summation and direct substitution yields F µν Fµν = F 00 F00 + F 01 F01 + F 02 F02 + F 03 F03 + F 10 F10 + F 11 F11 + F 12 F12 + F 13 F13 + F 20 F20 + F 21 F21 + F 22 F22 + F 23 F23 + F 30 F30 + F 31 F31 + F 32 F32 + F 33 F33
2 2 = 0 − E 2 /c2 − Ey /c2 − Ez /c2 x
and from formula (7.81) on page 150 that 0 E x /c Ey /c Ez /c −E /c 0 −Bz By Fµν = x −Ey /c Bz 0 −B x −Ez /c −By Bx 0
(8.77)
− E 2 /c2 + 0 + B2 + B2 x z y
(8.78)
2 − Ey /c2 + B2 + 0 + B2 z x
2 2 = −2E 2 /c2 − 2Ey /c2 − 2Ez /c2 + 2B2 + 2B2 + 2B2 x x y z
2 − Ez /c2 + B2 + B2 + 0 y x
= −2E 2 /c2 + 2B2 = 2(B2 − E 2 /c2 ) 1 2 B2 − E µ0 c2 µ0 = 1 2
or 1 1 µν F Fµν = 4µ0 2 B2 − ε0 E 2 µ0 (8.79) QED ⊳ E ND OF EXAMPLE 8.1
where, in the last step, the identity ε0 µ0 = 1/c2 was used.
Downloaded from
Version released 1st July 2008 at 20:49.
171
Downloaded from
Version released 1st July 2008 at 20:49.
F
F ORMULÆ
F.1 The electromagnetic field
F.1.1 Maxwell’s equations
∇·D=ρ ∂ B ∂t ∂ ∇×H=j+ D ∂t ∇×E=− ∇·B=0 (F.1) (F.2) (F.3) (F.4)
Constitutive relations
D = εE B H= µ (F.5) (F.6)
j = σE P = ε0 χE
(F.7) (F.8)
173
F. Formulæ
F.1.2 Fields and potentials
Vector and scalar potentials
B=∇×A ∂ E = −∇φ − A ∂t (F.9) (F.10)
The Lorenz-Lorentz gauge condition in vacuum
∇·A+ 1 ∂ φ=0 c2 ∂t (F.11)
F.1.3 Force and energy
Poynting’s vector
S=E×H (F.12)
Maxwell’s stress tensor
1 T i j = Ei D j + Hi B j − δi j (Ek Dk + Hk Bk ) 2 (F.13)
F.2 Electromagnetic radiation
F.2.1 Relationship between the field vectors in a plane wave
B= ˆ k×E c (F.14)
F.2.2 The far fields from an extended source distribution
−iµ0 eik|x| ′ d3 x′ e−ik·x jω × k 4π |x| V ′ i eik|x| ′ Erad (x) = x× ˆ d3 x′ e−ik·x jω × k ω ′ 4πε0 c |x| V Brad (x) = ω (F.15) (F.16)
174
Version released 1st July 2008 at 20:49.
Downloaded from
Electromagnetic radiation
F.2.3 The far fields from an electric dipole
ωµ0 eik|x| pω × k 4π |x| 1 eik|x| (pω × k) × k Erad (x) = − ω 4πε0 |x| Brad (x) = − ω (F.17) (F.18)
F.2.4 The far fields from a magnetic dipole
Brad (x) = − ω µ0 eik|x| (mω × k) × k 4π |x| k eik|x| mω × k Erad (x) = ω 4πε0 c |x| (F.19) (F.20)
F.2.5 The far fields from an electric quadrupole
iµ0 ω eik|x| (k · Qω ) × k 8π |x| i eik|x| [(k · Qω ) × k] × k Erad (x) = ω 8πε0 |x| Brad (x) = ω (F.21) (F.22)
F.2.6 The fields from a point charge in arbitrary motion
v′2 q (x − x0 ) 1 − 2 4πε0 s3 c E(t, x) B(t, x) = (x − x′ ) × c|x − x′ | E(t, x) = s = x − x′ − (x − x′ ) · ∂t′ ∂t |x − x′ | s v′ c v′ c + (x − x′ ) × ˙ (x − x0 ) × v′ 2 c (F.23) (F.24)
(F.25) (F.26) (F.27)
x − x0 = (x − x′ ) − |x − x′ | =
x
Downloaded from
Version released 1st July 2008 at 20:49.
175
F. Formulæ
F.3 Special relativity
F.3.1 Metric tensor
gµν 1 0 0 0 0 −1 0 0 = 0 0 −1 0 0 0 0 −1 (F.28)
F.3.2 Covariant and contravariant four-vectors
vµ = gµν vν (F.29)
F.3.3 Lorentz transformation of a four-vector
x′µ = Λµν xν γ −γβ 0 0 −γβ γ 0 0 Λµν = 0 0 1 0 0 0 0 1 1 γ= 1 − β2 v β= c (F.30)
(F.31)
(F.32) (F.33)
F.3.4 Invariant line element
ds = c dt = c dτ γ (F.34)
F.3.5 Four-velocity
uµ = dx µ = γ(c, v) dτ (F.35)
176
Version released 1st July 2008 at 20:49.
Downloaded from
Vector relations
F.3.6 Four-momentum
pµ = m0 uµ = E ,p c (F.36)
F.3.7 Four-current density
jµ = ρ0 uµ (F.37)
F.3.8 Four-potential
Aµ = φ ,A c (F.38)
F.3.9 Field tensor
F µν 0 −E x /c −Ey /c −Ez /c E /c 0 −Bz By = ∂µ Aν − ∂ν Aµ = x Ey /c Bz 0 −Bx Ez /c −By Bx 0 (F.39)
F.4 Vector relations
Let x be the radius vector (coordinate vector) from the origin to the point (x1 , x2 , x3 ) ≡ (x, y, z) and let |x| denote the magnitude (‘length’) of x. Let further α(x), β(x), . . . be arbitrary scalar fields and a(x), b(x), c(x), d(x), . . . arbitrary vector fields. The differential vector operator ∇ is in Cartesian coordinates given by ∇ ≡ ∑ xi ˆ
i=1 3
∂ def ∂ def ≡ xi ≡ ∂ ˆ ∂xi ∂xi
(F.40)
where xi , i = 1, 2, 3 is the ith unit vector and x1 ≡ x, x2 ≡ y, and x3 ≡ z. In ˆ ˆ ˆ ˆ ˆ ˆ ˆ component (tensor) notation ∇ can be written ∇i = ∂i = ∂ ∂ ∂ , , ∂x1 ∂x2 ∂x3 = ∂ ∂ ∂ , , ∂x ∂y ∂z (F.41)
Downloaded from
Version released 1st July 2008 at 20:49.
177
F. Formulæ
F.4.1 Spherical polar coordinates
Base vectors (F.42a) (F.42b) (F.42c)
ϕ = − sin ϕ x1 + cos ϕ x2 ˆ ˆ ˆ
(F.43a) (F.43b) (F.43c)
Directed line element
ˆ dx x = dl = dr r + r dθ θ + r sin θ dϕ ϕ ˆ ˆ ˆ (F.44)
Solid angle element
dΩ = sin θ dθ dϕ (F.45)
Directed area element
d2x n = dS = dS r = r2 dΩ r ˆ ˆ ˆ (F.46)
Volume element
d3x = dV = dr dS = r2 dr dΩ (F.47)
F.4.2 Vector formulae
General vector algebraic identities
a · b = b · a = δi j ai b j = ab cos θ (F.48) (F.49) (F.50) (F.51) (F.52)
a × b = −b × a = ǫi jk a j bk xi ˆ a · (b × c) = (a × b) · c
a × (b × c) + b × (c × a) + c × (a × b) = 0
a × (b × c) = b(a · c) − c(a · b) ≡ ba · c − ca · b
178
Version released 1st July 2008 at 20:49.
Downloaded from
Vector relations
(a × b) × (c × d) = (a × b · d)c − (a × b · c)d
(a × b) · (c × d) = a · [b × (c × d)] = (a · c)(b · d) − (a · d)(b · c)
(F.53) (F.54)
General vector analytic identities
∇(αβ) = α∇β + β∇α ∇ × (αa) = α∇ × a − a × ∇α ∇ · (αa) = a · ∇α + α∇ · a (F.55) (F.56) (F.57) (F.58) (F.59) (F.60) (F.61) (F.62) (F.63) (F.64)
∇ · (a × b) = b · (∇ × a) − a · (∇ × b)
∇ × ∇α = 0
∇ · ∇α = ∇ α
∇(a · b) = a × (∇ × b) + b × (∇ × a) + (b · ∇)a + (a · ∇)b
2
∇ × (a × b) = a(∇ · b) − b(∇ · a) + (b · ∇)a − (a · ∇)b
∇ × (∇ × a) = ∇(∇ · a) − ∇2 a ≡ ∇∇ · a − ∇ · ∇a
∇ · (∇ × a) = 0
Special identities
In the following x = xi xi and x′ = xi′ xi are radius vectors, k an arbitrary constant ˆ ˆ ∂ ∂ ˆ ˆ vector, a = a(x) an arbitrary vector field, ∇ ≡ ∂xi xi , and ∇′ ≡ ∂x′ xi .
i
∇×x=0 ∇(k · x) = k x ∇|x| = |x|
∇·x=3
(F.65) (F.66) (F.67) (F.68) (F.69) (F.70) (F.71) (F.72) (F.73)
x − x′ = −∇′ |x − x′ | |x − x′ | 1 x ∇ =− 3 |x| |x| 1 1 x − x′ ∇ = −∇′ =− ′ |3 ′| |x − x |x − x |x − x′ | 1 x = −∇2 = 4πδ(x) ∇· 3 |x| |x| x − x′ 1 ∇· = −∇2 = 4πδ(x − x′ ) |x − x′ |3 |x − x′ | ∇ |x − x′ | =
Downloaded from
Version released 1st July 2008 at 20:49.
179
F. Formulæ
∇·
k |x|
=k· ∇ x |x|3 = k∇2
1 |x| = −∇
=− k·x |x|3
k·x |x|3 if |x| 0
(F.74) (F.75) (F.76) (F.77)
∇× k× ∇2 k |x|
∇ × (k × a) = k(∇ · a) + k × (∇ × a) − ∇(k · a)
1 |x|
= −4πkδ(x)
Integral relations
Let V(S ) be the volume bounded by the closed surface S (V). Denote the 3dimensional volume element by d3x(≡ dV) and the surface element, directed along the outward pointing surface normal unit vector n, by dS(≡ d2x n). Then ˆ ˆ (∇ · a) d3x = (∇α) d3x =
V S
V
S
dS · a
(F.78) (F.79) (F.80)
dS α dS × a
S
(∇ × a) d3x =
V
If S (C) is an open surface bounded by the contour C(S ), whose line element is dl, then α dl =
C S
dS × ∇α dS · (∇ × a)
(F.81) (F.82)
C
a · dl =
S
F.5 Bibliography
[1] G. B. A RFKEN AND H. J. W EBER, Mathematical Methods for Physicists, fourth, international ed., Academic Press, Inc., San Diego, CA . . . , 1995, ISBN 0-12-059816-7. [2] P. M. M ORSE AND H. F ESHBACH, Methods of Theoretical Physics, Part I. McGraw-Hill Book Company, Inc., New York, NY . . . , 1953, ISBN 07-043316-8. [3] W. K. H. PANOFSKY AND M. P HILLIPS, Classical Electricity and Magnetism, second ed., Addison-Wesley Publishing Company, Inc., Reading, MA . . . , 1962, ISBN 0-201-057026.
180
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
M
M ATHEMATICAL M ETHODS
M.1 Scalars, vectors and tensors
Every physical observable can be described by a geometric object. We have chosen to describe the observables in classical electrodynamics in terms of scalars, pseudoscalars, vectors, pseudovectors, tensors or pseudotensors, all of which obey certain canonical rules of transformation under a change of coordinate systems. We will not exploit differential forms to any significant degree to describe physical observables. A scalar describes a scalar quantity which may or may not be constant in time and/or space. A vector describes some kind of physical motion along a curve in space due to vection and a tensor describes the local motion or deformation of a surface or a volume due to some form of tension. However, generalisations to more abstract notions of these quantities have proved useful and are therefore commonplace. The difference between a scalar, vector and tensor and a pseudoscalar, pseudovector and a pseudotensor is that the latter behave differently under such coordinate transformations which cannot be reduced to pure rotations. Throughout we adopt the convention that Latin indices i, j, k, l, . . . run over the range 1, 2, 3 to denote vector or tensor components in the real Euclidean threedimensional (3D) configuration space R3 , and Greek indices µ, ν, κ, λ, . . . , which are used in four-dimensional (4D) space, run over the range 0, 1, 2, 3.
181
M. Mathematical Methods
M.1.1 Vectors
Radius vector
Mathematically, a vector can be represented in a number of different ways. One suitable representation in a real or complex1 vector space of dimensionality N is in terms of an ordered N-tuple of real or complex numbers, or a row vector of the components, (a1 , a2 , . . . , aN ), along the N coordinate axes that span the vector space under consideration. Note, however, that there are many ordered N-tuples of numbers that do not comprise a vector, i.e., do not exhibit vector transformation properties! The most basic vector, and the prototype against which all other vectors are benchmarked, is the radius vector which is the vector from the origin to the point of interest. Its N-tuple representation simply enumerates the coordinates which describe this point. In this sense, the radius vector from the origin to a point is synonymous with the coordinates of the point itself. In the 3D Euclidean space R3 , we have N = 3 and the radius vector can be represented by the triplet (x1 , x2 , x3 ) of coordinates xi , i = 1, 2, 3. The coordinates xi are scalar quantities which describe the position along the unit base vectors xi ˆ which span R3 . Therefore a representation of the radius vector in R3 is x = ∑ xi xi ≡ xi xi ˆ ˆ
def i=1 3
(M.1)
where we have introduced Einstein’s summation convention (EΣ) which states that a repeated index in a term implies summation over the range of the index in question. Whenever possible and convenient we shall in the following always assume EΣ and suppress explicit summation in our formulae. Typographically, we represent a vector in 3D Euclidean space R3 by a boldface letter or symbol in a Roman font. Moreover, we introduced the symbol ≡def which may be read ‘is, by definition, to equal in meaning’, or ‘equals by definition’, or, formally, definiendum ≡def definiens [4]. Alternatively, we may describe the radius vector in component notation as follows: xi ≡ (x1 , x2 , x3 ) ≡ (x, y, z)
def
(M.2)
This component notation is particularly useful in 4D space where we can repis often very convenient to use complex notation in physics. This notation can simplify the mathematical treatment considerably. But since all physical observables are real, we must in the final step of our mathematical analysis of a physical problem always ensure that the results to be compared with experimental values are real-valued. In classical physics this is achieved by taking the real (or imaginary) part of the mathematical result, whereas in quantum physics one takes the absolute value.
1 It
182
Version released 1st July 2008 at 20:49.
Downloaded from
Scalars, vectors and tensors
resent the radius vector either in its contravariant component form xµ ≡ (x0 , x1 , x2 , x3 ) or its covariant component form xµ ≡ (x0 , x1 , x2 , x3 )
def def
(M.3)
(M.4)
The relation between the covariant and contravariant forms is determined by the metric tensor (also known as the fundamental tensor) whose actual form is dictated by the properties of the vector space in question. The dual representation of vectors in contravariant and covariant forms is most convenient when we work in a non-Euclidean vector space with an indefinite metric. An example is Lorentz space L4 which is a 4D Riemannian space utilised to formulate the special theory of relativity. We note that for a change of coordinates xµ → x′µ = x′µ (x0 , x1 , x2 , x3 ), due to a transformation from a system Σ to another system Σ′ , the differential radius vector dxµ transforms as dx′µ = ∂x′µ ν dx ∂xν (M.5)
which follows trivially from the rules of differentiation of x′µ considered as functions of four variables xν .
M.1.2 Fields
A field is a physical entity which depends on one or more continuous parameters. Such a parameter can be viewed as a ‘continuous index’ which enumerates the ‘coordinates’ of the field. In particular, in a field which depends on the usual radius vector x of R3 , each point in this space can be considered as one degree of freedom so that a field is a representation of a physical entity which has an infinite number of degrees of freedom.
Scalar fields
We denote an arbitrary scalar field in R3 by α(x) = α(x1 , x2 , x3 ) ≡ α(xi )
def
(M.6)
This field describes how the scalar quantity α varies continuously in 3D R3 space. In 4D, a four-scalar field is denoted α(x0 , x1 , x2 , x3 ) ≡ α(xµ )
def
(M.7)
Downloaded from
Version released 1st July 2008 at 20:49.
183
M. Mathematical Methods
which indicates that the four-scalar α depends on all four coordinates spanning this space. Since a four-scalar has the same value at a given point regardless of coordinate system, it is also called an invariant. Analogous to the transformation rule, equation (M.5) on page 183, for the differential dxµ , the transformation rule for the differential operator ∂/∂xµ under a transformation xµ → x′µ becomes ∂xν ∂ ∂ = ′µ ν ′µ ∂x ∂x ∂x (M.8)
which, again, follows trivially from the rules of differentiation.
Vector fields
We can represent an arbitrary vector field a(x) in R3 as follows: a(x) = ai (x) xi ˆ In component notation this same vector can be represented as ai (x) = (a1 (x), a2 (x), a3 (x)) = ai (x j ) (M.10) (M.9)
In 4D, an arbitrary four-vector field in contravariant component form can be represented as aµ (xν ) = (a0 (xν ), a1 (xν ), a2 (xν ), a3 (xν )) or, in covariant component form, as aµ (xν ) = (a0 (xν ), a1 (xν ), a2 (xν ), a3 (xν )) (M.12) (M.11)
where xν is the radius four-vector. Again, the relation between aµ and aµ is determined by the metric of the physical 4D system under consideration. Whether an arbitrary N-tuple fulfils the requirement of being an (N-dimensional) contravariant vector or not, depends on its transformation properties during a change of coordinates. For instance, in 4D an assemblage yµ = (y0 , y1 , y2 , y3 ) constitutes a contravariant four-vector (or the contravariant components of a fourvector) if and only if, during a transformation from a system Σ with coordinates xµ to a system Σ′ with coordinates x′µ , it transforms to the new system according to the rule y′µ = ∂x′µ ν y ∂xν (M.13)
i.e., in the same way as the differential coordinate element dxµ transforms according to equation (M.5) on page 183.
184
Version released 1st July 2008 at 20:49.
Downloaded from
Scalars, vectors and tensors
The analogous requirement for a covariant four-vector is that it transforms, during the change from Σ to Σ′ , according to the rule y′ = µ ∂xν yν ∂x′µ (M.14)
i.e., in the same way as the differential operator ∂/∂xµ transforms according to equation (M.8) on page 184.
Tensor fields
We denote an arbitrary tensor field in R3 by A(x). This tensor field can be represented in a number of ways, for instance in the following matrix form: A11 (x) A12 (x) A13 (x) def Ai j (xk ) ≡ A21 (x) A22 (x) A23 (x) (M.15) A31 (x) A32 (x) A33 (x)
Strictly speaking, the tensor field described here is a tensor of rank two. A particularly simple rank-two tensor in R3 is the 3D Kronecker delta symbol δi j , with the following properties: δi j = 0 1 if i j if i = j (M.16)
Another common and useful tensor is the fully antisymmetric tensor of rank 3, also known as the Levi-Civita tensor 1 if i, j, k is an even permutation of 1,2,3 (M.18) ǫi jk = 0 if at least two of i, j, k are equal −1 if i, j, k is an odd permutation of 1,2,3 with the following further property ǫi jk ǫilm = δ jl δkm − δ jm δkl (M.19)
The 3D Kronecker delta has the following matrix representation 1 0 0 (δi j ) = 0 1 0 0 0 1
(M.17)
In fact, tensors may have any rank n. In this picture a scalar is considered to be a tensor of rank n = 0 and a vector a tensor of rank n = 1. Consequently, the
Downloaded from
Version released 1st July 2008 at 20:49.
185
M. Mathematical Methods
notation where a vector (tensor) is represented in its component form is called the tensor notation. A tensor of rank n = 2 may be represented by a two-dimensional array or matrix whereas higher rank tensors are best represented in their component forms (tensor notation). In 4D, we have three forms of four-tensor fields of rank n. We speak of • a contravariant four-tensor field, denoted Aµ1 µ2 ...µn (xν ), • a covariant four-tensor field, denoted Aµ1 µ2 ...µn (xν ),
µ ...µ • a mixed four-tensor field, denoted Aµ1 µ2...µnk (xν ). k+1
The 4D metric tensor (fundamental tensor) mentioned above is a particularly important four-tensor of rank 2. In covariant component form we shall denote it gµν . This metric tensor determines the relation between an arbitrary contravariant four-vector aµ and its covariant counterpart aµ according to the following rule: aµ (xκ ) ≡ gµν aν (xκ )
def
(M.20)
This rule is often called lowering of index. The raising of index analogue of the index lowering rule is: aµ (xκ ) ≡ gµν aν (xκ )
def
(M.21)
More generally, the following lowering and raising rules hold for arbitrary rank n mixed tensor fields:
...ν gµk νk Aν1 ν2νk+2k−1 νnk (xκ ) = Aν1kν2 ...νk−1 (xκ ) νk+1 ...ν µ νk+1 ...νn
(M.22)
ν2 ...νk−1 ...ν gµk νk Aν1νk+1 ...νn (xκ ) = Aν1 ν2νk+2k−1 µnk (xκ ) νk νk+1 ...ν
(M.23)
Successive lowering and raising of more than one index is achieved by a repeated application of this rule. For example, a dual application of the lowering operation on a rank 2 tensor in contravariant form yields Aµν = gµκ gλν Aκλ (M.24)
i.e., the same rank 2 tensor in covariant form. This operation is also known as a tensor contraction.
186
Version released 1st July 2008 at 20:49.
Downloaded from
Scalars, vectors and tensors
M.1.3 Vector algebra
Scalar product
The scalar product (dot product, inner product) of two arbitrary 3D vectors a and b in ordinary R3 space is the scalar number a · b = ai xi · b j x j = xi · x j ai b j = δi j ai b j = ai bi ˆ ˆ ˆ ˆ (M.25)
where we used the fact that the scalar product xi · x j is a representation of the ˆ ˆ Kronecker delta δi j defined in equation (M.16) on page 185. In Russian literature, the 3D scalar product is often denoted (ab). The scalar product of a in R3 with itself is a · a ≡ (a)2 = |a|2 = (ai )2 = a2 and similarly for b. This allows us to write a · b = ab cos θ (M.27)
def
(M.26)
where θ is the angle between a and b. In 4D space we define the scalar product of two arbitrary four-vectors aµ and µ b in the following way aµ bµ = gνµ aν bµ = aν bν = gµν aµ bν (M.28)
where we made use of the index lowering and raising rules (M.20) and (M.21). The result is a four-scalar, i.e., an invariant which is independent of in which 4D coordinate system it is measured. The quadratic differential form ds2 = gµν dxν dxµ = dxµ dxµ (M.29)
i.e., the scalar product of the differential radius four-vector with itself, is an invariant called the metric. It is also the square of the line element ds which is the distance between neighbouring points with coordinates xµ and xµ + dxµ .
Dyadic product
The dyadic product field A(x) ≡ a(x)b(x) with two juxtaposed vector fields a(x) and b(x) is the outer product of a and b. Operating on this dyad from the right and from the left with an inner product of an vector c one obtains
A · c ≡ ab · c ≡ a(b · c)
def def
(M.30a)
Downloaded from
Version released 1st July 2008 at 20:49.
187
M. Mathematical Methods
c · A ≡ c · ab ≡ (c · a)b
def
def
(M.30b)
which we identify with expression (M.15) on page 185, viz. a tensor in matrix notation.
which means that we can represent the tensor A(x) in matrix form as a1 b1 a1 b2 a1 b3 Ai j (xk ) = a2 b1 a2 b2 a2 b3 a3 b1 a3 b2 a3 b3
i.e., new vectors, proportional to a and b, respectively. In mathematics, a dyadic product is often called tensor product and is frequently denoted a ⊗ b. In matrix notation the outer product of a and b is written x1 ˆ a1 b1 a1 b2 a1 b3 x1 x2 x3 a2 b1 a2 b2 a2 b3 x2 ˆ ˆ ˆ ˆ ab = (M.31) x3 ˆ a3 b1 a3 b2 a3 b3
(M.32)
Vector product
The vector product or cross product of two arbitrary 3D vectors a and b in ordinary R3 space is the vector c = a × b = ǫi jk a j bk xi ˆ (M.33)
Here ǫi jk is the Levi-Civita tensor defined in equation (M.18) on page 185. Sometimes the 3D vector product of a and b is denoted a ∧ b or, particularly in the Russian literature, [ab]. Alternatively, a × b = ab sin θ e ˆ (M.34)
where θ is the angle between a and b and e is a unit vector perpendicular to the ˆ plane spanned by a and b. ′ ′ ′ A spatial reversal of the coordinate system (x1 , x2 , x3 ) = (−x1 , −x2 , −x3 ) changes sign of the components of the vectors a and b so that in the new coordinate system a′ = −a and b′ = −b, which is to say that the direction of an ordinary vector is not dependent on the choice of directions of the coordinate axes. On the other hand, as is seen from equation (M.33), the cross product vector c does not change sign. Therefore a (or b) is an example of a ‘true’ vector, or polar vector, whereas c is an example of an axial vector, or pseudovector. A prototype for a pseudovector is the angular momentum vector L = x × p and hence the attribute ‘axial’. Pseudovectors transform as ordinary vectors under translations and proper rotations, but reverse their sign relative to ordinary vectors
188
Version released 1st July 2008 at 20:49.
Downloaded from
Scalars, vectors and tensors
for any coordinate change involving reflection. Tensors (of any rank) which transform analogously to pseudovectors are called pseudotensors. Scalars are tensors of rank zero, and zero-rank pseudotensors are therefore also called pseudoscalars, an example being the pseudoscalar xi · ( x j × xk ). This triple product is a repreˆ ˆ ˆ sentation of the i jk component of the Levi-Civita tensor ǫi jk which is a rank three pseudotensor.
M.1.4 Vector analysis
The del operator
In R3 the del operator is a differential vector operator, denoted in Gibbs’ notation by ∇ and defined as ∇ ≡ xi ˆ
def
∂ def ∂ def ≡ ∂ ≡ ∂xi ∂x
(M.35)
where xi is the ith unit vector in a Cartesian coordinate system. Since the opˆ erator in itself has vectorial properties, we denote it with a boldface nab-la. In ‘component’ notation we can write ∂i = ∂ ∂ ∂ , , ∂x1 ∂x2 ∂x3 (M.36)
In 4D, the contravariant component representation of the four-del operator is defined by ∂µ = ∂ ∂ ∂ ∂ , , , ∂x0 ∂x1 ∂x2 ∂x3 (M.37)
whereas the covariant four-del operator is ∂µ = ∂ ∂ ∂ ∂ , , , ∂x0 ∂x1 ∂x2 ∂x3 (M.38)
We can use this four-del operator to express the transformation properties (M.13) and (M.14) on page 185 as y′µ = ∂ν x′µ yν and y′ = ∂′ xν yν µ µ (M.40) (M.39)
respectively. With the help of the del operator we can define the gradient, divergence and curl of a tensor (in the generalised sense).
Downloaded from
Version released 1st July 2008 at 20:49.
189
M. Mathematical Methods
The gradient
The gradient of an R3 scalar field α(x), denoted ∇α(x), is an R3 vector field a(x): ∇α(x) = ∂α(x) = xi ∂i α(x) = a(x) ˆ (M.41)
From this we see that the boldface notation for the nabla and del operators is very handy as it elucidates the 3D vectorial property of the gradient. In 4D, the four-gradient of a four-scalar is a covariant vector, formed as a derivative of a four-scalar field α(xµ ), with the following component form: ∂µ α(xν ) = ∂α(xν ) ∂xµ (M.42)
The divergence
We define the 3D divergence of a vector field in R3 as ∇ · a(x) = ∂ · x j a j (x) = δi j ∂i a j (x) = ∂i ai (x) = ˆ ∂ai (x) = α(x) ∂xi (M.43)
which, as indicated by the notation α(x), is a scalar field in R3 . We may think of the divergence as a scalar product between a vectorial operator and a vector. As is the case for any scalar product, the result of a divergence operation is a scalar. Again we see that the boldface notation for the 3D del operator is very convenient. The four-divergence of a four-vector aµ is the following four-scalar: ∂µ aµ (xν ) = ∂µ aµ (xν ) = ∂aµ (xν ) ∂xµ (M.44)
The Laplacian
The 3D Laplace operator or Laplacian can be described as the divergence of the gradient operator: ∇2 = ∆ = ∇ · ∇ =
3 ∂ ∂2 ∂ ∂2 xi · x j ˆ ˆ = δi j ∂i ∂ j = ∂2 = 2 ≡ ∑ 2 i ∂xi ∂x j ∂xi i=1 ∂xi
(M.45)
The symbol ∇2 is sometimes read del squared. If, for a scalar field α(x), ∇2 α < 0 at some point in 3D space, it is a sign of concentration of α at that point.
The curl
In R3 the curl of a vector field a(x), denoted ∇ × a(x), is another R3 vector field b(x) which can be defined in the following way: ∇ × a(x) = ǫi jk xi ∂ j ak (x) = ǫi jk xi ˆ ˆ ∂ak (x) = b(x) ∂x j (M.46)
190
Version released 1st July 2008 at 20:49.
Downloaded from
Analytical mechanics
where use was made of the Levi-Civita tensor, introduced in equation (M.18) on page 185. The covariant 4D generalisation of the curl of a four-vector field aµ (xν ) is the antisymmetric four-tensor field Gµν (xκ ) = ∂µ aν (xκ ) − ∂ν aµ (xκ ) = −Gνµ (xκ ) (M.47)
A vector with vanishing curl is said to be irrotational. Numerous vector algebra and vector analysis formulae are given in chapter F. Those which are not found there can often be easily derived by using the component forms of the vectors and tensors, together with the Kronecker and Levi-Civita tensors and their generalisations to higher ranks. A short but very useful reference in this respect is the article by A. Evett [3].
M.2 Analytical mechanics
M.2.1 Lagrange’s equations
As is well known from elementary analytical mechanics, the Lagrange function or Lagrangian L is given by L(qi , qi , t) = L qi , ˙ dqi ,t dt =T −V (M.48)
where qi is the generalised coordinate, T the kinetic energy and V the potential energy of a mechanical system, Using the action
t2
S =
t1
dt L(qi , qi , t) ˙
(M.49)
and the variational principle with fixed endpoints t1 and t2 , δS = 0 one finds that the Lagrangian satisfies the Euler-Lagrange equations d dt ∂L ∂qi ˙ − ∂L =0 ∂qi (M.51) (M.50)
To the generalised coordinate qi one defines a canonically conjugate momentum pi according to pi = ∂L ∂qi ˙ (M.52)
Downloaded from
Version released 1st July 2008 at 20:49.
191
M. Mathematical Methods
and note from equation (M.51) on page 191 that ∂L = pi ˙ ∂qi (M.53)
If we introduce an arbitrary, differentiable function α = α(qi , t) and a new Lagrangian L′ related to L in the following way L′ = L + then ∂L′ ∂L ∂α = + ∂qi ˙ ∂qi ∂q ˙ ∂L d ∂α ∂L′ = + ∂qi ∂qi dt ∂q Or, in other words, d ∂L′ ∂L′ ∂L d ∂L − − = dt ∂qi ˙ ∂qi dt ∂qi ˙ ∂qi where p′ = i and q′ = − i ∂L′ ∂L = = qi ∂ pi ˙ ∂p ˙ (M.57b) ∂L ∂α ∂α ∂L′ = + = pi + ∂qi ˙ ∂qi ∂qi ˙ ∂qi (M.57a) (M.56) (M.55a) (M.55b) ∂α ∂α dα = L + qi ˙ + dt ∂qi ∂t (M.54)
M.2.2 Hamilton’s equations
From L, the Hamiltonian (Hamilton function) H can be defined via the Legendre transformation H(pi , qi , t) = pi qi − L(qi , qi , t) ˙ ˙ (M.58)
After differentiating the left and right hand sides of this definition and setting them equal we obtain ∂H ∂H ∂L ∂L ∂L ∂H dpi + dqi + dt = qi dpi + pi dqi − ˙ ˙ dqi − dqi − ˙ dt ∂pi ∂qi ∂t ∂qi ∂qi ˙ ∂t (M.59)
192
Version released 1st July 2008 at 20:49.
Downloaded from
Analytical mechanics
According to the definition of pi , equation (M.52) on page 191, the second and fourth terms on the right hand side cancel. Furthermore, noting that according to equation (M.53) on page 192 the third term on the right hand side of equa˙ tion (M.59) on page 192 is equal to − pi dqi and identifying terms, we obtain the Hamilton equations: dqi ∂H = qi = ˙ ∂pi dt ∂H dpi = − pi = − ˙ ∂qi dt (M.60a) (M.60b)
Downloaded from
Version released 1st July 2008 at 20:49.
193
M. Mathematical Methods
M.3 Examples
E XAMPLE M.1
⊲ T ENSORS IN 3D SPACE
x3
n ˆ
d2x x2 V
x1
F IGURE M.1 :
Tetrahedron-like volume element V containing matter.
Consider a tetrahedron-like volume element V of a solid, fluid, or gaseous body, whose atomistic structure is irrelevant for the present analysis; figure M.1 indicates how this volume may look like. Let dS = d2x n be the directed surface element of this volume element and let ˆ the vector T n d2x be the force that matter, lying on the side of d2x toward which the unit normal ˆ vector n points, acts on matter which lies on the opposite side of d2x. This force concept is ˆ meaningful only if the forces are short-range enough that they can be assumed to act only in the surface proper. According to Newton’s third law, this surface force fulfils
T− n = − T n ˆ ˆ
(M.61)
Using (M.61) and Newton’s second law, we find that the matter of mass m, which at a given instant is located in V obeys the equation of motion
194
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
T n d2x − cos θ1 T x1 d2x − cos θ2 T x2 d2x − cos θ3 T x3 d2x + Fext = ma ˆ ˆ ˆ ˆ m d2x Fext m
(M.62)
where Fext is the external force and a is the acceleration of the volume element. In other words T n = n 1 T x1 + n 2 T x2 + n 3 T x3 + ˆ ˆ ˆ ˆ a− (M.63)
Since both a and Fext /m remain finite whereas m/d2x → 0 as V → 0, one finds that in this limit T n = ∑ ni T xi ≡ ni T xi ˆ ˆ ˆ
i=1 3
(M.64)
From the above derivation it is clear that equation (M.64) is valid not only in equilibrium but also when the matter in V is in motion. Introducing the notation T i j = T xi ˆ
j
(M.65)
for the jth component of the vector T xi , we can write equation (M.64) above in component form ˆ as follows T n j = (T n) j = ∑ ni T i j ≡ ni T i j ˆ ˆ
i=1 3
(M.66)
Using equation (M.66), we find that the component of the vector T n in the direction of an ˆ arbitrary unit vector m is ˆ T nm = T n · m ˆ ˆˆ ˆ = ∑ T njm j = ∑ ˆ
j=1 3 3 j=1
∑ ni T i j
i=1
3
ˆ m j ≡ ni T i j m j = n · T · m ˆ
(M.67)
Hence, the jth component of the vector T xi , here denoted T i j , can be interpreted as the i jth ˆ component of a tensor T. Note that T nm is independent of the particular coordinate system used ˆˆ in the derivation. We shall now show how one can use the momentum law (force equation) to derive the equation of motion for an arbitrary element of mass in the body. To this end we consider a part V of the body. If the external force density (force per unit volume) is denoted by f and the velocity for a mass element dm is denoted by v, we obtain d dt v dm =
V V
f d3x +
S
T n d2x ˆ
(M.68)
The jth component of this equation can be written d v j dm = dt f j d3x +
V S
T nj d2x = ˆ
V
f j d3x +
S
ni T i j d2x
(M.69)
V
where, in the last step, equation (M.66) above was used. Setting dm = ρ d3x and using the divergence theorem on the last term, we can rewrite the result as ρ
V
d v j d3x = dt
f j d3x +
V V
∂T i j 3 dx ∂xi
(M.70)
Downloaded from
Version released 1st July 2008 at 20:49.
195
M. Mathematical Methods
Since this formula is valid for any arbitrary volume, we must require that ρ ∂T i j d vj − fj − =0 dt ∂xi (M.71)
or, equivalently ρ ∂T i j ∂v j + ρv · ∇v j − f j − =0 ∂t ∂xi (M.72)
Note that ∂v j /∂t is the rate of change with time of the velocity component v j at a fixed point x = (x1 , x1 , x3 ). ⊳ E ND OF EXAMPLE M.1
E XAMPLE M.2
⊲ C ONTRAVARIANT AND COVARIANT VECTORS IN FLAT L ORENTZ SPACE The 4D Lorentz space L4 has a simple metric which can be described either by the metric tensor 1 if µ = ν = 0 gµν = −1 if µ = ν = i = j = 1, 2, 3 (M.73) 0 if µ ν
which, in matrix notation, is represented as 1 0 0 0 0 −1 0 0 (gµν ) = 0 0 −1 0 0 0 0 −1
(M.74)
which, in matrix notation, is represented as −1 0 0 0 0 1 0 0 (gµν ) = 0 0 1 0 0 0 0 1 i.e., a matrix with signature {−, +, +, +}.
i.e., a matrix with a main diagonal that has the sign sequence, or signature, {+, −, −, −} or −1 if µ = ν = 0 gµν = 1 (M.75) if µ = ν = i = j = 1, 2, 3 0 if µ ν
(M.76)
Consider an arbitrary contravariant four-vector aν in this space. In component form it can be written: aν ≡ (a0 , a1 , a2 , a3 ) = (a0 , a)
def
(M.77)
196
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
According to the index lowering rule, equation (M.20) on page 186, we obtain the covariant version of this vector as aµ ≡ (a0 , a1 , a2 , a3 ) = gµν aν In the {+, −, −, −} metric we obtain µ=0: µ=1: µ=2: µ=3: or aµ = (a0 , a1 , a2 , a3 ) = (a0 , −a1 , −a2 , −a3 ) = (a0 , −a) Radius 4-vector itself in L4 and in this metric is given by xµ = (x0 , x1 , x2 , x3 ) = (x0 , x, y, z) = (x0 , x) xµ = (x0 , x1 , x2 , x3 ) = (x0 , −x1 , −x2 , −x3 ) = (x0 , −x) where x0 = ct. Analogously, using the {−, +, +, +} metric we obtain aµ = (a0 , a1 , a2 , a3 ) = (−a0 , a1 , a2 , a3 ) = (−a0 , a) (M.85) (M.84) (M.83) a0 = 1 · a0 + 0 · a1 + 0 · a2 + 0 · a3 = a0
0 1 2 3 def
(M.78)
(M.79)
1
a1 = 0 · a − 1 · a + 0 · a + 0 · a = −a
0 1 2 3
(M.80) (M.81) (M.82)
a2 = 0 · a0 + 0 · a1 − 1 · a2 + 0 · a3 = −a2 a3 = 0 · a + 0 · a + 0 · a − 1 · a = −a
3
⊳ E ND OF EXAMPLE M.2
⊲ I NNER PRODUCTS IN COMPLEX VECTOR SPACE A 3D complex vector A is a vector in C3 (or, if we like, in R6 ), expressed in terms of two real vectors aR and aI in R3 in the following way
def def ˆ A ≡ aR + iaI = aR aR + iaI aI ≡ A A ∈ C3 ˆ ˆ
E XAMPLE M.3
(M.86)
The inner product of A with itself may be defined as A2 ≡ A · A = a2 − a2 + 2iaR · aI ≡ A2 ∈ C R I from which we find that A= a2 − a2 + 2iaR · aI ∈ C R I (M.88)
def def
(M.87)
Using this in equation (M.86) above, we see that we can interpret this so that the complex unit vector is
Downloaded from
Version released 1st July 2008 at 20:49.
197
M. Mathematical Methods
ˆ A = A= A = aR
aR a2 − a2 + 2iaR · aI R I (a2 + a2 ) R I 1−
aR + i ˆ
aI a2 − a2 + 2iaR · aI R I aI (a2 + a2 ) R I 1−
aI ˆ a I ∈ C3 ˆ (M.89)
a2 − a2 − 2iaR · aI R I
4a2 a2 sin2 θ R I (a2 +a2 )2 R I
aR + i ˆ
a2 − a2 − 2iaR · aI R I
4a2 a2 sin2 θ R I (a2 +a2 )2 R I
On the other hand, the definition of the scalar product in terms of the inner product of complex vector with its own complex conjugate yields |A|2 ≡ A · A∗ = a2 + a2 = |A|2 R I with the help of which we can define the unit vector as A ˆ A= = |A| = aR aR a2 + a2 R I aR + i ˆ aI a2 + a2 R I aI ˆ (M.91)
def
(M.90)
a2 + a2 aI a2 + a2 R I R I aR + i ˆ a I ∈ C3 ˆ 2 2 aR + aI a2 + a2 R I
⊳ E ND OF EXAMPLE M.3
E XAMPLE M.4
⊲ S CALAR PRODUCT, NORM AND METRIC IN L ORENTZ SPACE In L4 the metric tensor attains a simple form [see example M.2 on page 196] and, hence, the scalar product in equation (M.28) on page 187 can be evaluated almost trivially. For the {+, −, −, −} signature it becomes aµ bµ = (a0 , −a) · (b0 , b) = a0 b0 − a · b The important scalar product of the L4 radius four-vector with itself becomes xµ xµ = (x0 , −x) · (x0 , x) = (ct, −x) · (ct, x) = (ct)2 − (x1 )2 − (x2 )2 − (x3 )2 = s2 which is the indefinite, real norm of L4 . The L4 metric is the quadratic differential form ds2 = dxµ dxµ = c2 (dt)2 − (dx1 )2 − (dx2 )2 − (dx3 )2 (M.94) (M.93) (M.92)
⊳ E ND OF EXAMPLE M.4
198
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
⊲ T HE FOUR - DEL OPERATOR IN L ORENTZ SPACE In L the contravariant form of the four-del operator can be represented as ∂µ = 1 ∂ , −∂ c ∂t = 1 ∂ , −∇ c ∂t (M.95)
4
E XAMPLE M.5
and the covariant form as ∂µ = 1 ∂ ,∂ c ∂t = 1 ∂ ,∇ c ∂t (M.96)
Taking the scalar product of these two, one obtains ∂µ ∂µ = 1 ∂2 − ∇2 = c2 ∂t2
2
(M.97) , and sometimes defined with an oppo⊳ E ND OF EXAMPLE M.5
which is the d’Alembert operator, sometimes denoted site sign convention.
⊲ G RADIENTS OF SCALAR FUNCTIONS OF RELATIVE DISTANCES IN 3D Very often electrodynamic quantities are dependent on the relative distance in R between two vectors x and x′ , i.e., on |x − x′ |. In analogy with equation (M.35) on page 189, we can define the primed del operator in the following way: ∇ ′ = xi ˆ ∂ = ∂′ ∂x′ i (M.98)
3
E XAMPLE M.6
Using this, the unprimed version, equation (M.35) on page 189, and elementary rules of differentiation, we obtain the following two very useful results: ∇ (|x − x′ |) = xi ˆ x − x′ ∂|x − x′ | ∂|x − x′ | = = − xi ˆ ′| ∂xi |x − x ∂x′ i
(M.99)
= − ∇′ (|x − x′ |) and ∇ 1 |x − x′ | = −
x − x′ = − ∇′ |x − x′ |3
1 |x − x′ |
(M.100)
⊳ E ND OF EXAMPLE M.6
Downloaded from
Version released 1st July 2008 at 20:49.
199
M. Mathematical Methods
E XAMPLE M.7
⊲ D IVERGENCE IN 3D For an arbitrary R3 vector field a(x′ ), the following relation holds: ∇′ · a(x′ ) |x − x′ | = ∇′ · a(x′ ) + a(x′ ) · ∇′ |x − x′ | 1 |x − x′ | (M.101)
which demonstrates how the primed divergence, defined in terms of the primed del operator in equation (M.98) on page 199, works. ⊳ E ND OF EXAMPLE M.7
E XAMPLE M.8
⊲ T HE L APLACIAN AND THE D IRAC DELTA A very useful formula in 3D R3 is ∇·∇ 1 |x − x′ | = ∇2 1 |x − x′ | = − 4πδ(x − x′ ) (M.102)
where δ(x − x′ ) is the 3D Dirac delta ‘function’. This formula follows directly from the fact that
V
d3x ∇ · ∇
equals −4π if the integration volume V(S ), enclosed by the surface S (V), includes x = x′ , and equals 0 otherwise. ⊳ E ND OF EXAMPLE M.8
1 |x − x′ |
=
V
d3x ∇ ·
−
x − x′ |x − x′ |3
=
S
d2x n · ˆ
−
x − x′ |x − x′ |3
(M.103)
E XAMPLE M.9
⊲ T HE CURL OF A GRADIENT Using the definition of the R3 curl, equation (M.46) on page 190, and the gradient, equation (M.41) on page 190, we see that ∇ × [∇α(x)] = ǫi jk xi ∂ j ∂k α(x) ˆ which, due to the assumed well-behavedness of α(x), vanishes: ǫi jk xi ∂ j ∂k α(x) = ǫi jk ˆ = + + ≡0 ∂ ∂ α(x) xi ˆ ∂x j ∂xk α(x) x1 ˆ α(x) x2 ˆ α(x) x3 ˆ (M.105) (M.104)
200
Version released 1st July 2008 at 20:49.
Downloaded from
Examples
We thus find that ∇ × [∇α(x)] ≡ 0 for any arbitrary, well-behaved R scalar field α(x). In 4D we note that for any well-behaved four-scalar field α(xκ ) (∂µ ∂ν − ∂ν ∂µ )α(xκ ) ≡ 0 so that the four-curl of a four-gradient vanishes just as does a curl of a gradient in R3 . Hence, a gradient is always irrotational. ⊳ E ND OF EXAMPLE M.9 (M.107)
3
(M.106)
⊲ T HE DIVERGENCE OF A CURL With the use of the definitions of the divergence (M.43) and the curl, equation (M.46) on page 190, we find that ∇ · [∇ × a(x)] = ∂i [∇ × a(x)]i = ǫi jk ∂i ∂ j ak (x) (M.108)
E XAMPLE M.10
Using the definition for the Levi-Civita symbol, defined by equation (M.18) on page 185, we find that, due to the assumed well-behavedness of a(x), ∂i ǫi jk ∂ j ak (x) = = + + ≡0 i.e., that ∇ · [∇ × a(x)] ≡ 0 for any arbitrary, well-behaved R3 vector field a(x). In 4D, the four-divergence of the four-curl is not zero, for ∂νGµν = ∂µ ∂ν aν (xκ ) −
2 µ
∂ ∂ ǫi jk ak ∂xi ∂x j a1 (x) a2 (x) a3 (x) (M.109)
(M.110)
a (xκ )
0
(M.111)
⊳ E ND OF EXAMPLE M.10
Downloaded from
Version released 1st July 2008 at 20:49.
201
M. Mathematical Methods
M.4 Bibliography
[1] G. B. A RFKEN AND H. J. W EBER, Mathematical Methods for Physicists, fourth, international ed., Academic Press, Inc., San Diego, CA . . . , 1995, ISBN 0-12-059816-7. [2] R. A. D EAN, Elements of Abstract Algebra, John Wiley & Sons, Inc., New York, NY . . . , 1967, ISBN 0-471-20452-8. [3] A. A. E VETT, Permutation symbol approach to elementary vector analysis, American Journal of Physics, 34 (1965), pp. 503–507. 191 [4] C. G. H EMPEL, Fundamentals of Concept Formation in Empirical Science, University of Chicago Press, Chicago, 1969, Tenth Impression. 182 [5] P. M. M ORSE AND H. F ESHBACH, Methods of Theoretical Physics, Part I. McGraw-Hill Book Company, Inc., New York, NY . . . , 1953, ISBN 07-043316-8. [6] B. S PAIN, Tensor Calculus, third ed., Oliver and Boyd, Ltd., Edinburgh and London, 1965, ISBN 05-001331-9. [7] W. E. T HIRRING, Classical Mathematical Physics, Springer-Verlag, New York, Vienna, 1997, ISBN 0-387-94843-0.
202
Version released 1st July 2008 at 20:49.
Downloaded from
Downloaded from
Version released 1st July 2008 at 20:49.
I NDEX
acceleration field, 100 advanced time, 46 Ampère’s law, 6 Ampère-turn density, 57 angular momentum density, 125 anisotropic, 117 anomalous dispersion, 118 antenna, 77 antenna current, 77 antenna feed point, 78 antisymmetric tensor, 148 associated Legendre polynomial of the first kind, 87 associative, 140 axial gauge, 49 axial vector, 149, 188 Bessel functions, 84 Biot-Savart’s law, 8 birefringent, 117 braking radiation, 108 bremsstrahlung, 108, 113 canonically conjugate four-momentum, 158 canonically conjugate momentum, 158, 191 canonically conjugate momentum density, 165 Cerenkov radiation, 119 characteristic impedance, 29 classical electrodynamics, 1, 9 closed algebraic structure, 140 coherent radiation, 112 collisional interaction, 116 complete α-Lorenz gauge, 48 complex field six-vector, 23 complex notation, 33, 181 complex vector, 197 component notation, 182 concentration, 190 conservative field, 12 conservative forces, 162 constitutive relations, 15 contravariant component form, 136, 182 contravariant field tensor, 149 contravariant four-tensor field, 186 contravariant four-vector, 184 contravariant four-vector field, 139 contravariant vector, 136 convection potential, 129 convective derivative, 13 cosine integral, 81 Coulomb gauge, 47 Coulomb’s law, 2 covariant, 134 covariant component form, 183 covariant field tensor, 149 covariant four-tensor field, 186 covariant four-vector, 184 covariant four-vector field, 139 covariant vector, 136 cross product, 188 curl, 190 cutoff, 131 cyclotron radiation, 110, 113 d’Alembert operator, 26, 43, 145, 199 definiendum, 182 definiens, 182 del operator, 189 del squared, 190 differential distance, 138 differential vector operator, 189 dipole antennas, 77 Dirac delta, 200 Dirac’s symmetrised Maxwell equations, 16 dispersive, 118 displacement current, 11
203
Index
divergence, 190 dot product, 186 dual electromagnetic tensor, 151 dual vector, 136 duality transformation, 17, 151 dummy index, 136 dyadic product, 187 dyons, 17 E1 radiation, 91 E2 radiation, 93 Einstein’s summation convention, 182 electric charge conservation law, 10 electric charge density, 4 electric conductivity, 11 electric current density, 8 electric dipole moment, 90 electric dipole moment vector, 54 electric dipole radiation, 91 electric displacement, 15 electric displacement current, 21 electric displacement vector, 53, 55 electric field, 3 electric field energy, 59 electric monopole moment, 53 electric permittivity, 116 electric polarisation, 54 electric quadrupole moment tensor, 54 electric quadrupole radiation, 93 electric quadrupole tensor, 92 electric susceptibility, 55 electric volume force, 60 electricity, 2 electrodynamic potentials, 40 electromagnetic field tensor, 149 electromagnetic linear momentum flux, 61 electromagnetic scalar potential, 41 electromagnetic vector potential, 40 electromagnetism, 1 electromagnetodynamic equations, 16 electromagnetodynamics, 17 electromotive force (EMF), 12 electrostatic scalar potential, 39 electrostatics, 2 electroweak theory, 1 energy theorem in Maxwell’s theory, 59 equation of continuity, 10, 145
equations of classical electrostatics, 9 equations of classical magnetostatics, 9 Euclidean space, 141 Euclidean vector space, 137 Euler-Lagrange equation, 164 Euler-Lagrange equations, 165, 191 Euler-Mascheroni constant, 81 event, 141 far field, 68 far zone, 71 Faraday’s law, 12 field, 183 field Lagrange density, 166 field point, 4 field quantum, 131 fine structure constant, 115, 131 four-current, 145 four-del operator, 189 four-dimensional Hamilton equations, 158 four-dimensional vector space, 136 four-divergence, 190 four-gradient, 190 four-Hamiltonian, 158 four-Lagrangian, 156 four-momentum, 143 four-potential, 145 four-scalar, 183 four-tensor fields, 185 four-vector, 139, 184 four-velocity, 143 Fourier integral, 28 Fourier series, 27 Fourier transform, 28, 44 free-free radiation, 108 functional derivative, 164 fundamental tensor, 136, 183, 186 Galileo’s law, 133 gauge fixing, 49 gauge function, 42 gauge invariant, 42 gauge transformation, 42 Gauss’s law of electrostatics, 5 general inhomogeneous wave equations, 42 generalised coordinate, 158, 191 generalised four-coordinate, 158
204
Version released 1st July 2008 at 20:49.
Downloaded from
Gibbs’ notation, 189 gradient, 189 Green function, 44, 87 group theory, 140 group velocity, 118 Hamilton density, 165 Hamilton density equations, 165 Hamilton equations, 158, 192 Hamilton function, 192 Hamilton gauge, 49 Hamiltonian, 192 Heaviside potential, 129 Heaviside-Larmor-Rainich transformation, 17 Helmholtz’ theorem, 43 help vector, 86 Hertz vector, 86 Hodge star operator, 17 homogeneous wave equation, 26 Hooke’s law, 162 Huygen’s principle, 44 identity element, 140 in a medium, 119 incoherent radiation, 113 indefinite norm, 137 index contraction, 136 index lowering, 136 induction field, 68 inertial reference frame, 133 inertial system, 133 inhomogeneous Helmholtz equation, 44 inhomogeneous time-independent wave equation, 44 inhomogeneous wave equation, 43 inner product, 186 instantaneous, 104 interaction Lagrange density, 166 intermediate field, 71 invariant, 183 invariant line element, 138 inverse element, 140 inverse Fourier transform, 28 irrotational, 6, 191 Jacobi identity, 151
Kelvin function, 114 kinetic energy, 162, 191 kinetic momentum, 161 Kronecker delta, 185 Lagrange density, 163 Lagrange function, 162, 191 Lagrangian, 162, 191 Laplace operator, 190 Laplacian, 190 Larmor formula for radiated power, 104 law of inertia, 133 Legendre polynomial, 87 Legendre transformation, 192 Levi-Civita tensor, 185 Liénard-Wiechert potentials, 95, 128, 148 light cone, 139 light-like interval, 139 line element, 187 linear mass density, 163 linear momentum density, 124 longitudinal component, 30 loop antenna, 81 Lorentz boost parameter, 142 Lorentz force, 14, 59, 128 Lorentz space, 137, 183 Lorentz transformation, 128, 135 Lorenz-Lorentz gauge, 47 Lorenz-Lorentz gauge condition, 43, 145 lowering of index, 186 M1 radiation, 92 Møller scattering, 115 Mach cone, 120 macroscopic Maxwell equations, 116 magnetic charge density, 16 magnetic current density, 16 magnetic dipole moment, 56, 92 magnetic dipole radiation, 92 magnetic displacement current, 21 magnetic field, 7 magnetic field energy, 59 magnetic field intensity, 57 magnetic flux, 12 magnetic flux density, 8 magnetic four-current, 152 magnetic induction, 8
Downloaded from
Version released 1st July 2008 at 20:49.
205
Index
magnetic monopole equation of continuity, 17 magnetic monopoles, 16 magnetic permeability, 116 magnetic susceptibility, 57 magnetisation, 57 magnetisation currents, 56 magnetising field, 15, 53, 57 magnetostatic vector potential, 40 magnetostatics, 6 massive photons, 169 mathematical group, 140 matrix form, 185 Maxwell stress tensor, 61 Maxwell’s macroscopic equations, 16, 58 Maxwell’s microscopic equations, 15 Maxwell-Lorentz equations, 15 mechanical Lagrange density, 166 metric, 183, 187 metric tensor, 136, 183, 186 Minkowski equation, 158 Minkowski space, 141 mixed four-tensor field, 186 mixing angle, 17 momentum theorem in Maxwell’s theory, 61 monochromatic, 65 multipole expansion, 85, 88 near zone, 71 Newton’s first law, 133 Newton-Lorentz force equation, 158 non-Euclidean space, 137 non-linear effects, 11 norm, 136, 198 null vector, 139 observation point, 4 Ohm’s law, 11 one-dimensional wave equation, 31 outer product, 187 Parseval’s identity, 75, 115, 130 phase velocity, 117 photon, 131 physical measurable, 33 plane wave, 31 plasma, 118
plasma frequency, 118 Poincaré gauge, 49 Poisson equation, 128 Poisson’s equation, 39 polar vector, 149, 188 polarisation charges, 55 polarisation currents, 56 polarisation potential, 86 polarisation vector, 85 positive definite, 141 positive definite norm, 137 potential energy, 162, 191 potential theory, 87 power flux, 59 Poynting vector, 59 Poynting’s theorem, 59 Proca Lagrangian, 168 propagator, 44, 87 proper time, 139 pseudo-Riemannian space, 141 pseudoscalar, 181 pseudoscalars, 188 pseudotensor, 181 pseudotensors, 188 pseudovector, 148, 181, 188 quadratic differential form, 138, 187 quantum chromodynamics, 1 quantum electrodynamics, 1, 47 quantum mechanical nonlinearity, 4 radial gauge, 49 radiation field, 68, 71, 100 radiation fields, 71 radiation resistance, 81 radius four-vector, 136 radius vector, 181 raising of index, 186 rank, 185 rapidity, 142 refractive index, 117 relative electric permittivity, 61 relative magnetic permeability, 61 relative permeability, 116 relative permittivity, 116 Relativity principle, 134 relaxation time, 28
206
Version released 1st July 2008 at 20:49.
Downloaded from
rest mass density, 166 retarded Coulomb field, 71 retarded potentials, 46 retarded relative distance, 95 retarded time, 46 Riemann-Silberstein vector, 23 Riemannian metric, 138 Riemannian space, 136, 183 row vector, 181 scalar, 181, 190 scalar field, 140, 183 scalar product, 186 shock front, 120 signature, 137, 196 simultaneous coordinate, 126 skew-symmetric, 149 skin depth, 33 source point, 4 space components, 137 space-like interval, 139 space-time, 137 special theory of relativity, 133 spherical Bessel function of the first kind, 87 spherical Hankel function of the first kind, 87 spherical harmonic, 87 spherical waves, 74 standard configuration, 134 standing wave, 78 super-potential, 86 synchrotron radiation, 110, 113 synchrotron radiation lobe width, 111 telegrapher’s equation, 31, 116 temporal dispersive media, 11 temporal gauge, 49 tensor, 181 tensor contraction, 186 tensor field, 185 tensor notation, 185 tensor product, 187 the Hertz method, 85 three-dimensional functional derivative, 165 time component, 137 time-dependent Poisson’s equation, 47
time-harmonic wave, 27 time-independent diffusion equation, 29 time-independent telegrapher’s equation, 31 time-independent wave equation, 29 time-like interval, 139 total charge, 53 total electromagnetic angular momentum, 125 total electromagnetic linear momentum, 125 transverse components, 30 transverse gauge, 48 uncoupled inhomogeneous wave equations, 43 vacuum permeability, 6 vacuum permittivity, 2 vacuum polarisation effects, 4 vacuum wave number, 29 variational principle, 191 ˇ Vavilov-Cerenkov cone, 120 ˇ Vavilov-Cerenkov radiation, 119, 120 vector, 181 vector product, 188 velocity field, 100 velocity gauge condition, 48 virtual simultaneous coordinate, 96, 100 wave equations, 25 wave vector, 31, 117 world line, 141 Young’s modulus, 163 Yukawa meson field, 168
Downloaded from
Version released 1st July 2008 at 20:49.
207 | https://www.scribd.com/document/17107623/EMFT-Book | CC-MAIN-2017-30 | refinedweb | 61,801 | 69.92 |
#include <qstereo.h>
#include <qstereo.h>
Collaboration diagram for QStereo:
QStereo class is a visualization widget for stereo camera devices. This calss can be used for the following purposes:
0
A constructor.
A destructor.
[protected, virtual]
[inline, slot]
Reset the stereo camera.
[signal]
Emitted when the size of camera images has been changed.
[virtual, slot]
Resize camera images.
Connect a stereo camera device.
[slot]
display an image on the screen.
Capture a pair of images from a stereo camera and show them.
Capture images from a stereo camera and show them periodically.
[inline]
Return the current stereo camera device.
Stop capturing images from a stereo camera.
[protected]
Stereo camera device.
Internal pixmap for double-buffering.
Memory buffer to store a left PNM image.
Painter for drawing.
Size of a PNM image.
Memory buffer to store a right PNM image.
The height of camera images.
The width of camera images. | http://robotics.usc.edu/~boyoon/bjlib/d2/dbb/classQStereo.html | CC-MAIN-2017-04 | refinedweb | 149 | 64.07 |
PTHREAD_JOIN(3) Linux Programmer's Manual PTHREAD_JOIN(3)
pthread_join - join with a terminated thread
#include <pthread.h> int pthread_join(pthread_t thread, void **retval); Compile and link with -pthread.).
On success, pthread_join() returns 0; on error, it returns an error number._join() │ Thread safety │ MT-Safe │ └───────────────┴───────────────┴─────────┘
POSIX.1-2001, POSIX.1-2008.)
This page is part of release 5.08 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2020-06-09 PTHREAD_JOIN(3)
Pages that refer to this page: pthread_attr_getdetachstate(3), pthread_attr_setdetachstate(3), pthread_cancel(3), pthread_create(3), pthread_detach(3), pthread_exit(3), pthread_timedjoin_np(3), pthread_tryjoin_np(3) | https://man7.org/linux/man-pages/man3/pthread_join.3.html | CC-MAIN-2020-40 | refinedweb | 113 | 51.75 |
Cantor – dynamic keywords in python backend
In previous post, I mentioned about dynamic keywords in python backend. The idea is, after import a python module in Cantor workspace, functions, keywords, variables, and more from this module are load by Cantor and available to syntax highlighting and tab complete.
This feature is implemented for now. You can test it compiling Cantor from python-backend branch.
But, let me show more information about this feature.
There are several ways to import a python module in python console. You have “import modulename”, “import modulename as modulevariable”, “from modulename import *”, “from modulename import function_1, function_2, …”, and more. Each import way causes different consequences to user experience.
The four import ways mentioned in previous paragraph are supported by python backend. I will show these different import ways and how python backend behave for each one.
import modulename
The more basic import way. After this command, a variable named “modulename” is defined and the functions and more keywords of this module are available to access using “modulename.keyword”.
Syntax Highlighting
import modulename as modulevariable
This way the user define a name “modulevariable” to reference “modulename”, and “modulename” is not defined. So, you can access the functions and more from “modulename” using “modulevariable.keyword”.
Tab Complete
Syntax Highlighting
from modulename import *
This way the user import all functions and keywords from “modulename” but anything variable is defined to access “modulename”. The functions of the module are accessed directly.
Tab Complete
Syntax Highlighting
from modulename import function_1, function_2, …
The user import only specific functions from a “modulename”, no all functions.
Tab Complete
Syntax Highlighting
Cantor plugin
I developed a Cantor plugin to import modules. This plugin open a dialog to user enter a modulename and, after press Ok, Cantor run “import modulename” and keywords are available. The diaglog is accessible by “Packaging” menu, in toolbar.
Cantor Plugin
Handling Errors
The backend can identify several errors during import.
Handling Errors
Conclusions
Well, the feature is working and it is mature for use, however it don’t support all import ways in python. But, I think these five ways cover the most commons import ways used by most python scientific users.
The important thing is, this feature enable python backend to support the several python modules, and no only scipy, numpy, and matplotlib, as I proposed in begin of this project.
Let me know how you import a module in python. I will develop support to more import ways in future versions of the backend.
For now, wait for more news of this project soon!
Maybe it would be worthwhile getting your blog posts about cantor added to the news section at the bottom of as with only an item from 2009 it looks rather dead?
Yes, after the python backend code merged in Cantor master branch, we will update this page.
Really, several backends are missing in this page (Octave, Qualculate, Scilab, and now, Python).
Another import that is important to consider is the __from_future__, particularly “division” and “print_statement”. Although these could be specified in a configuration dialog rather than having to manually run them each time, it would still be good to support running them manually.
Will it be possible to configure the python backend to automatically import particular modules when you first start it up? Either specifying modules in a configuration dialog, or better yet allowing you to specify arbitrary lines that are executed each time the backend is started (or both).
Thanks for your ideas @TheBlackCat.
I will see it after the end of GSoC. But, I think it will be available in a next version of the backend.
Great! Keep up the good work, I can’t wait to try it out.
Thanks @TheBlackCat! You are welcome! =)
[…] Cantor – dynamic keywords in python backend […]
Amazing! As a python scripter I really like this! Keep up the good work, cause it’s awesome!
Very thanks @snizzo! =) | http://blog.filipesaraiva.info/?p=1097 | CC-MAIN-2015-14 | refinedweb | 649 | 56.25 |
List of CGPoints
The following crashes on the last line and in objc_util.py on line 897. Any ideas how to get this working?
from objc_util import * load_framework('SpriteKit') SKShapeNode = ObjCClass('SKShapeNode') cg_points = [CGPoint(0,0), CGPoint(10,5), CGPoint(5,0)] node = SKShapeNode.shapeNodeWithSplinePoints_count_(cg_points, len(cg_points))
@mikael try this, I found something similar here
from objc_util import * load_framework('SpriteKit') SKShapeNode = ObjCClass('SKShapeNode') cg_points = [CGPoint(0,0), CGPoint(10,5), CGPoint(5,0)] cg_points_array = (CGPoint * len(cg_points))(*cg_points) node = SKShapeNode.shapeNodeWithSplinePoints_count_(cg_points_array, len(cg_points), restype=c_void_p,argtypes=[POINTER(CGPoint), c_ulong])
@mikael Obviously, but forum friends are there for that, isn't? Not always easy to search something, better if you (remember that you) got the same kind of problem.
- mithrendal
🥰 I fully agree. But the „you“ is valid for you both.
@mithrendal Sure! That was obvious for me, perhaps due to my poor English.
When I speak about "remember", it is always a reference to my bad and old memory 😇
- mithrendal
Vous etes super 😍 👍🏻 Je tellement aimes votre messages. That was my school french sorry it is poor too. 😌 | https://forum.omz-software.com/topic/5798/list-of-cgpoints/7 | CC-MAIN-2022-27 | refinedweb | 180 | 50.33 |
- You can find details about seeing a live version of this project, both web and Facebook interfaces, here.
Okay, we've been writing models, tests, and even forms, but we don't have any actual functionality yet. But, fear not, we're about to change that.
In this segment of the tutorial we are going to implement the most of our web app (just a layer between our users and the core app, where our fundamental functionality lives). Infact, we are going to implement everything except for the Ajax bits (we'll be implementing those in the next segment): soon we'll have something we can actually use in our web browser.
Writing the web/urls.py file
Now we're going to want to create a new file in our polling/web folder: urls.py.
emacs web/urls.py
And we're going to want two imports at the top of this file:
from django.conf.urls.defaults import * from polling.core.models import *
We want to make three different url patterns for the web project: one for viewing a list of polls, one for viewing a specific poll, and one for creating polls. This is going to look like this:'), )
Looking at the code, we are using something called generic views to avoid writing boilerplate generic code. The one thing we will need to write for these views is the template to be rendered.
Tweaking our Templates (for the generic views)
The urls.py file we are editing is in the *web application, and are being used to represent the Poll model, so the list and detail generic views are (by default, this behavior is overridable) going to be looking for templates in web/poll_list.html and web/poll_detail.html*.
Before we build those though, we'll want to put together a base template that all our web templates will end. We're going to put it at polling/templates/web/base.html and it should look something like this:
<html> <head> <title>{% block title %}A Generic Title{% endblock %}</title> </head> <body> {% block body %} {% endblock %} </body> </html>
Okay save that, and now we'll write a very simple template for representing a list of Poll objects. Make a file at polling/templates/web/poll_list.html. It should contain this:
{% extends "web/base.html" %} {% block title %} Our Polls! {% endblock %} {% block body %} <div id="polls"> {% for object in object_list %} <p id="poll{{ object.pk }}" ><a href="/poll/{{ object.pk }}/">{{ object }}</a> has a score of {{ object.score }}.</p> {% endfor %} </div> {% endblock %}
And now an equally simple template for displaying individual Poll objects:
{% extends "web/base.html" %} {% block title %} Poll: {{ object.question }} {% endblock %} {% block body %} <div id="poll"> <p>We have a question for you. {{ object.question }} <p> So far we have {{ object.up_votes }} upvotes and {{ object.down_votes }} downvotes, for an overall vote of {{ object.score }}! </p> <p> Do you <span id="upvote">agree</span> or <span id="downvote">disagree</span>? </p> </div> {% endblock %}
(We're going to be dealing with the up and down voting functionality (implemented via the JQuery javascript library) in the next segment of the series, for the moment we're just going to ignore the fact that we can't vote. A minor detail...)
One slightly less generic view
Now we need to put together one more view, and this one won't be generic so we'll have to write a slight bit of code for it. Its going to be the view for our "create a new poll" view. Earlier in our web/urls.py file we described where we're going to put it, so lets glance at our web/urls.py file for a moment.
(r'^create/$', 'polling.web.views.create'),
Right. Its going to be stored in a function named create in the polling/web/views.py file. Before we put the code together, lets briefly consider what we want the view to do. There are two things: allow users to create new polls, and also complain if the user attempts to create an invalid poll (in this case meaning that it asks the same question as a previously created poll).
First lets open up the views.py file in the web app.
emacs web/views.py
And now lets add some imports to the file
from django.http import HttpResponseRedirect from django.views.generic.simple import direct_to_template from polling.core.models import Poll, User from polling.core.forms import PollForm
We're going to be using our *PollForm for both rendering and validating the form for creating new polls. We need the Poll model to create new instances when the form is valid, and we need direct_to_template* for rendering the template we are going to create for this view (which will live at templates/web/create.html, but don't worry about that, since we'll be writing it in a moment).
The code for our view is going to have some simple logic to it:
- Check if there is attached POST data.
- If there is POST data, attempt to create a PollForm with it.
- If the new PollForm is valid, then create a new Poll and redirect to the main page.
- If the new PollForm is not valid, return the user to the same page, but display any error messages.
- If there is not POST data, display an empty form for users to describe their new Poll.
In Python, it is going to look like this:
def create(request): if request.method == 'POST': form = PollForm(request.POST) if form.is_valid(): # Because explaining in detail how to use the # authentication framework isn't within my # energy level at this exact moment u = User(name="Someone Else") u.save() poll = Poll(creator=u, question=form.cleaned_data['question']) poll.save() return HttpResponseRedirect('/') else: form = PollForm() return direct_to_template(request, 'web/create.html', extra_context={'form':form})
Now we just need to write a quick template to display our web.create view, and then we'll be all set.
Lets open up the template file
emacs templates/web/create.html
And this is what our template will look like:
{% extends "web/base.html" %} {% block title %} Creating a new Poll {% endblock %} {% block body %} <form method="post" action=""> <table>{{ form }}</table> <input type="submit" /> </form> {% endblock %}
And thats a wrap.
Putting our new code through its paces
Its a bit harder to write unittests for this kind of code. You can write code that verifies that each webpage is returning what you want, you can also hook into an HTML validator and verify that the pages are returning valid HTML. You could even write some multi-step interactions. The key is to make sure that your tests can resist a bit of change in your templates.
We're not going to explicitly write those tests, but its not a bad idea to work through them yourself. We will, on the other hand, do some quick informal testing with our browser to make sure these things are coming together correctly.
First we need to synchronize our database for our project:
python manage.py syncdb
You'll be asked to create a superuser. Go ahead and do so. Once the database synchronization finishes up, next we want to run the development server:
python manage.py runserver
And now lets fire up a browser and navigate to. We're going to create a poll first, because our generic views will complain if there are no polls (if this behavior really bothered us, we could change that behavior in our web/urls.py).
First go ahead and make a poll. It should redirect you to the list of polls. After that go back and try to create a poll with the same question. It should display an error message explaining that this poll has already been created. Good.
Go back to the poll listing and click on one of the polls and make sure that it behaves reasonably (displaying a few snippets of information about our poll).
A snapshot of the current development of this tutorial is available [here][polling4]. And feel free to move on to the fifth segment of this tutorial whenever you are ready. | http://lethain.com/two-faced-django-implementing-most-webapp/ | CC-MAIN-2014-52 | refinedweb | 1,356 | 73.78 |
UPDATE! Microsoft has just recently released a much better way to integrate Azure Machine Learning with Azure Stream Analytics. You can now call an AzureML service directly from the SQL query in the stream analytics system. This means you don’t need the message bus and microservice layer I describe below. Check out the blog by Sudhesh Suresh and the excellent tutorial from Jeff Stokes. I will do a performance analysis to compare this method to the one below, but I will wait until the new feature comes out of “preview” mode :). I will also use a better method to push events to the eventhub.
Doing sophisticated data analytics on streaming data has become a really interesting and hot topic. There is a huge explosion of research around this topic and there are a lot of new software tools to support it. Amazon has its new Kinesis system, Google has moved from MapReduce to Cloud DataFlow, IBM has Streaming Analytics on their Bluemix platform and Microsoft has released Azure Stream Analytics. Dozens of other companies that use data streaming analytics to make their business work have contributed to the growing collection of open source of tools. For example LinkedIn has contributed the original version of Apache Kafka and Apache Samza and Yahoo contributed Storm. And there are some amazing start-ups that are building and supporting important stream analytics tools such as Flink from Data-Artisans. Related university research includes systems like Neptune from Colorado State. I will post more about all of these tools later, but in this article I will describe my experience with the Microsoft EventHub, Stream Analytics and AzureML. What I will show below is the following
- It is relatively easy to build a streaming analytics pipeline with these tools.
- It works, but the performance behavior of the system is a bit uneven with long initial latencies and a serious bottleneck which is probably the result of small size of my experiment.
- AzureML services scale nicely
- Finally there are some interesting ways in which blocking can greatly improve performance.
In a previous post I described how to use AzureML to create a version of a science document analyzer that I originally put together using Python Scikit-Learn, Docker and Mesosphere. That little project is described in another post. The streaming challenge here is very simple. We have data that comes from RSS feeds concerning the publication of scientific papers. The machine learning part of this is to use the abstract of the paper to automatically classify the paper into scientific categories. At the top level these categories are “Physics”, “math”, “compsci”, “biology”, “finance”. Big streaming data challenges that you find in industry and science involve the analysis of events that may be large and arrive at the rate of millions per second. While there are a lot of scientists writing lots papers, they don’t write papers that fast. The science RSS feeds I pull from are generating about 100 articles per day. That is a mere trickle. So to really push throughput experiments I grabbed several thousands of these records and wrote a simple server that would push them as fast as possible to the analysis service.
In this new version described here I want to see what sort of performance I could get from AzureML and Azure Stream Analytics. To accomplish this goal I set up the pipeline shown in Figure 1.
Figure 1. Stream event pipeline
As shown in the diagram events (document abstracts) are initially pushed into the event hub which is configured as the source for the stream analytics engine. The analytics engine does some initial processing of the data and then pushes the events to a message queue in the Azure Message Bus. The events are then pulled from the queue by a collection of simple microservices which call the AzureML classifier and then push the result of the call into the azure table service.
In the following paragraphs I will describe how each stage of this pipeline was configured and I will conclude with some rather surprising throughput results.
Pushing events into the Event Hub.
To get the events into the Event Hub we use a modified version the solution posted by Olaf Loogman. Loogman’s post provides an excellent discussion of how to get an event stream from the Arduino Yun and the Azure event hub using a bit of C and Python code. Unfortunately the Python code does not work with the most current release of the Python Azure SDK[1], but it works fine with the old one. In our case all that we needed to do was modify Loogman’s code to read our ArXiv RSS feed data and convert it into a simple JSON object form
{ ‘doc’: ‘the body of the paper abstract’, ‘class’: ‘one of classes:Physics, math, compsci, bio, finance’, ‘title’: ‘ the title of the paper’ }
The Python JSON encoder is very picky so it is necessary to clean a lot of special characters out of the abstracts and titles. Once that is done it is easy to push the stream of documents to the Event Hub[2].
According to Microsoft, the Event Hub is capable of consuming many millions of events per second. My simple Python publisher was only able to push about 4 events per second to the hub, but by running four publisher instances I was up to 16 eps. It was clear to me that it would scale to whatever I needed.
The Stream Analytics Engine
The Azure stream analytics engine, which is a product version of the Trill research project, has a very powerful engine for doing on-line stream processing. There are three things you must do to configure the analytics engine for your application. First you must tell it where to get its input. There are three basic choices: the event hub, blob storage and the “IOT” hub. I configured it to pull from my event hub channel. The second task is to tell the engine where to put the output. Here you have more choices. The output can go to a message queue, a message topic, blob or table storage or a SQL database. I directed it to a message queue. The final thing you must do is configure the query processing step you wish the engine to do. For the performance tests described here I use the most basic query which simply passes the data from the event hub directly to the message queue. The T-SQL code for this is
SELECT * INTO eventtoqueue FROM streampuller
where eventtoqueue is the alias for my message bus queue endpoint and streampuller is the alias for my event queue endpoint. The original JSON object that went into the event hub emerges with top level objects which include the times stamps of the event entry and exit as shown below.
{ "doc": "body of the abstract", "class": "Physics", "title":"title of the paper", "EventProcessedUtcTime":"2015-12-05T20:27:07.9101726Z", "PartitionId":10, "EventEnqueuedUtcTime":"2015-12-05T20:27:07.7660000Z" }
The real power of the Analytics Engine is not being used in our example but we could have done some interesting things with it. For example, if we wanted to focus our analysis only on the Biology documents in the stream, that would only require a trivial change to the query.
SELECT * INTO eventtoqueue FROM streampuller WHERE class = ‘bio’
Or we could create a tumbling window and group select events together for processing as a block. (I will return to this later.) To learn more about the Azure Analytics Engine and T-SQL a good tutorial is a real-time fraud detection example.
Pulling events from the queue and invoking the AzureML service
To get the document events from the message queue so that we can push them to the AzureML document classifier we need to write a small microservice to do this. The code is relatively straightforward, but a bit messy because it involves converting the object format from the text received from the message queue to extract the JSON object which is then converted to the list form required by the AzureML service. The response is then encoded in a form that can be stored in the table. All of this must be encapsulated in the appropriate level of error handling. The main loop is shown below and the full code is provided in Github.
def processevents(table_service, hostname, bus_service, url, api_key): while True: try: msg = bus_service.receive_queue_message('tasks', peek_lock=False) t = msg.body #the message will be text containing a string with a json object #if no json object it is an error. Look for the start of the object start =t.find("{") if start > 0: t = t[start:] jt = json.loads(t) title = jt["title"].encode("ascii","ignore") doc = jt["doc"].encode("ascii","ignore") tclass = jt["class"].encode("ascii","ignore") evtime = jt["EventEnqueuedUtcTime"].encode("ascii", "ignore") datalist = [tclass, doc, title] #send the datalist object to the AzureML classifier try: x = sendrequest(datalist, url, api_key) #returned value is the best guess and #2nd best guess for the class best = x[0][1] second = x[0][2] #save the result in an Azure Table using the hash # of the title as the rowkey #and the hostname of this container as the table partition rk = hash(title) timstamp = str(int(time.time())%10000000) item = {'PartitionKey': hostname, 'RowKey': str(rk), 'class':tclass, 'bestguess':best, 'secondguess':second, 'title': title, 'timestamp': timstamp, 'enqueued': evtime} table_service.insert_entity('scimlevents', item) except: print "failed azureml call or table service error" else: print "invalid message from the bus" except: print "message queue error”
Performance results
Now that we have this pipeline the most interesting experiment is to see how well it will perform when we push a big stream of messages to it.
To push the throughput of the entire pipeline as high as possible we wanted as many instances of the microservice event puller as possible. So I deployed a Mesos Cluster with 8 dual core worker nodes and one manager node using the template provided here. To maximize parallelism for the AzureML service, three additional endpoints were created. The microservices were assigned one of the four AzureML service endpoints as evenly as possible.
We will measure the throughput in seconds per event or, more accurately, the average interval between event arrivals over a sliding window of 20 events. The chart below shows the seconds/event as the sliding window proceeds from the start of a stream to the end. The results were a bit surprising. The blue line represents one instance of the microservice and one input stream. As you can see there is a very slow startup and the performance levels out at about 1 second/event. The orange line is the performance with 12 microservice instances and four concurrent input streams. Again the startup was slow but the performance leveled off at about 4 events/sec.
Figure 2. Performance in Seconds/Event with a sliding window of 20 events. Event number on the x-axis.
This raises two questions.
- Why the slow startup?
- Why the low performance for 12 instance case? Where is the bottleneck in the pipeline? Is it with the Azure Stream Analytics service, the message bus or the AzureML service?
Regarding the slow startup, I believe that the performance of the Azure services are scaled on demand. In other words, as a stream arrives at the event hub, resources are allocated to try to match the processing rate with the event arrival rate. For the first events the latency of the system is very large (it can be tens of seconds), but as the pool of unprocessed events grows in size the latency between event processing drops very fast. However, as the pool of unprocessed events grows smaller small resources are withdrawn and the latency goes back up again. (We pushed all the events into the event hub in the first minute of processing, so after that point the number in the hub declines. You can see the effect of this in the tail of the orange curve in Figure 2.) Of course, belief is not science. It is conjecture.
Now to find the bottleneck that is limiting performance. It is clear that some resources are not scaling to a level that will allow us to achieve more than 4 events/second with the current configuration. So I tried two experiments.
- Run the data stream through the event hub, message bus to the microservices but do not call the AzureML service. Compare that to the version where the AzureML service is called.
- Run the data stream directly into the message bus and do not call the AzureML service. Compare that one to the others.
The table below in Figure 3 refers to experiment 1. As you can see, the cost of the AzureML service is lost in the noise. For experiment 2 we see that the performance of the message bus alone was slightly worse that the message bus plus the eventhub and stream analytics. However, I expect these slight differences are not statistically significant.
Figure 3. Average events per second compairing one microservice instance and one input stream to 8 microservices and 4 input streams to 8 microservices and 4 input streams with no call to AzureML and 8 microservices with 4 input streams and bypassing the eventhub and stream analytics.
The bottom line is that the message bus is the bottleneck in the performance of our pipeline. If we want to ask the question how well the AzureML service scales independent of the message bus, we can replace it with the RabbitML AMQP server we have used in previous experiments. In this case we see a very different result. Our AzureML service demonstrates nearly linear speed-up in terms of events/sec. The test used an ancreasing number of microservices (1, 2, 4, 8, 12, 16 and 20) and four endpoints to the AzureML service. As can be seen in Figure 4 the performance improvement lessens when the number of microservice instances goes beyond 16. This is not surprising as there are only 8 servers running all 20 instances and there will be contention over shared resources such as the network interface.
Figure 4. AzureML events per second using multiple microservice instances pulling the event stream from a RabbitMQ server instance running on a Linux server on Azure.
Takeaway
It was relatively easy to build a complete event analytics pipeline using the Azure EventHub, Azure Stream Analytics and to build a set of simple microservices that pull events from the message bus and invoke an AzureML service. Tests of the scalability of the service demonstrated that performance is limited by the performance of the Azure message bus. The AzureML service scaled very well when tested separately.
Because the Azure services seems to deliver performance based on demand (the greater the number unprocessed events in the EventHub, the greater the amount of resources that are provisioned to handle the load.) The result is a slow start but a steady improvement in response until a steady state is reached. When the unprocessed event pool starts to diminish the resources seem to be withdrawn and the processing latency grows. It is possible that the limits that I experience were because the volume of the event stream I generated was not great enough to warrant the resources to push the performance beyond 4 events/sec. It will require more experimentation to test that hypothesis.
It should also be noted that there are many other ways to scale these systems. For example, more message bus queues and multiple instances of the AzureML server. The EventHub is designed to ingest millions of events per second and the stream analytics should be able to support that. A good practice may be to use the Stream Analytics engine to filter the events or group events in a window into a single block which is easier to handle on the service side. The AzureML server has a block input mode which is capable of processing over 200 of our classification events per second, so it should be possible to scale the performance of the pipeline up a great deal.
[1] The Microsoft Azure Python folks seem to have changed the namespaces around for the Azure SDK. I am sure it is fairly easy to sort this out, but I just used the old version.
[2] The source code is “run_sciml_to_event_hub.py” in GitHub for those interested in the little details. | https://esciencegroup.com/tag/azure/ | CC-MAIN-2021-39 | refinedweb | 2,745 | 60.95 |
I would like to know what is the best structure and best practice the React component for you ? (With redux).
Thanks !
As a starter for 10:
I always ensure
props,
className and
children are always treated in the same way.
spreadoperator
This ensure all components are very flexible for future use as any extra attributes will always be added even if you hadn't coded for them.
import React from 'react'; import bemHelper from 'react-bem-helper'; import './styles.scss'; const bem = bemHelper({prefix: 'n-', name: 'button'}); export default class Button extends React.Component { constructor(props) { super(props); } static propTypes = { className: React.PropTypes.string, secondary: React.PropTypes.bool, href: React.PropTypes.string }; static defaultProps = { secondary: false }; render() { const {className, secondary, children, ...props} = this.props; const classes = bem(null, { 'secondary': secondary, 'primary': !secondary }, className ); const tag = this.props.href ? 'a' : 'button'; return React.createElement(tag, {...classes, ...props}, children); } }
a great project for you to take a look at, especially as far as adding redux goes is react-lego. It has a redux branch there showing you the code changes needed to turn a normal container/component into a redux component. | https://codedump.io/share/pwmwhkSlmGYL/1/best-structure-for-a-react-component | CC-MAIN-2017-13 | refinedweb | 189 | 50.94 |
Scala Varargs
Most of the programming languages provide us variable length argument mobility to a function, Scala is not a exception. it allows us to indicate that the last argument of the function is a variable length argument. it may be repeated multiple times. It allows us to indicate that last argument of a function is a variable length argument, so it may be repeated multiple times. we can pass as many argument as we want. This allows programmers to pass variable length argument lists to the function. Inside function, the type of args inside the declared are actually saved as a Array[Datatype] for example can be declared as type String* is actually Array[String].
Note :- We place * on the last argument to make it variable length.
Syntax : –
def Nameoffunction(args: Int *) : Int = { s foreach println. }
Below are some restrictions of varargs :
- The last parameter in the list must be the repeating argument.
def sum(a :Int, b :Int, args: Int *)
- No default values for any parameters in the method containing the varargs.
- All values must be same data type otherwise error.
> sum(5, 3, 1000, 2000, 3000, "one")
> error: type mismatch;
found : String("one")
required: Int
- Inside the body args is an array, so all values are packed into an array
Example :
Output :
Sum is: 6008
In above example we can see the last argument of the function is a variable length argument. here 1000 is variable length argument. argument arg is added to the result variable. the names argument is of type Integer.
Example :
Output :
Geeks for geeks
In above example as we have defined it using the * syntax so it is a variable argument. the names argument is of type String. | https://www.geeksforgeeks.org/scala-varargs/ | CC-MAIN-2022-33 | refinedweb | 285 | 64.2 |
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.
It's not me doing it. It's students and faculty. I'm just passing along a reproducible failure. If I change that to #include <iostream>, I have to add 'using namespace std;', and it makes no difference to the end result. Still fails. That syntax may be deprecated, but there is still a LOT of code out there using it, and a lot of books that list it the old way as well. Thanks for the attempt though. -- Nathan mikas493@student.liu.se wrote: > > Hello > Is there a reason for using the old, deprecated <iostream.h> when you should > use > <iostream>? You might want to test your program using <iostream> instead. > > Good luck! > > ----- Original Message ----- > From: "Neulinger, Nathan R." <nneul@umr.edu> > To: <libstdc++@gcc.gnu.org>; <gcc-bugs@gcc.gnu.org> > Sent: Tuesday, March 20, 2001 9:18 PM > Subject: Problems with cin.getline on solaris 2.x > > > > > > > > > > ---cut--- > > > > or > > > > ---run on sol 2.7 piped--- > > arstest(40)> echo fred | ./getln > > > arstest(41)> > > --- > > > > ---run on linux and any other box--- > > infinity(97)>./getln > > > > > > -- ------------------------------------------------------------ Nathan Neulinger EMail: nneul@umr.edu University of Missouri - Rolla Phone: (573) 341-4841 CIS - Systems Programming Fax: (573) 341-4216 | http://gcc.gnu.org/ml/libstdc++/2001-03/msg00179.html | crawl-001 | refinedweb | 213 | 79.16 |
- Author:
- heckj
- Posted:
- June 4, 2007
- Language:
- Python
- Version:
- .96
- sql middleware terminal logging
- Score:
- 7 (after 7 ratings)
A handy ANSI-colored logging mechanism to display the SQL queries and times in the terminal when using django-admin.py runserver. DEBUG mode must be true for this to work.
More like this
- SQL Log Middleware by joshua 9 years, 5 months ago
- SQL Log Middleware w/query count & exec time by tobias 9 years, 4 months ago
- Middelware to remember sql query log from before a redirect by miracle2k 8 years, 11 months ago
- SQL Log Middleware - with multiple databases by guglielmocelata 5 years, 6 months ago
- SQL Log To Console Middleware by davepeck 7 years ago
Where the connection object on the 5th line comes from?
#
from django.db import connection
#
I guess it would be helpful to include that line
to the snippet itself :)
#
Please login first before commenting. | https://djangosnippets.org/snippets/264/ | CC-MAIN-2016-36 | refinedweb | 152 | 50.09 |
Is it bad practice to use the same names for classes inside tools that both get executed into the same python environment, simultaneously?
I've created two python widgets as seen in the image below. Each of the widgets contain QTreeViews that use their own custom SortModel.
I was wondering if it's bad practice to name both of the SortModel and MainWindow classes the same between the two files?
Because i later load both files into the same tool as Tabs. I'm starting to get some weird bugs in the program and I have a feeling this may be causing it.
Considering you have to import both classes into the same module namespace, using the same name for distinct classes is more of a bad idea than a bad practice.
The current module will use only one of the classes for all cases where you need one of both; weird results.
However, you can distinguish one from the other at the import level by using the
import as feature:
from camera_publish import SortModel as CameraSortModel from cache_publish import SortModel as CacheSortModel | https://codedump.io/share/26uqNsJkPAsW/1/python-class-duplication | CC-MAIN-2017-13 | refinedweb | 183 | 59.64 |
This article is on reaching ports, controlling external devices and electronics. Perhaps you are asking "why?" The idea is simple: It is to achieve something that is real, physical and emotional. As a freelancer I have been coding for about 4 years for my own interest. At first I started with C but now for the GUI, I use mostly C# . Therefore a lot of people participating in the codeproject can declare and assign a variable in more than one language:
int variable = 5;
$variable = 5;
Dim variable As Integer = 5
We can do things, however we do same things using different methods. By working in different ways we improve our skills, but everyday something new comes and we need to look for the references. For eg: there are differences in .NET Framework 1.0 and 1.1, MSDN says "we have improved" blah blah blah... Who cares?!... As a result, you need to make some changes in your old program and this is a pain...
Anyway, a friend of mine said: "You have to pass your electronic knowledge with everybody..." This is why I am writing this article.
A port contains a set of signal lines that the CPU sends or receives data with other components. We use ports to communicate via modem, printer, keyboard, mouse etc. In signaling, open signals are "1" and close signals are "0" so it is like binary system [See Part 3]. A parallel port sends 8 bits and receives 5 bits at a time. The serial port RS-232 sends only 1 bit at a time but it is multidirectional so it can send 1 bit and receive 1 bit at a time...
Parallel Port - Data Ports:
In my application, I used the data ports which can be seen in the picture from D0 to D7
These ports are made for reading signals. The range is like in data ports which are S0-S7. But S0, S1, S2 are invisible in the connector (See my picture in the article). I mentioned these are for reading signals but S0 is different, this bit is for timeout flag in EPP (Enhanced Parallel Port) compatible ports. The address of this status port is 0x379 . this will always be refer to "DATA+1" and it can send 5 numeric data from the 10 - 11 - 12 - 13 - 15 th pins. So how can we reach the data ports? It is simple: every parallel port has an address. In Windows 2000, you can see yours by Settings > Control Panel > System > Hardware > Device Manager > Ports (COM & LPT) > Printer Port(LPT1) > Properties = in Resources > Resource Setting and you can see your address for your parallel port. For Ex: Mine is 0378-037F. This is hexadecimal like in math (mod 16). 0x378 belongs to 888 in decimal form. In this way you can look for your com port or game port addresses. Let's enlighten these bits with a printer example:
This port usually used for outputting but these can be used for inputting. The range is like in data ports C0-C7 but C4, C5, C6, C7 are invisible in connector. And the address for this is 0x37A
These are (G0 - G7) the pins from 18 to 25 . These are mostly used for completing the circuit.
After these I used data ports in my application because there are reversed pins in control and status ports. Here is an explanation for reversed pins: While you are not sending any signals to the data port it is in closed position like "00000000" so the 8 pins have no voltage on it (0 Volt) .If you send decimal "255" (binary "11111111") every pin (D0-D7) has a +5 Volt... On the other hand, if I used control ports, there are reversed pins which are C0, C1 and C3 so while we send nothing to the control port its behaviour is "0100" in binary (decimal "11")... If I receive e-mails from you I can make apps using control and status ports...
And also I get different angled pictures of my complete circuit. Click for the bigger ones.
Ok then let's find out what we have to supply:
Assemble the circuit as in the picture if it is not clear, e-mail me as ls@izdir.com and I will send you the bigger pictures of the circuits...
Binary = 0, 1 --> 2 digit
Decimal = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 --> 10 digit
Hexadecimal = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F --> 16 digit
The logic is in these three examples but nobody does the conversion like this. They use Windows operating system's scientific calculator. So if a conversion is needed I use Start > Programs > Accessories > Calculator . or you can make your own conversion program. Also you can check my loop (enumerated checkboxes) func in my app for binary to decimal conversion.
I used inpout32.dll in my app for interoping. You can check the workflow below for inpout32.dll and also you can get the source of the dll from here .
Note: I am importing it with the reference of So for further info about the driver check out the site...
In my PortInterop.cs I used the following:
using System;
using System.Runtime.InteropServices;
public class PortAccess
{
[DllImport("inpout32.dll", EntryPoint="Out32")]
public static extern void Output(int adress, int value);
}
PortAccess.Output.
Output
PortAccess
PortAccess.Output(888, 255);
And for null data we have to send "0" to the Output method like:
null
PortAccess.Output(888, 0);
I wrote a func for reseting the LEDs which is:
private void Reset_LEDs()
{
PortAccess.Output(adress, 0);
}
I didn't use loops for checkboxes and pictureboxes you can also enumerate these for quick coding. First, I do like that but after I changed to several if-else statements because I had to change the GUI. But I left them on the code for performance issues anyone who want speed can use these.
if-else
You can also reach your ports with Turbo C++ like:
#include <conio.h>
#include <dos.h> // For _out
#define port 0x378 // Port Address
#define data port+0 // Data Port of the parallel cable
void main (void)
{
_out(data, 255); // For all lights on
_out(data, 0); // For all lights off
}
I think you will find this to be the most exciting part of this article... So what can you do besides powering small LEDs? You can... Search the net about relays for triggering higher voltages, search some electrical newsgroups and then make circuits and connect them to your parallel port, light up your room lights or turn on your TV etc etc... You can do a thousand things it is up to your imagination... I am planning to write more articles about relays, lcds, oscillators and things like that (of course with PC connection)... Below is a picture of my next article.... | http://www.codeproject.com/Articles/4981/I-O-Ports-Uncensored-1-Controlling-LEDs-Light-Emit?fid=21021&df=90&mpp=25&sort=Position&spc=Relaxed&select=4383010&tid=3948189 | CC-MAIN-2016-36 | refinedweb | 1,154 | 72.87 |
Hello Friends!
If you'd like to read up on Week 11, click here.
Finally! We finally began learning about a topic that began hearing whispers about ever since the beginning of the bootcamp...REACT!
DOM Manipulation in Plain JS
One of the big struggles of building a larger application front-end was managing how to manipulate the DOM and creating re-usable code that would render or update DOM elements.
In plain Javascript, you'd work with classes and/or functions that would explicitly create DOM, kinda of like the code I used to build my project last week:
class CharacterSelection{ static renderPage(bodyElement){ clearElements(bodyElement) let chooseTop = document.createElement('div'); chooseTop.className = "choose-top"; let chooseMid = document.createElement('div'); chooseMid.className = "choose-mid"; let chooseBottom = document.createElement('div'); chooseBottom.className = "choose-bottom"; this.renderTop(chooseTop); bodyElement.appendChild(chooseTop); this.renderMid(chooseMid); bodyElement.appendChild(chooseMid); this.renderBottom(chooseBottom); bodyElement.appendChild(chooseBottom) } static renderTop(chooseTop) { let titleText = document.createElement('p'); titleText.textContent = "CHOOSE YOUR CHARACTER" chooseTop.appendChild(titleText); }
A limitation of this was that if I wanted to re-use an element in another page, I wouldn't easily be able to
REACT
React is a library built by Facebook specifically designed to build Web Application User Interfaces with an emphasis on performance.
In React, you no longer have to explicitly create HTML elements (like div, or img etc.), you work with Components.
Similar to how ActiveRecord provided some methods to help build backend stuff, React is an awesome tool to help us as long as we follow React convention and understand some React specific terminology and some advanced Javascript concepts like:
JSX (Javascript XML): Special React syntax that makes creating DOM elements really easy and easy to read when you get used to it. Here's a sample of it for a small practice program I was writing.
const GifDisplay = (props) => { return ( <div> <img src={props.gifUrl}</img> <div/> ); }; export default GifDisplay;
Context: As javascript programmers we need to be cognizant about where we are calling methods, especially when we call methods within classes. Understanding the this keyword is critical in React.
Callbacks: Certain Components may need to pass data around, or you might take data and map them into components. Either way, Javascript's callbacks definitely have significance in React.
Functional or Class: React components can (for the most part) be divided into either 'Functional' or 'Class'. I won't dive into this right now, but just know that it's important to understand why we use either.
State & Props: As a front-end designer, I now have to make decisions about how components hold data (state) and pass/handle data (props). Below is another snippet of a practice program I am currently building.
class IntroductionContainer extends Component { constructor(props) { super(props); this.state = { // set up the state buttonTextArray: ["Enter"] // the text that will be passed to the button container to create buttons }; } //renders the content container and navBar for the introduction page render() { return ( <div className="page-container"> <IntroductionContentContainer /> <NavBarContainer buttonTexts={this.state.buttonTextArray} handleButtonClick={this.props.handleEnterButtonClick} /> </div> ); } } export default IntroductionContainer;
The Challenge This Week
To be honest, the work load (pretty much all labs) has been heavy, but that isn't what was most challenging for me this week. The most challenging thing this week has been preventing myself from getting overwhelmed by the sheer amount of libraries and plug-ins that work with React to make some really jaw-dropping web applications.
I know we will be having a project due in the next couple weeks, and I want to be able to make an application somewhat similar to some absolutely fantastic websites I've seen! Here's one ESPECIALLY cool one I saw:
When I see super neat-o websites like Bruno's site, I find it hard not to explore libraries when really, I should be focusing on the React fundamentals
What's Next?
Next week is our code challenge, which I am feeling confident about. I still want to play around with some React styling libraries like Semantic UI. For the time being, I'll just be practicing React through lectures, videos, readings and actual mini coding projects. I'll be sure to update all of you next week!
Good luck in your own endeavors!
Shawn
Discussion (3)
Hey Shawn!
I would like to gather some info on how Flatiron is working out for you, and I also have some general questions about the process! I love your series about the boot camp, it definitely got my attention!
Keep up the hard work, and I wish you the best of luck with your assignments!
Kindly add me on Discord(ofeher#6265) so we can chat/talk about it!
Thanks,
Oliver
Hi Oliver!
I'll be sure to connect up with you on discord :)! Look forward to chatting!
Thanks, please do! I have the deadline coming up pretty soon, I would love to char before I make a decision. | https://dev.to/shawnhuangfernandes/booting-up-bootcamp-week-10-react-2gc9 | CC-MAIN-2021-31 | refinedweb | 827 | 54.12 |
Hello Jay
Have you defined a content type for the category like this?
[ContentType] public class BasicCategory : CategoryData { }
David
Hi Jay,
Yes, you need to define the content type as David mentioned.
More info available here-
Hey Jay,
Can you please try this on alloy project and if it works on the alloy then you can compare if something is missing?
Deleting CategoryData class did the trick, still doesn't show Categories in the Nav but I can live with that
Not sure, but it's possible that resetting the views for your user could help:
Log in to the CMS -> click the little profile icon in the top right -> select "My Settings" -> go to the "Display Options" tab -> click "Reset Views"
Hi,
Just installed EpiCategories 1.2.9 on CMS 11.9.0< managed to get everything set up (I think) but when I try and add a category the only option I get is New from Template!
Anyone help me figure out where I have gone wrong?
Thanks | https://world.optimizely.com/forum/developer-forum/CMS/Thread-Container/2020/3/geta-epicategories---cant-add-categories/ | CC-MAIN-2022-33 | refinedweb | 170 | 64.64 |
.
Boost bimap - a two way map
#include <boost/bimap.hpp> typedef boost::bimap< string, string > map_type; map_type m; m.insert( map_type::value_type("ABC","ABC.X.Y") ); m.insert( map_type::value_type("DEF","DEF.X.Y") ); m.insert( map_type::value_type("GHI","GHI.X.Y") );
The above
typedef defines a two way map where both keys and values are of type
std::string. You could use other types, for example
<int,string> and so on. By default the resulting bimap will internally store data in two
std::map equivalent data structures with string as key and string value type.
To use boost::bimap you need to only include headers and add path to header file to your compiler include path.
Data in those two internal structures are accessible through
left and
right accessors. They are both signature equivalent to
std::map<string,string> and
std::map<string,string>. Additionally there is a way to access the relationship between those two structures which is not shown here.
You can access data via:
map_type::left_map& view_type = m.left;
or
map_type::right_map& view_type = m.right;
Iterating over bimap using each side as key
We can create a method that takes a collection, and uses collection's iterator to access key-value pairs using standard
std notation:
template < class MapType > void dump( const MapType& m) { typedef typename MapType::const_iterator const_iterator; for ( const_iterator iter(m.begin()), iend(m.end()); iter != iend; ++iter ) { std::cout << iter->first << "-->" << iter->second << std::endl; } }
We call the above method with either
left or
right collection from the bimap created before.
Once again, the
left collection uses the original key to access values.
The
right collecton is the reverse map using
values from the first collection to access
keys. The code looks like this:
dump( m.left ); dump( m.right );
Output looks like this:
// using left collection key --> value ABC-->ABC.X.Y DEF-->DEF.X.Y GHI-->GHI.X.Y // using right collection 'value' --> 'key' ABC.X.Y-->ABC DEF.X.Y-->DEF GHI.X.Y-->GHI
Another way of iterating over one or the other side looks like this, substitute
left for
right to get the reverse mapping:
map_type::left_map& map_view = m.left; for (map_type::left_map::const_iterator it(map_view.begin()), end(map_view.end()); it != end; ++it) { cout << (*it).first << " --> " << (*it).second << endl; }
Output:
ABC --> ABC.X.Y DEF --> DEF.X.Y GHI --> GHI.X.Y
Additionally, you can access the relationship which is not shown here but you can find examples in boost::bimap documentation.
Specify different types of collection in bimap
There are many options how to construct
boost::bimap. You can specify what type of data structure should be used for
each of collections and even what type of mapping to use for the relationship between
left and
right side.
In my case I have unique strings with one-to-one mapping on each side. I create the
bimap on startup and then only use for lookup by either key.
hash-maps seem like perfect candidate here, in
bimap they are specified by
unordered_set_of type.
See boost::bimap examples and reference for more explanation and examples.
To use hash-maps use appropriate parts above with the following code:
Add another header file
#include <boost/bimap.hpp> #include <boost/bimap/unordered_set_of.hpp>
Use appropriate namespace so you don't have to prefix everything with
boost::for readability
using namespace boost::bimaps;
Define
map_typeusing hash_maps, or
unordered_set_ofas they are called in boost::bimap;
typedef boost::bimap< unordered_set_of< string > , unordered_set_of< string > > map_type;
The rest of the code works the same way.
This shows some very basic usage of
boost::bimaps. You can use them whenever you need to access collection in
c++
by key, value or by mapping relationship. Boost's
bimap provides options to configure each type of internal structures to fit your requirements. | http://mybyteofcode.blogspot.com/2010/02/representing-bidirectional-relationship.html | CC-MAIN-2017-47 | refinedweb | 633 | 57.27 |
Difference between revisions of "Introduction to SourcePawn 1.7"
Latest revision as of 03:28, 14 October 2019.
Contents
- 1 Non-Programmer Intro
- 2 Language Paradigms
- 3 Variables
- 4 Arrays
- 5 Enums
- 6 Strings
- 7 Functions
- 8 Expressions
- 9 Conditionals
- 10 Loops
- 11 Scope
- 12 Dynamic Arrays
- 13.
Enums
Enums are retyped integers. A new enum can be declared as follows:
enum MyEnum // the name is optional { MyFirstValue, // == 0, if not explicitly assigned, the first value is zero MySecondValue, // == 1, implicitly set to the previous value plus one MyThirdValue = 1, // == 1, explicitly assign to one -- multiple names can share the same value MyFourthValue, // == 2 }
To allow implicit conversions of enums back to integers (that is, so functions expecting a value of type 'int' accepts it as one instead of generating a warning), the enum must either be anonymous (unnamed) or must start with a lowercase character..
Characters
A character of text can be used in either a String or a cell. For example:
char text[] = "Crab"; char:
int clams[] = "Clams"; // Invalid. int clams[] = {'C', 'l', 'a', 'm', 's', 0}; // Valid, but NOT A STRING.
Concatenation
In programming, concatenation is the operation of joining character strings end-to-end. The benefit of this is to improve the readability of the source code for humans, since the compiler will continue to treat the strings as a single string. String literals can be concatenated with the ... or \ operator:
char text[] = "This is a really long string of text that should be split over multiple lines for the sake of readability." char text[] = "This is a really long string of text that should be " ... "split over multiple lines for the sake of readability."; // Valid. char text[] = "This is a really long string of text that should be \ split over multiple lines for the sake of readability."; // Valid. char prefix[] = "What you can't do, however, "; char moreText[] = prefix ... "is concatenate using a non-literal string."; // Invalid, not a constant expression..:
int a = 5;
In this example a is an l-value and 5 is an r-value.
The rules:
- Expressions are never l-values.
- Variables are both l-values and r-values.
Conditionals
Conditional statements let you only run code if a certain condition is matched. { /* body */ } while ( /* condition */ );. */ int SearchInArray(const int array[], int count, int value) { int index = -1; for (int::
void Function1() { int: = new int.
Extended Variable Declarations
Variables can be declared in more ways than simply int float or char.
static
The static keyword is available at global and local scope. It has different meanings in each.#.
Local static
A local static variable is a global variable that is only visible from its local lexical scope. For example:
int MyFunction(int inc) { static int:
int MyFunction(int inc) { if (inc > 0) { static int counter; return (counter += inc); } return -1; } | https://wiki.alliedmods.net/index.php?title=Introduction_to_SourcePawn_1.7&diff=10869&oldid=9737 | CC-MAIN-2019-51 | refinedweb | 469 | 64 |
Use the Amazon Dash button and a bit of Python to create and assign tickets on the fly.
The Amazon Dash button first needs to be connected to your local network. Once you have your Dash Button, go through the initial setup BUT DO NOT COMPLETE IT. Once the Dash Button is connected to your wireless network, it will ask you which product you want to associate with the button. Exit the Dash Button setup at this step, unless you want to order laundry detergent every time a ticket is submitted. This is also a good time to turn of Dash Button notifications in the Amazon Mobile App, otherwise you will get a notification asking you to complete the setup of the Dash Button every time it is pressed.
We will be using Python and the Scapy library, so make sure you have both of those installed. The code below will sniff the network for ARP packets and print the corresponding MAC address. Once this code is running, go ahead and press your Dash Button.)
Depending on how busy your network is, you may need to push the Dash Button a few times in order to narrow down its MAC address.
This is the Python scrip that will run looking for the ARP request from your button, and send an email if it finds your Dash Button. We will save this as ticket.py
import os
import time
timed = 0
wait = 0
from scapy.all import *
def arp_display(pkt):
if pkt[ARP].op == 1: #who-has (request)
if pkt[ARP].psrc == '0.0.0.0': # ARP Probe
if pkt[ARP].hwsrc == '00:11:22:33:44:55': #button MAC
timestamp = int(time.time())
global wait
global timed
if (timestamp > wait) or (timed == 0):
print timestamp
print "New Ticket Button Pressed!"
os.system('python sendmail.py')
wait = timestamp + 60
timed = 1
print sniff(prn=arp_display, filter="arp", store=0, count=0)
Please note that '00:11:22:33:44:55' needs to be changed to the MAC address of your Dash Button found in the previous step.
This is the code that runs when ticket.py sees the Dash Button come online. This will be called sendmail.py
import smtplib
sender = 'button@domain.com' #Address emails will be sent to
receivers = ['support@domain.com'] #Your spiceworks support address
message = """From: TheButton
To: Support
Subject: New Button Support Ticket
New Support Button ticket created.
#assign Username
"""
try:
smtpObj = smtplib.SMTP('emailserver', 25) #Your email server
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except smtplib.SMTPException:
print "Error: unable to send email"
You will need to change all email address, "#assign Username, and the email server to match your environment
When you press the button, it will turn on, connect to the wireless network, and send out an ARP packet. ticket.py will identify the packet from your button, and start sendmail.py. sendmail.py will then email your support address, and assign the ticket to a user.
Hopefully this will minimize the amount of tickets that slip through the cracks and never get created. Our button has been stuck to the inside of the IT department door, so it can easily be pressed on our way out. Don't forget to create an email address for whatever you email you decide to have the button send from, and make that account an admin in Spiceworks so that you can take full control of Tickets Anywhere tags. I in no way consider myself a programmer, so I'm sure there are some changes that could be made to these scripts to get them more inline with best practices.
What a cool idea!
I think that it might be useful to get a bit more feedback on how it works out for you; if there are any specific issues or drawbacks that you came across, or if you found it helpful or not.
But a nice how to overall.
This would be great on the side of printers and copiers in organizations where I.T. is responsible for toner changes. "Toner Replacement Button Pressed - Printer 1" or something like that.
Really, it could work in any situation where you don't necessarily need to know who found the problem, just that the problem exists.
This sounds awesome but how would you know whom or where the ticket is about or going to. Seems like it would just make a blank ticket or am i missing a step?
That's a really great idea. I was trying to think of things to use the button for too, but this is way ahead of what I was imagining. Thanks for sharing!
@wingzfann99 you hit the nail on the head! I was essentially thinking the same thing. Have it on the copiers. If you wanted you could make a pedestal by the copier that says "Press this button for a jamming issue" "press this button for scanning issues" etc... then each button submits the ticket with different information as to what is wrong. This though would be an awesome tool for a critical piece of equipment somewhere.
Now that's thinking outside the box. What a great idea!
WOW! ... I can't believe how much I want to do this now. I can just see putting them on copiers and having them order their toner or paper. Not to mention putting a OMG button someplace important. I can just see taking apart one of these and then 3D printing a "PANIC" button instead. THE POSSIBILITIES ARE ...well, limited but still "fun" :-)
Now Amazon needs to start selling blank buttons in packs so we can do ALL OF THE IOTs!!! .... then we run out of IPs, again.
This is awesome! I love the idea and have been thinking about using these buttons for IoT in my house. You can imagine turn lights on or off, enabling/disabling alarms or other similar activities.
Truthfully, the possibilities are endless here. I find it amazing that Amazon could sell something like this for a relatively low price and that it could be so powerful in completely different use cases than intended.
That is a pretty cool idea. I would probably break it in the first week from over using, but I might have to give it a try.
While I think the concept is pretty cool, and I could definitely see some good uses for this, I worry a little about basing ticket creation off arp requests. What happens if the device simply learns the mac-address of the router and stops sending arp-requests?
Sulk! The Dash button is only available in the USA, so being in the UK I can't order a few to start playing around with! :-(
fun! just don't let THAT user get hold of it. (you know the one ...)
Rad post and walk through m8. Really brilliant Idea. I quite like it, I just worry about giving users that kind of power. It will make them lazy and even less grateful....
WOW, Amazing!!! Now all I have to do is get my hands on a "Dash Button"
I would use this to be a second restart button for everybody on their computer. Pre-IT ticket step, "P.E.B.K.A.C. push button". If computer still has issues, then call. I can't count the number of times that people say they have restarted their computer after I ask and come to find out a restart was all it needed. | https://community.spiceworks.com/how_to/123640-create-an-iot-button-to-submit-and-assign-tickets | CC-MAIN-2019-39 | refinedweb | 1,249 | 73.78 |
Textbooks: Nelson Essentials of Pediatrics, Pediatric Secrets, First Aid for Pediatric Clerkship--------------------------------------------------------------------------------------------------------------------------------------------Common Problems in PediatricsPreventative: Immunizations, Normal Growth and DevelopmentCough: URI, Asthma, Pneumonia, Bronchiolitis, Allergic RhinitisFever: Common Viral Illnesses, UTI, Occult Bacteremia, Meningitis, Febrile SeizuresSore Throat: Group A Beta-Hemolytic Streptococcal Pharyngitis, MononucleosisEar Pain: Otitis Media, Otitis ExternaAbdominal Pain: Gastroenteritis, UTI, PID, Functional Abdominal PainDermatitis: Atopic Dermatitis, Viral Exanthems, Impetigo, Monilial and Tinea Infections, ScabiesHeart Murmurs: Innocent Murmurs, Septal DefectsDevelopmental: Developmental Delay, Failure to ThriveHematology: Sickle Cell Disease, ThalassemiasNephrology: UTI, Nephrotic/Nephritic Syndromes, ProteinuriaChronic: Allergies, Asthma, Cerebral Palsy, Cystic Fibrosis, Diabetes Mellitus, Seizure Disorders--------------------------------------------------------------------------------------------------------------------------------------------Procedures: NEJM Videos In Clinical Medicine: To Succeed – First Aid For The Pediatrics Clerkship (Stead, Stead, & Kaufman)Be On Time: Most wards teams begin rounding around 8am. Give yourself at least 15 minutes per patient for pre-rounding to learn about events that occurred overnight or lab/imaging results.Dress In A Professional Manner: Regardless of what the attending wears. A short white coat should be worn overyour professional dress clothes unless it is discouraged.Act In A Pleasant Manner: The medical rotation is often difficult, stressful, and tiring. Smooth out your experienceby being nice to be around. Smile a lot and learn everyone’s name. Don’t be afraid to ask how your resident’sweekend was. If you do not understand or disagree with a treatment plan or diagnosis, do not “challenge.” Instead,say “I’m sorry, I don’t quite understand, could you please explain...” Show kindness and compassion toward yourpatients. Never participate in callous talk about patients.Take Responsibility: Know everything there is to know about your patients: their history, test results, details abouttheir medical problem, and prognosis. Keep your intern or resident informed of new developments that they mightnot be aware of, and ask them for any updates you might not be aware of. Assist the team in developing a plan;speak to radiology, consultants, and family. Never give bad news to patients or family members without theassistance of your supervising resident or attending.Respect Patient’s Rights:1) All patients have the right to have their personal medical information kept private. This means do not discuss thepatient’s information with family members without that patient’s consent, and do not discuss any patient inhallways, elevators, or cafeterias.2) All patients have the right to refuse treatment. This means they can refuse treatment by a specific individual (you,the medical student) or of a specific type (no nasogastric tube). Patients can even refuse life-saving treatment. Theonly exceptions to this rule are if the patient is deemed to not have the capacity to make decisions or understandsituations, in which case a health care proxy should be sought, or if the patient is suicidal or homicidal.3) All patients should be informed of the right to seek advanced directives on admission. Often, this is done by theadmissions staff, in a booklet. If your patient is chronically ill or has a life-threatening illness, address the subject ofadvanced directives with the assistance of your attending.More Tips: Volunteer, be a team player, be honest, and keep patient information handy.Present In An Organized Manner: “This is a [age] year old [gender] with a history of [major/pertinent history suchas asthma, prematurity, etc. or otherwise healthy] who presented on [date] with [major symptoms, such as cough,fever, and chills], and was found to have [working diagnosis]. [Tests done] showed [results]. Yesterday/ overnightthe patient [state important changes, new plan, new tests, new medications]. This morning the patient feels [state thepatient’s words], and the physical exam is significant for [state major findings]. Plan is [state plan].”On Outpatient: The ambulatory part of the pediatrics rotation consists of mainly two parts: focused histories andphysicals for acute problems and well-child visits. Usually, you will see the patient first, to take the history and dothe physical exam. It is important to strike a balance between obtaining a thorough exam and not upsetting the childso much that the attending won’t be able to recheck any pertinent parts of it. For acute cases, present the patientdistinctly, including an appropriate differential diagnosis and plan. In this section, be sure to include possibleetiologies, such as specific bacteria, as well as a specific treatment (e.g., a particular antibiotic, dose, and course of
treatment). For presentation of well-child visits, cover all the bases, but focus on the patients’ concerns and yourfindings. There are specific issues to discuss depending on the age of the child. Past history and development isimportant, but so is anticipatory guidance–prevention and expectations for what is to come. The goal is to be bothefficient and thorough.--------------------------------------------------------------------------------------------------------------------------------------------Top 100 Secrets – Pediatric Secrets (4th, Polin & Ditmar)1) Methods to increase compliance by adolescents with medical regimens include the following: simplifying theregimen, making the patient responsible, discussing potential side effects, using praise liberally, and educating thepatient.2) A pelvic examination is not required before prescribing oral contraceptives for teenagers without risk factors.Appropriate screening for sexually transmitted diseases and possible cervical dysplasia can be scheduled, butdelaying oral contraception unnecessarily increases the risk of pregnancy.3) Emergency contraception should be discussed with all sexually active adolescents; 90% of teenage pregnanciesare unintended.4) Teenagers with attention deficit hyperactivity disorder (ADHD) and conduct disorders are at high risk forsubstance abuse disorders. Substance abuse is often associated with comorbid psychiatric disorders.5) Calluses over the metacarpophalangeal joints of the index and/or middle fingers (Russell sign) may indicaterepetitive trauma from self-induced attempts at vomiting in patients with eating disorders.6) Appreciating that ADHD is a chronic condition (like asthma or diabetes) is useful for management strategies,follow up, and ongoing patient/parental education and involvement.7) Although colic is common and resolves spontaneously by 3 months, do not underestimate the physical andpsychological impact of the condition on a family.8) Bilingual children develop speech milestones normally; two-language households should not be presumed as acause of speech delay.9) Most amblyopia is unilateral; vision testing solely with both eyes open is inadequate.10) Congenitally missing or misshapen teeth can be markers for hereditary syndromes.11) Syncope in a deaf child should lead one to suspect prolongation of the QT wave on the electrocardiogram.12) Bounding pulses in an infant with congestive heart failure should cause one to consider a large patient ductusarteriosus.13) If a bruit is heard over the anterior fontanel in a newborn with congestive heart failure, suspect a systemicarteriovenous fistula.14) The chief complaint in a child with congestive heart failure may be nonspecific abdominal pain.15) Diastolic murmurs are never innocent and deserve further cardiac evaluation.16) Patients with atypical Kawasaki disease (documented by coronary artery abnormalities despite not fulfillingclassic criteria) are usually younger (<1 year old) and most commonly lack cervical adenopathy and extremitychanges.17) Neonates with midline lumbosacral lesions (e.g., sacral pits, hypertrichosis, lipomas) should have screeningimaging of the spine performed to search for occult spinal dysraphism.18) Hemangiomas in the "beard distribution" may be associated with internal airway hemangiomas.19) Infantile acne necessitates an endocrine workup to rule out precocious puberty.20) If a child develops psoriasis for the first time or has a flare of existing disease, look for streptococcalpharyngitis.21) Look for associated autoimmune thyroiditis in children who present with a family history of thyroid disease andextensive alopecia areata or vitiligo.22) Most cardiac arrests in children are secondary to respiratory arrest. Therefore, early recognition of respiratorydistress and failure in children is crucial.23) Because children are much more elastic than adults, beware of internal injuries after trauma; these can occurwithout obvious skeletal injuries.24) Because children get colder faster than adults as the result of a higher ratio of body surface area to body mass, besure that hypothermia is not compounding hemodynamic instability in a pediatric trauma patient in shock.25) Hypotension and excessive fluid restriction should be avoided at all costs in the child in shock with severe headinjury because such a patient is highly sensitive to secondary brain injury from hypotension.26) The most common finding upon the examination of a child's genitalia after suspected sexual abuse is a normalexamination.
27) Because the size of a normal hymenal opening in a prepubertal child can vary significantly, the quality andsmoothness of the contours of the hymenal opening, including tears and scarring, are more sensitive indicators ofsexual abuse.28) Palpation for an enlarged or nodular thyroid is one of the most overlooked parts of the pediatric physicalexamination in all age groups.29) Because 20-40% of solitary thyroid nodules in adolescents are malignant, an expedited evaluation is needed if anodule is discovered.30) Unless a blood sugar level is checked, the diagnosis of new-onset diabetic ketoacidosis can be delayed becauseabdominal pain can mimic appendicitis, and hyperventilation can mimic pneumonia.31) Beware of syndrome of inappropriate antidiuretic hormone secretion and possible cerebral edema if a normal orlow sodium level begins to fall with fluid replenishment during the treatment of diabetic ketoacidosis.32) Acanthosis nigricans is found in 90% of youth diagnosed with type 2 diabetes.33) Growth hormone deficiency present during the first year of life is associated with hypoglycemia; after the age of5 years, it is associated with short stature.34) Fecal soiling is associated with severe functional constipation.35) More than 40% of infants regurgitate effortlessly more than once a day.36) Nasogastric lavage is a simple method for differentiating upper gastrointestinal bleeding from lowergastrointestinal bleeding.37) Conjugated hyperbilirubinemia in any child is abnormal and deserves further investigation.38) Potential long-term complications of pediatric inflammatory bowel disease include chronic growth failure,abscesses, fistulas, nephrolithiasis, and toxic megacolon.39) Bilious emesis in a newborn represents a sign of potential obstruction and is a true gastrointestinal emergency.40) In patients with Down syndrome and behavioral problems, do not overlook hearing loss (both sensorineural andconductive); it occurs in up to two thirds of patients with this condition, and it can be a possible contributor to thosetypes of problems.41) Fluorescence in situ hybridization (FISH) is indicated for the rapid diagnosis of trisomies 13 and 18 and multiplesyndromes in children with moderate to severe mental retardation and apparently normal chromosomes(subtelomeric FISH probes).42) Three or more minor malformations should raise concern about the presence of a major malformation.43) The diagnosis of fetal alcohol syndrome is problematic in infants because facial growth and development canmodify previously diagnostic features over a 4- to 6-year period.44) Diabetes mellitus is the most common teratogenic state; insulin-dependent diabetic mothers have infants with aneight-fold increase in structural anomalies.45) An infant with nonsyndromic sensorineural hearing loss should be tested for mutations in the connexin 26 gene.Mutations in that gene contribute to at least about 50% of autosomal recessive hearing loss and about 10-20% of allprelingual hearing loss.46) In children <12 years old, the lower limit of normal for the mean corpuscular volume (MCV) can be estimatedas 70 + (the child's age in years)/mm3. For a patient that is more than 12 years old, the lower limit for a normalMCV is 82/mm3.47) In the setting of microcytosis, an elevated red blood cell distribution width index suggests a diagnosis of irondeficiency rather than thalassemia.48) After iron supplementation for iron-deficiency anemia, the reticulocyte count should double in 1-2 weeks, andhemoglobin should increase by 1 gm/dL in 2-4 weeks. The most common reason for persistence of iron deficiencyanemia is poor compliance with supplementation.49) Children with elevated lead levels are at increased risk for iron deficiency anemia because lead competitivelyinhibits the absorption of iron.50) Chronic transfusion therapy to reduce sickle hemoglobin levels to 30-40% of the total lowers the likelihood ofstroke.51) Because 30% of patients with hemophilia have no family history of the disorder, clinical suspicion is importantin the presence of excessive and frequent ecchymoses.52) Marked neutropenia (<500/mm3 absolute neutrophil count) in a previously healthy child often heralds the onsetof overwhelming sepsis.53) The determination of immunoglobulin G subclass concentrations is meaningless in children who are less than 4years old.54) Neutrophil deficiency should be considered in a newborn with a delayed separation of the umbilical cord (>3weeks).
55) Clinical features of autoimmunity do not exclude the diagnosis of a primary immunodeficiency.56) A male child with a liver abscess should be considered to have chronic granulomatous disease until it is provenotherwise.57) The most common congenital infection is cytomegalovirus, which in some large screening studies occurs in upto 1.3% of newborns, although most of these infants remain asymptomatic.58) Up to 25% of infants <28 days old with bacterial sepsis and positive blood cultures will have culture-confirmedmeningitis.59) Erythematous papules with a pale center ("doughnut lesions") located on the hard and soft palates arepathognomonic for streptococcal pharyngitis.60) The red man syndrome, which is a complication of vancomycin administration, can usually be avoided byslowing the rate of drug infusion or by premedicating with diphenhydramine.61) A petechial-purpuric rash in a glove-and-stocking distribution should raise the possibility of infection withparvovirus B19.62) Perinatal asphyxia accounts for less than 15% of cases of cerebral palsy.63) Because primary and secondary apnea are indistinguishable in newborns, the initial clinical response should beidentical in the delivery room.64) Hyperbilirubinemia is generally not an indication for the cessation of breast-feeding but rather for increasing itsfrequency.65) Sepsis is in the differential diagnosis of virtually every neonatal sign and symptom.66) Breast feeding lowers the risks of necrotizing enterocolitis and nosocomial sepsis.67) Ten percent of febrile infants with documented urinary tract infections have normal urinalyses; this emphasizesthe importance of obtaining a urine culture if clinical risk factors are present.68) Vigorous correction of constipation has been shown to diminish both enuresis and the frequency of urinary tractinfections.69) Chromosomal and endocrinologic evaluation should be done if testes are bilaterally undescended andnonpalpable or one or two testicles are undescended with hypospadias present.70) In patients with acute renal failure, the measurement of urinary indices (urine sodium concentration, fractionalexcretion of sodium, urine specific gravity, and osmolality) should be done before initiating any therapy to helpdistinguish between prerenal, renal, and postrenal etiologies.71) The two most productive facets of patient evaluation to explain renal disease as a possible cause of symptomsare as follows: (1) the measurement of blood pressure and (2) the examination of the first morning void after thebladder is emptied of urine stored overnight (when a specimen is most likely to be concentrated).72) The most common cause of persistent seizures is an inadequate serum antiepileptic level.73) Antiepileptic drugs in tablet and capsule form produce less variation in blood concentrations than liquidpreparations, particularly suspensions, do.74) Resist polypharmacy: three or more medications have not been shown to improve seizure control as comparedwith one or two drugs, and side effects and compliance become much more problematic.75) The diagnosis of cerebral palsy is rarely made at <1 year old because neurologic findings in infancy are subjectto significant change.76) Migraine headaches are usually bilateral in children but unilateral (75%) in adults.77) Seizures with fever in patients older than 6 years of age should not be considered febrile seizures.78) Children with fever and neutropenia must continue to receive broad-spectrum antibiotics until definitive signs ofmarrow recovery are documented, typically with the presence of a peripheral monocytosis and an absoluteneutrophil count >200/mm3 and rising.79) Empiric antifungal agents are administered to children with neutropenia who remain febrile or develop newfever within 3 to 7 days of starting broad-spectrum antibiotics because the risk of invasive fungal infection increaseswith the duration and depth of neutropenia.80) After age and white blood cell count, early response to therapy is the most important prognostic feature forchildren with acute lymphoblastic leukemia.81) Leukemias and lymphomas that have a high proliferation and cell turnover rate (e.g., Burkitt's lymphoma, T-celllymphoblastic leukemia) place patients at the highest risk of complications from tumor lysis syndrome.82) Eighty percent or more of patients who present with acute lymphoblastic leukemia have a normochromic,normocytic anemia with reticulocytopenia.83) Because it changes more quickly as inflammation changes, C-reactive protein is better than sedimentation ratefor monitoring the response to therapy in patients with osteomyelitis.
84) Pseudoparalysis (with decreased arm or leg movement) with no systemic illness may be a presenting sign in aninfant with osteomyelitis.85) Back pain is atypical for scoliosis and may point to another diagnosis.86) Consider magnetic resonance imaging for patients with scoliosis and the less common left-sided thoracic curvesbecause 5-7% of these patients can have intraspinal abnormalities (e.g., hydromelia).87) A plain x-ray is unreliable in the diagnosis of developmental dysplasia of the hip in infants less than 6 months ofage because ossification of the femoral head is incomplete.88) Older children with unexplained unilateral deformities (e.g., pes cavus) of an extremity should have screeningmagnetic resonance imaging to evaluate for intraspinal disease.89) Asthma rarely causes clubbing in children. Consider other diseases, particularly cystic fibrosis.90) Most children with recurrent pneumonia or persistent right middle lobe atelectasis have asthma. But … all thatwheezes is not asthma.91) Home peak flow monitoring is most helpful in those asthmatic patients with very labile disease or poor symptomrecognition.92) A normal respiratory rate strongly argues against a bacterial pneumonia.93) Upper lobe pneumonias with radiation of pain to the neck can cause meningismus and mimic appendicitis; lowerlobe pneumonias can present with abdominal pain.94) Nasal polyps or rectal prolapse in children suggests cystic fibrosis.95) The three most common causes of anaphylaxis in pediatric hospitals and emergency departments are latex, food,and drugs. Suspected allergies to shellfish, peanuts, and nuts warrant a prescription for an epinephrine pen becauseof the increased risk of future anaphylaxis.96) Up to 10% of normal, healthy children may have low-level (1:10) positive-antinuclear antibody (ANA) testingthat will remain positive. Without clinical or laboratory features of disease, it is of no significance.97) The daily spiking fevers of systemic juvenile rheumatoid arthritis can precede the development of arthritis byweeks to months.98) Antistreptolysin O antibodies are positive in only 80% of patients with acute rheumatic fever. Test for anti-DNase B antibodies to increase the likelihood to more than 95% when diagnosing a recent group A beta-hemolyticinfection.99) Because up to 10% of patients can have asymptomatic Borrelia burgdorferi infection and because bothimmunoglobulin M and immunoglobulin G antibodies to B. burgdorferi can persist for 10-20 years, the diagnosis ofLyme disease in older children and adolescents can be tricky in patients with atypical clinical presentations.100) Abdominal pain (mimicking an acute abdomen) and arthritis can frequently precede the rash in Henoch-Schönlein purpura disease and thus confuse the diagnosis.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Neonatology with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Newborn Skin* Newborn infant at birth is noted to have acrocyanosis, a heart rate of 140, grimaces to stimulation, and is activewith a lusty cry. What is her APGAR score?* APGAR score 0: no heart rate, no respirations, no muscle tone, no reflex irritability (e.g. bulb suction), blue body.* APGAR score 1: HR < 100, weak cry, some extremity flexion, some reflex motion, pink body blue extremities.* APGAR score 2: HR > 100, vigorous cry, arms/legs flexed, reflex cry/withdrawal, pink all over.* Virginia Apgar, an anesthesiologist, developed the APGAR score. Useful tool for immediate assessment of thechild. It is not used for later in life, only at birth. Useful for determining progression of resuscitation.* APGAR is for appearance, pulse, grimace, activity, and respirations.* Score 0 to 3 at one minute requires resuscitation. Do not wait for one minute though. 4 can be poor also.* Poor score at 5 minutes does not predict subsequent cerebral palsy. Poor score at 20 minutes predicts highermorbidity and mortality.* Score 8 to 10 is good. Scores 5 to 7 are fair. Newborn is any child under the age of 28 days.* Newborn infants has a blue-gray pigmented lesion on the sacral area. It is clearly demarcated and does not fadeinto the surrounding skin. What is the most likely diagnosis? Answer is Mongolian spot. They are more commonlyseen in dark-skinned races. Up to 5% of Caucasian newborns will have it.* Differential diagnosis includes child abuse, so document Mongolian spots to prevent subsequent issues. Bruiseswill fade into surrounding skin; in that case consider child abuse. Mongolian spots can occur on any part of thebody, typically seen on the buttocks or sacral area. They fade in months to a year.* Mongolian spots caused by heightened receptor response to melanocyte stimulating hormone.
* Erythema toxicum is very common in newborns and should be differentiated from staphylococcal scalded skinsyndrome (SSSS). Erythema toxicum does not appear in the first day of life, usually shows in 2-3 days. It ischaracterized by erythematous macules that can become blisters or pustules. It is migratory, such that the next daythere may be clearing in some spots and new erythema in other spots.* Pustules of erythema toxicum neonatorum (red rash of the newborn), if scraped, will contain many eosinophils.* Staphylococcal scalded skin may be present in the first day of life, may present with pustules, skin will start topeel off. If you scrap it, it will form a blister like a burn (Nikolsky sign). Pustules will be full of neutrophils.* SSS babies will be ill, toxic in appearance, can have sepsis.* Treat erythema toxicum with reassurance of the parents.* Sebaceous gland hyperplasia looks like lots of little whiteheads, in areas that are more oily like nose. Treatment isto leave them alone.* Milia comes in fine-white (miliaria crystallina) and red (miliaria rubra). Benign.* Ebstein pearls are commonly seen in the mouth (mucous membranes) along the midline, just a collection ofstratified epithelium and tends to go away. Do not confuse with torus palatinus, an actual deformity of the hardpalate where it curves down. That is permanent and can be covered by mucous membrane, cause no issues.* Cutis marmorata looks like cobblestone blood-vessels. Can occur when the baby is cold. It is secondary tovasomotor instability. As they get older, it gets better. Cutis marmorata telangiectasia congenita does not go away asthe child gets older. Cutis marmorata sometimes seen in Down syndrome.* Neonatal acne (acne neonatorum) is a heightened receptor response to circulating estrogens. Usually shows arounda week to two weeks. Goes away, no need to treat with acne medications.* Newborn has a flat salmon-colored lesion on the glabella, which becomes darker red when he cries. What is thebest course of management? This is a salmon patch, also known as nevus flammeus. Best course of management isreassurance of parents. This goes away as the child gets older. Nevus simplex is also known as “stork bite.”* Salmon patch seen over the eyelids, bridge of the nose, and back of the neck. Also known as a “stork bite” (on theneck) or “angel kisses” (on the forehead/nose).* Nevus flammeus divided into salmon patch (goes away) and port-wine stain (does not go away, hemangioma,associated with Sturge-Weber syndrome. 50% of babies are born with salmon patch. Facial lesions tend to go away,neck lesions may stay but are covered with hair.* Capillary hemangioma, also known as strawberry hemangioma usually starts as flat macular lesion. May get largerduring first few months of age, raised lesion. After first year of life, they tend to regress slowly. In general, there isno need to go cut them out as this results in bleeding since they are a collection of blood vessels. No need to do lasertreatment either. Only do treatment if the lesion is over a vital structure.* Baby presents with capillary hemangioma on the skin and stridor. Think about subglotic hemangioma.* As capillary hemangiomas get better, they start to turn bluish and get boggy like an abscess.* Nevus sebaceous (nevus of Jadassohn) is present at birth. It is salmon fleshy colored and there will be no hairgrowth coming through the lesion. They are only seen on the scalp. Treatment is to follow until adolescent age andthen remove. There is some minor risk of malignancy, so remove after child is no longer growing.* Café-au-lait are light-brown in color (coffee with milk) and also known as “giraffe spots.” They may or may notbe associated with underlying diseases (neurofibromatosis, McCune Albright syndrome, Von Hipple Lindau).* Harlequin baby will have redder skin closer to the ground/gravity. This is due to vasomotor instability.--------------------------------------------------------------------------------------------------------------------------------------------Birth Trauma* Cephalhematoma is a collection of fluid underneath the bone. Must be differentiated from caput hematoma. Acephalhematoma is a subperiosteal bleed, since it is beneath the bone it is limited by the bone, thus it will not crossthe suture lines. A caput is a scalp swelling so it does cross suture lines.* Cephalhematomas tend to get worse over a few days and can take weeks to months to resolve. As the resolve, youcan feel the volcano rim or crater, which is the edge of the cephalhematoma. Even if they are bilateral, they will notcross the suture line so you should be able to feel a groove in between the hematomas.* Caput hematomas starts to get better as soon as the baby is delivered.* Differential diagnosis of a cephalhematoma includes a depressed skull fracture.* Subcutaneous fat necrosis is a type of birth injury. Associated with birth trauma or forceps use. Will be firmrubbery nodules, can be seen anywhere like cheeks, buttocks, back, extremities.* Brachial palsies occur with stretching of the brachial plexus, such as forceps or arm pulling.* Erb-Duchenne palsy involves C5-C6 and arm will be internally rotated, wrist flexed, “waiter’s tip” or “secretsmoker.” Ipsilateral hemi-diaphragmatic paralysis means C4 is also affected.
* Klumpke palsy involves C8-T1 and hand will have fingers flexed, “claw hand.” If sympathetic fibers of T1 areaffected the child may have a Horner syndrome. Horner is anhidrosis, ptosis, myosis. Horner is a guy whoseforehead is dry, can’t see the sky, and has a small eye.* Facial palsy will have no ipsilateral movement with crying. These palsies tend to be fairly mild and resolve.* Clavicle is the most commonly fractures bone during delivery. Babies tend to be large for gestational age, such aswhen the mother has gestational diabetes. Shoulder dystocia during delivery predisposes to fracture. Baby may notmove their arm well or has an asymmetric Moro response or mother notices a lump (callous already forming). Forthe most part, these fix themselves, no need to splint in a figure-of-eight. May feel crepitus on affected side.* Subconjunctival hemorrhages are temporary. You see blood in the eye, due to birth pressure.--------------------------------------------------------------------------------------------------------------------------------------------Congenital Anomalies* Coloboma is a defect in the iris, may look like a keyhole, also known as “latch key eye”. Can have a coloboma ofthe eyelid, choroid, or retina.* Aniridia is lack of iris, usually bilateral. Baby will not have a colored part of the eye. Aniridia plus hemi-hypertrophy is associated with Wilms tumor.* Congenital cataract will have no red-reflex on the affected side. Eye appears cloudy, there is an opacity in the lens.Baby may be born with cataract or be developing it due to something like galactosemia.* White reflex implies retinoblastoma until proven otherwise. Red reflex and be red or orange or tan.* Pre-auricular skin tags are generally a normal variant. There is a slightly higher association with cleft lip/palate.* Pre-auricular dimple or pit is a normal variant. There is a slightly higher association with hearing abnormalities.* Microtia is grossly malformed misshapen ears. Much higher association with renal abnormalities (e.g. Potter).* Macroglosia is huge tongue, can obstruct the airway and cause feeding difficulties. Can be seen in Downsyndrome, Beckwith-Wiedemann Syndrome, or a normal variant.* Ankyloglossia also known as “tongue tie” at the bottom of the tongue. Generally no need to intervene. Do not snipthe attachment as there is an artery that runs through this area. If baby can get tongue to edge of gums (most can)they will be able to nurse well and speak well.* Branchial cleft cysts are generally unilateral and can become infected, drain, require antibiotics, and sometimesneed to be closed or removed.* Congenital torticollis also known as “wry neck” is balling-up of sternocleidomastoid. Child will keep its head tothe side. You may be able to feel a knot on that side of the neck. Treat with passive range of motion, moving head toopposite side. Some torticollis patients may have a hemi-vertebra in the neck associated with certain syndromes.* Breast hypertrophy is due to heightened response of receptors to circulating hormones. It goes away as the babygets older. There may even be discharge from the breast.* Supernumerary nipples (polythelia) will be anywhere along the mammary “milk” lines. There is an associationwith renal and cardiovascular anomalies. Most people with polythelia do not have problems though.* Poland syndrome is absence of the pectoralis muscle with amastia on that side, can have rib deformities, webbedfingers, and radial nerve aplasia.* Pectus excavatum also known as “funnel chest” and pectus carinatum also known as “pigeons chest”. These arenormal variants and should be left alone. Very rarely do they cause cardiac problems, such as cor pulmonale frompectus excavatum. Most common reason for having them fixed is cosmetic.* Polycystic kidney is the most commonly palpated mass in the abdomen of a neonate. Next most common is likelya large bladder, maybe secondary to posterior urethral valves.* Umbilical hernias are commonly seen. This is incomplete closure of the fascia umbilical ring. Old school mythwas to put a large coin on it and tape it down. Treatment is to leave it alone. After about a year, they will haveclosed either way (coin taping or leaving it alone). Nearly all close by age 5.* Omphalocele is due to embryologic development. Intestines come out in-utero, do 270-degree flip, and come backin. In omphalocele, the intestines did not come back in. There is a sac “-cele” with this deformity. This is a midlinedefect and is a surgical emergency. Generally, this is diagnosed on ultrasound so the surgical team is ready at birth.* Gastroschisis does not have a sac. This is usually to the right of the umbilicus. Since it is not contained, there is amuch higher risk for volvulus and malrotation. More likely to have ischemia. Surgical emergency.* Imperforate anus can occur. Never take a newborn’s temperature with a rectal thermometer as this could perforatethe anus. Symptoms include no defecation within the first 24 hours of life.* Epispadias is urethral meatus opening on the dorsum of the penis. Hypospadias is on the ventral side. Right belowthe tip of the glans is a first-degree, along the shaft is a second-degree, and at the base of the shaft is third-degreehypospadias. Usually there is a hooded prepuce seen in hypospadias or isolated chordee. Hypospadias is acontraindication for circumcision as all the tissue will be needed for the repair.
* Retractile testicle means there is an active cremasteric reflex, where testicle slides up with touching or coldtemperature. Undescended testicle means it is not palpable or is palpable in the inguinal canal but cannot be broughtdown. If it is undescended at one year of age, it has to be surgically brought down as there is a higher risk ofmalignancy and will become atrophic.* Ebstein pearls can also occur on the penis; anywhere with mucous membranes.* Hydrocele suspected with enlarged scrotum. Can be transilluminated. Hernias reduce, hydroceles do not.* Syndactyly is when fingers do not separate in development. X-ray to determine if 1 or 2 fingers. If 2 fingers,surgery may be considered.* Polydactyly is extra fingers. If there is a well developed bone with vascular supply, consider leaving finger. If nobone present in extra finger or just a stalk, tie-off with a suture and it will auto-amputate.* Amniotic band occurs when there is a little tear in the amnion in-utero and the baby gets it’s finger through. Whenthe amnion heals up, it compresses and creates a band. Could cause phocomelia where entire arm is deformed.--------------------------------------------------------------------------------------------------------------------------------------------Neonatal Screening Tests* One-month old fair-haired fair-skinned baby presents with projectile vomiting of 4-days duration. Physical examreveals a baby with eczema and a musty (mousy) odor. Which screening test would most likely be abnormal? Thisbaby presents similar to pyloric stenosis. This is phenylketonuria (PKU).* Major three for screening are PKU, galactosemia, hypothyroidism. Some places will test for maple syrup urinedisease or sickle cell anemia.* PKU is a defect in the hydroxylation of phenylalanine to tyrosine. It is autosomal recessive. What are the chancesthat this family will have another affected child? Answer is 1 in 4. Occurs in about 1:10,000 live births.* In PKU, babies are normal at birth. Mental retardation is the most common manifestation. Commonly seen in fair-haired, fair-skinned, blue-eyed population. Rash looking like atopic dermatitis or eczema may be present.* Screening test for PKU is best done at 48-72 hours after starting to take in protein.* If positive PKU screening test, then do blood levels of phenylalanine (high) and tyrosine (normal levels).* Treatment for PKU is dietary, low phenylalanine formula and then low phenylalanine diet. Avoid things likeaspartame (sugar substitute), which is common in diet drinks.* Complications include mental retardation, microcephaly, and congenital heart disease.* Galactosemia is a defect in galactose-1-phosphate-uridyltransferase. Patients are unable to metabolize galactoseand the levels will accumulate in the kidney, liver, and brain. It is autosomal recessive.* Duarte variant of galactosemia is asymptomatic, no clinical significance.* Babies will have a variety of symptoms including vomiting, jaundice, hypoglycemia, seizures, cataracts (due togalactitol in lens), enlarged liver or spleen, gain weight poorly, high risk of E. coli sepsis.* Treatment is to eliminate galactose from the diet. One of the few contraindications to breast feeding, should usesoy formula. Although they are treated, babies tend not to do as well, may have developmental delay or speech andlearning problems.--------------------------------------------------------------------------------------------------------------------------------------------Maternal Diabetes* You are called to see a 9.5lb newborn infant who is jittery. Physical exam reveals a large plethoric (red, ruddy)baby who is tremulous. A murmur is heard. Blood sugar is low. This is a baby born to a mother with diabetes or whodeveloped gestational diabetes.* Babies tend to be macrosomic (big baby). Babies tend to develop hypoglycemia because they have highcirculating levels of sugar in-utero so the baby overproduces insulin. Once born, the increased insulin and lack ofmaternal sugar leads to hypoglycemia. Insulin works as a growth hormone, so not only is the baby getting lots ofcalories it is hormonally enhanced in size.* Since they are large for gestational age, they can get birth trauma such as broken clavicle or shoulder dystocia.* Along with hypoglycemia, they can get hypocalcemia and hypomagnesemia. Sometimes they will have respiratorydistress syndrome because insulin can block surfactant production.* Infants of diabetic mothers are at higher risk for hypertrophic cardiomyopathy. In general, they will get better overtime, by about 6 months of age.* Infants can get hyperbilirubinemia and polycythemia. At higher risk for other congenital anomalies like ventricularseptal defects, atrial septal defects, and transposition of the great arteries. At higher risk for lumbosacral agenesisand specifically small or lazy left colon, which can appear like Hirschsprung or meconium ileus.* Treatment is to control mother’s blood sugar while fetus is in-utero. After birth monitor the babies and treathypoglycemia until they adjust their insulin levels.* Complications include diabetes and obesity development as children.
--------------------------------------------------------------------------------------------------------------------------------------------Size For Gestational Age* Most scales to determine if child is appropriate for age include a physical scale and neuromaturation scale.* Ballard scale (Dubowitz is another), looks at muscular maturity, posture, skin, lanugo, plantar creases, breastdevelopment, ear stiffness, genitalia, etc.. Repeat exam 24 hours later, helps compensate for things like depressantmedications taken by mother. Premature babies will have floppy ears because stiff cartilage has not developed.* Small for gestational age does not matter if baby is pre-term, term, or post-term. Only says if the size isappropriate for that particular gestational age.* Shiny skin in a baby implies little subcutaneous tissue, so there was not enough time to develop the tissue.* Labia majora being wide and not covering labia minora is also a sign of prematurity.* As male gets to term, scrotum gets darker, more wrinkles, and testes descend into scrotum.* Lots of lanugo hair implies pre-term.* Flexion a both hips and knees is a good sign. Arm flexion as well. Lusty cry is good.* Most babies start to peel at two-weeks of age. No need to put lotion on it, leave skin alone. A post-term baby mayhave peeling at birth and longer nails.* Term infant weights 4lbs at birth. Physical exam reveals a small infant with a disproportionally large head. Themother has a history of smoking during pregnancy (risk of prematurity, IUGR). This baby is small for gestationalage, intrauterine growth restriction (IUGR). Small for gestational age is below the third percentile for that particulargestational age.* Symmetric means the baby is the same proportions. Asymmetric is when the head is bigger than the body, thesebabies have a better prognosis. It implies that the brain has been spared.* IUGR is associated with any factors that decrease oxygenation to fetus including chromosomes, TORCHinfections, congenital anomalies, irradiation, insulin deficiency. Placental factors include small placenta, infractedplacenta, partial abruption, twin to twin transfusion. Maternal factors include toxemia of pregnancy, hypertension,malnutrition, tobacco use, narcotic use, alcohol use.* Ballard scoring helps to determine gestational age, then weight and plot out baby.* IUGR babies are at higher risk of cold stress (not enough fat) and hypoglycemia (no glycogen stores).* Small for gestational age (SGA) babies at risk for polycythemia because they have more hypoxia and producemore hemoglobin and cells.--------------------------------------------------------------------------------------------------------------------------------------------Neonatal Drug Withdrawal* A two day old infant is noticed to have course jitters and is very irritable, with a high-pitched cry. A low gradefever is reported as well as diarrhea. Maternal history is positive for heroin use.* Moms will say “as soon as I heard I was pregnant I quit doing drugs.” Do not believe them, drug test.* Most common elicit drugs that a baby goes through withdrawal from are narcotics and cocaine.* You can urine drug screen the baby as well.* Heroin has a shorter half-life than methadone so the babies will withdraw sooner. Heroin a couple of days,methadone a couple of weeks.* Hyperactivity, irritability, fever, diarrhea (classic), fussy baby, inconsolable, always sucking, think withdrawal.* Phenobarbital takes a couple of weeks for withdrawal symptoms.* Treatment is put child in long acing narcotics (e.g. methadone) and slowly wean baby. Minimize stimulus,swaddle baby, wrap up baby they like to be held tightly and closely.* Complications of neonatal drug withdrawal is low birth weights, higher risk for anomalies, higher risk for suddeninfant death syndrome, and higher risk for mother’s complications of drug use (e.g. hepatitis, HIV).--------------------------------------------------------------------------------------------------------------------------------------------Respiratory Diseases* Shortly after birth, a 33 week gestation infant develops tachypnea, nasal flaring, grunting, and requires intubation.Chest radiograph shows a hazy ground-glass appearance of the lungs. Suspect respiratory distress syndrome (RDS).This is secondary to surfactant deficiency, seen almost exclusively in preterm babies.* Surfactant decreases surface tension, preventing alveoli from collapsing. So lack of surfactant causes alveoli tocollapse leading to atelectasis. The atelectasis leads to the ground-glass haziness.* Blood gases will be poor due to ventilation-perfusion mismatch caused by the atelectasis.* Valsalva maneuver increases pressure in the chest and helps to keep alveoli open. When child needs to let out theair to breath in, they will grunt.* Usually it takes about three days for child to get better. One of the first signs of improvement is dieresis. No realdiagnostic test for RDS, more of a clinical diagnosis with help from the x-ray. Aside from the poorly demarcated
DO NOT DISTRIBUTE - 10 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Jaundice can come from extravascular blood such as petechiae, hematoma, pulmonary or cerebral hemorrhages,and swallowed blood. Example would be facial bruising during a difficult delivery, like face to pubis presentation.* Jaundice can come from polycythema such as maternal-fetal transfusion, twin-to-twin-transfusion, or placentaltransfusion (cord stripping toward baby).* Mechanical obstructions can cause jaundice, such as atresia, stenosis, Hirschsprung, meconium ileus, meconiumplug syndrome.* Under-secretion jaundice with Gilbert syndrome, Crigler-Najjar syndrome.* Other jaundice causes are TORCH infections, hepatitis, prematurity, infants of diabetic mothers.* In twin-to-twin-transfusion, larger baby has higher risk for jaundice and higher risk for problems.* Phototherapy can cause some diarrhea, but that’s alright cause they’re removing the bilirubin.* Double volumes transfusions help to remove circulating antibodies, remove bilirubin, and increase hemoglobin.* Erythroblastosis fetalis (hydrops fetalis) occurs with hemolysis in-utero, low hemoglobin high output failure,causing anasarca and death.--------------------------------------------------------------------------------------------------------------------------------------------Neonatal Sepsis* A 3week old infant presents with irritability, poor feeding, temperature of 102F, and grunting. Physical examreveals a bulging fontanelle and delayed capillary reflex.* Sepsis is a systemic response to infection. Divided in newborns into early onset and late onset. Early onset iswithin the first 7 days of life. Late onset is 8-28days of life.* Neonatal sepsis risk factors include maternal infection, prematurity, prolonged rupture of membranes.* Most common bacterial cause of neonatal sepsis is group B strep (GBS). E. coli and listeria are distant second andthird. Initial choice of antibiotics covers all three.* Viral causes of neonatal sepsis include herpes simplex and enteroviruses.* Signs and symptoms are non-specific, grunting, fussiness, poor feeding, tachypnea, respiratory distress, apnea.* Newborns do not always have fever. Sometimes they will present with hypothermia or temperature instability.* Neonates with fontanels usually do not present with nuchal rigidity as the pressure can go to the fontanelle,causing it to be fuller/bulging.* Work-up includes CBC, lumbar puncture to rule out meningitis, blood culture, urine culture, skin lesion culture,chest x-ray to rule out pneumonia.* Treatment is antibiotics (ampicillin + 3rd generation cephalosporin), fluid management, attention to details.* Antibiotic choice could also be ampicillin + aminoglycoside. Worry with aminoglycoside about nephrotoxicityand ototoxicity. Follow aminoglycoside levels and do hearing screens later on.* Penicillin or ampicillin given to mother at least 4 hours prior to delivery will reduce the risk of neonatal sepsisfrom group B streptococcus.* Differential includes respiratory diseases, metabolic diseases, intracranial hemorrhage, TORCH infections.--------------------------------------------------------------------------------------------------------------------------------------------Transplacental Infections* TORCH: Toxoplasmosis, Other (syphilis, varicella), Rubella, Cytomegalovirus, Herpes simplex virus.* Majority of TORCH infections occur when mother is in the first or second trimester. * Toxoplasmosis istransmitted by ingesting undercooked or raw infected meat. It is also found in cat feces, infection transmitted fromhandling used kitty litter.* Toxoplasmosis can be mild in the adult, but the problem is when the baby catches it via the mother.* Signs include intracranial calcifications, 40% infection rate if during 1st or 2nd trimester, IUGR, microcephaly,spasticity, seizures, blindness, retinitis, hepatosplenomegaly (HSM).* Diagnosis is via isolation from placenta or cord blood, TORCH IgM titers, IgM ELISA. Toxoplasmosisimmunosorbent agglutination assay can be used.* Treatment of toxo during pregnancy is spiramycin or pyrimethamine + sulfonamide. Postnatal (baby) treatment ispyrimethamine + sulfadiazine + leukovirin for six months. Leukovirin decreased the problems with bone marrowsuppression seen in chronic sulfa drug use. Steroids for chorioretinitis.* Cytomegalovirus (CMV) is the most common congenital, 40% transmission to baby.* Symptoms include SGA, petechiae, HSM, thrombocytopenia, direct hyperbiliribunemia.* Culture urine, blood, CSF, throat, placenta. Look for periventricular calcifications (in brain).* CMV causes chorioretinitis as well. Calcification around periventricular area. “V” in CMV and ventricular.* No treatment for CMV, usually babies do not do well, get mental retardation, microcephaly, liver problems.* Varicella (chickenpox) is divided into neonatal (delivered within a week before or after maternal disease onset)and congenital.
DO NOT DISTRIBUTE - 11 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Neonatal treated with varicella zoster immune globulin (VZIg), if the mother develops the disease 5 days before to2 days after delivery. Give acyclovir as well. This is more serious because the mother has not developed antibodies.* Congenital varicella associated with limb-hypoplasia, scaring, microcephaly, chorioretinitis. Give acyclovir.* Rubella has an 80% transfer rate if mother is infected in first trimester.* Rubella clinically causes mental retardation, microcephaly, heart defects (PDA, pulmonary stenosis), cataracts,HSM, thrombocytopenia, deftness, “blueberry muffin” baby.* Blueberry muffin due to purpuric lesions from thrombocytopenia, add jaundice and it looks like the muffin.* Diagnose via IgM titers for rubella. Prevention is to immunize mother prior to pregnancy. Anyone born after 1957should receive a second MMR vaccination.* Herpes simplex is acquired during passage through the birth canal. C-section not 100% for preventing HSV.* Primary disease is when the mother gets the disease for the first time, so no antibodies, thus lots of transmission tothe baby. With recurrent genital herpes there is low transmission rates.* Delivery can be vaginal if culture is negative and no lesions seen. Do C-section if any lesions or PROM.* Local HSV is present at 5-14 days on skin, eyes, mouth (SEM). Disseminated HSV presents at 5-7 days withpneumonia, shock, hepatitis. CNS HSV presents at 3-4 weeks with lethargy, seizures, instability.* If the CSF tap comes back “clean” but HSV symptoms, the tap is not clean. Think HSV.* SEM (local) HSV has about a 95% chance of normal development. Disseminated is about 60%. CNS is about35%, with only 5% if seizures present. Mortality is high with disseminated especially with pneumonitis.* Treatment of HSV is with acyclovir.* Syphilis is divided into early (first 2 years of life) or late manifestations.* Symptoms of early syphilis are fever, anemia, FTT, maculopapular rash, snuffles (runny nose), HSM.* If you’re suspecting syphilis and baby has glistening snuffles below nose, that’s not boogers, that’s treponems, youbetter put on a glove. That’ll be hard to explain, how you got syphilis from a baby.* Late stage manifestations include periostitis, saber (shaped) shins, Hutchinson (notched) teeth, saddle nose,rhagades (linear scars at angle of mouth), Clutton joints (symmetric joint swelling), Jarisch-Herxheimer reaction(fever and rash with penicillin, systemic reaction to treponems being killed).* Diagnosis with RPR and FTA-ABS. Dark field microscopy can be done too.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal* A newborn is noted to have choking and gagging with its first feed, then develops respiratory distress. Chest x-rayshows an aspiration pneumonia and a feeding tube coiled in the esophagus. This is a tracheoesophageal fistula(TEF). There are various kinds, most common is esophagus into a blind pouch and a fistula into the trachea distally.* TEF associated with prenatal history of polyhydramnios.* Diagnosis is clinical. Treatment is surgical repair.* Look for other abnormalities, such as congenital heart disease such as a PDA, vascular rings, coarctation. Look forvertebral anomalies, anal-rectal anomalies, renal issues. Mainly look at the heart.* Double-bubble sign seen in duodenal atresia. History will be bilious vomiting. Higher association with Downsyndrome.* Hirschsprung disease (also called congenital aganglionic megacolon) should be suspected in any newborn that hasnot passed stool in the first 24-48 hours. Also consider imperforate anus, meconium plug, and meconium ileus. Onbarium enema, the enlarged area is normal. The thing area is where the problem is, stool backs up proximally.* Gold standard (best test) for diagnosis for Hirschsprung disease is colon biopsy looking for aganglionic area.* Necrotizing enterocolitis (NEC) is the most common medical and surgical GI emergency of the newborn. Look fora history of a preterm infant and perinatal asphyxia (low APGAR scores). As baby gets fed, they get bloody stoolsor starts to get distended, lethargic.* Most appropriate test is an abdominal film, looking for pneumatosis intestinalis. Pneumatosis intestinalis is airinside the bowel wall (not just in the bowel lumen). Air inside the bowel wall implies NEC.* Treatment for NEC is bowel rest, antibiotics, and sometimes surgery to remove parts of bowel if it gets necrotic.--------------------------------------------------------------------------------------------------------------------------------------------Neonatal Seizures* In the newborn intensive care unit (NICU), a newborn is noted to have sucking movements, tongue thrusting, andbrief apneic spells. The blood counts and chemistries are normal.* Neonatal seizures do not generally presents with tonic/clonic seizures like they do in older adults.* Causes of neonatal seizures include hypoxic ischemic encephalopathy (most common). Seizures typically presentat 12-24 hours after birth.* Intraventricular hemorrhage usually presents with seizures after 24hours. Think respiratory distress syndrome or
DO NOT DISTRIBUTE - 12 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 13 -Study Notes – Pediatrics James Lamberg 01Apr2010
as mother is losing an additional 500 calories a day by nursing. Uterus regresses to normal size faster (oxytocin).* Part of newborn care is administering vitamin K (1mg IM) to prevent hemorrhagic disease of the newborn.Vitamin K is made in the gut with the help of bacteria, which newborns do no have.* Vitamin K is present is breast milk. Fluoride is recommended after 6 months of age. Fluoride is also recommendedif you are using ready-to-feed formula. If you are mixing formula with water, you have to know what the local watersupply contains (fluoride or not). Vitamin D to baby only if mother does not have adequate vitamin D intake,example would be cultures that are fully clothed and do not get enough sun exposure for vitamin D conversion. Ironfortified foods given at 4-6 months of age.* Few contraindications to breast feeding, such as active TB, syphilis, HIV, varicella, galactosemia, herpes if activelesions on the breast.* Drug affecting breastfeeding include atropine, anticoagulants (heparin safe), antithyroid drugs, antimetabolites,cathartics (except senna), dihydrotachysterol, iodides, narcotics, radioactive preparations, bromides, ergot,tetracyclines, metronidazole, antineoplastics, alkaloids, chloramphenicol, cyclosporin, nicotine, alcohol, steroids,diuretics, oral contraceptives, nalidixic acid, sulfonamides, lithium, reserpine, diphenylhydantoin, barbiturates.* Absolute drug contraindications to breastfeeding include antineoplastics (chemo), alkaloids, chloramphenicol,cyclosporin, nicotine, alcohol, lithium, radiopharmaceuticals (iodine), atropine.* Relative drug contraindications to breastfeeding include seizure medications, neuroleptics, sedatives, tranquilizers,metronidazole, tetracycline, sulfa, steroids.* Mastitis is not a contraindication to nursing. Breastfeeding during mastitis helps mother recover quicker. Mothercan take antibiotic and still nurse.--------------------------------------------------------------------------------------------------------------------------------------------Formula Feeding* Formula feeding is used as a substitute or as a supplement. A majority of formulas are cow’s milk based and areadjusted to be as close to breast milk as possible.* Common formula is 20 calories per ounce.* Human milk is 1.2g/dL protein (7% calories), 4g/dL fat (54% calories), 6.8g/dL carbohydrates (40% calories).* Soy formula is 1.5g/dL protein (9% calories), 3.8g/dL fat (50% calories), 6.9g/dL carbohydrates (41% calories).* Whole milk is 3.3g/dL protein (20% calories), 3.7g/dL fat (50% calories), 4.9g/dL carbohydrates (30% calories).* Whole cow’s milk is good for baby cows or anyone over 1 year of age. Higher risk for allergies, GI blood loss,and anemia if started early. Iron is not absorbed well and they get GI blood loss.* 13mo comes in with a hemoglobin of 6. Mother has been using cow’s milk since 4mo. That’s the cause.* Whole cow’s milk has a high solute load on the kidney. 87mEq/mL in human, 227mEq/mL in cow’s.* Vitamin D is recommended if the formula does not have it, but just get out in the sun and you’ll be fine.* Goat’s milk must be supplemented with folic acid.* If poor iron intake, foods contain iron and are started at 6 weeks.* Solids should be introduced at about 4-6 months of age. Baby can hold its head up, suck-swallow mechanism isbetter, lower risk of allergies. Start a new solid one at a time, one per week to determine if they like it and allergies.* A mother states that her infant is having episodes of inconsolable crying every night for the past 5 nights. Hedraws his legs up and his abdomen becomes rigid. The episodes resolve as quickly as they come on and the rest ofthe day he acts normally. No diagnostic tests for colic.* Usually colic starts about 3 weeks of age and lasts to 3 months of age, no one really understands it, cramping thingthat happens, babies cry then swallow air and get more cramping, pass gas, draw their legs up.* Generally, rhythmic motions help for colic. Patting the baby, bouncing the baby, car rides. Sometimes you can useanti-gas medications like simethicone. Typically occurs at the same time of night.* Differential for colic includes intussusception, hernias, strangulated hair (e.g. mother’s hair around toe).* A 3yo boy is seen for chronic illness. He appears edematous and apathetic with thin hair. Generalized dermatitis isnoted. Sparse hair and decreased muscle tone is noted. This is kwashiorkor, protein-calorie malnutrition.* Vitamin deficiencies are often associated with kwashiorkor. Usually it occurs after they wean from the breastbecause they aren’t getting the nutrition they need, seen in poor societies.* Edema is due to protein loss, thus loss of oncotic pressure in abdomen. Decreased serum albumin, decreased bloodglucose, decreased essential amino acids. Mortality can reach 30-40%.* Treatment of kwashiorkor is slow feeding, replacing quickly can make things worse, plus give vitamins.* Vitamin A deficiency causes night blindness. Thiamin deficiency leads to beri beri. Niacin deficiency leads topellagra.* No honey is recommended in the first year of life due to risk of infantile botulism.* Botulism presents as a descending paralysis (versus Guillain-Barre which is ascending).
DO NOT DISTRIBUTE - 14 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Infantile botulism is due to the spores themselves. In adults, botulism is due to the toxin.--------------------------------------------------------------------------------------------------------------------------------------------Growth, Disorders of Height, & Disorders of Weight* A father is concerned that their 13yo son is short. The child has been very healthy, is below the 5th percentile forheight and has been his whole life. Physical exam is normal. Father is 6’3”, mother is 5’10”. Father was a “latebloomer” meaning growth spurt was later than usual.* Growth is an increase in size, form, and biologic maturation.* Growth chart shows length until they are old enough to stand, then it is height.* 2 standard deviations above 50th percentile is 97th percentile (high normal).* 2 standard deviations below 50th percentile is 3rd percentile (low normal).* A child that is short most of their early years than ends up in the normal range is constitutional growth delay.* Child that is just below the minimal for normal height but is following the curve. Father is 5’6”, mother 5’1”. Thetallest person in the family is 5’7”. This is familial short stature.* A child that is 50th percentile for several years than drops to below 3rd percentile is worrisome. This could be apituitary tumor, craniopharyngioma, Turner syndrome, or other causes of falling off the growth curve.* Pathologic short stature and constitutional short stature both start with child in normal range for height.Constitutional will eventually reach adult height, pathologic will fall off. Past family member history is important.* Physical exam may be helpful if a syndrome is involved. Any female with short stature should be evaluated forTurner syndrome (e.g. karyotype).* Labs could include CBC, urinalysis (chronic renal disease), LFTs, TFTs (hypothyroid), growth hormone.* Wrist films can tell you bone age. If patient is 12yo and short, bone age is 9yo, you know there is room for thepatient to grow still.* If you suspect pituitary tumor, craniopharyngioma, do a skull film looking for an enlarged sella turcica.* Treatment is to correct the underlying disease. Growth hormone will help some patients.* Differential includes hypopituitarism, deprivational dwarfism, Turner, hypothyroidism, chronic disease.* Majority of patients who are tall are normal. Doubtful that any NBA basketball player has Marfan syndrome.* Causes of increased height include obesity, growth hormone excess (gigantism, acromegaly), androgen excess (tallas children, short as adults), hypothyroidism, homocystinuria, cerebral gigantism (Sotos syndrome), Beckwith-Wiedemann syndrome, Weaver-Smith syndrome, Klinefelter syndrome.* Disorders of weight include failure to thrive and obesity.* A baby weighs 16lbs at 1 year of age. His birth weight was 8lbs. Parents state that the baby feeds well. Physicalexam reveals a baby with little subcutaneous fat, long dirty fingernails, impetigo, and a flat occiput.* Failure to thrive (FTT) means you are not gaining weight appropriately or losing your rate of weight gain.* FTT causes include malnutrition, malabsorption (infection, celiac disease, chronic diarrhea), allergies, immunedeficiencies, chronic diseases.* Baby should double their birth weight in about 4-5 months. By 1yo, they should have tripled their birth weight.* Impetigo, flat occiput, and long dirty fingernails implies the baby is not being taken care of. Baby is not beingcleaned or cared for, occiput is flat because baby is just laying their on its back all day long.* Hospitalization may be necessary to document how many calories they are getting, to teach the parents to do itappropriately, to get the family the resources they need to feed the baby.* In children who do not gain weight after these measures, consider a swear chloride test for cystic fibrosis (CF).* Obesity is a generalized over-accumulation of fat, generally due to overeating without exercise. Mother may givethe baby a bottle every time it cries, so it gets use to more calories. Grandma may say “a fat baby is a healthy baby.”* Treatment is diet and exercise.* There are some syndromes associated with being overweight and obese, but they are rare. Exception to the rule.* Risk factors are parental obesity, family inactivity (T.V., video games), feeding in response to any crying, toomuch fruit juice in first year of life, and some syndromes.* Children present not only fat, but possibly with increased height. Boys may have increased fat tissue in themammary region (looks like gynecomastia), abdominal striae, pubic fat pad in boys makes it look like a micropenis.* Body mass index (BMI) curve over 95% or over 30.* Complications include risk of adult obesity (with hypertension, hyperglycemia, stroke, MI), cardiovascularproblems, slipped capital epiphysis, sleep apnea.* Differential includes endocrine and genetic causes, rarely.--------------------------------------------------------------------------------------------------------------------------------------------Fluids & Electrolytes* 7yo is admitted to the hospital for an elective tonsillectomy. The surgeon has asked the pediatrician to keep the
DO NOT DISTRIBUTE - 15 -Study Notes – Pediatrics James Lamberg 01Apr2010
child NPO after midnight. The child weights 22kg. Calculate maintained fluid from caloric expenditures. Replacewhat you would normally lose during the day, urine, sweat, breathing, stool.* Electrolytes are lost in urine, about 2-3mEq/kg/day sodium, 1-2mEq/kg/day potassium.* For first 10kg in children, 100mL/kg. So 5kg child would be 500mL for day. Next 10kg start with 1L then give50mL/kg up to 20kg. > 20kg give 1.5L then 20mL/kg for each kg over 20kg.* 22kg child would be 1500mL + 40mL is 1540mL in 24 hours.* 4-2-1 rule is 4mL/kg for first 10kg, 2mL/kg for next 10kg, and 1mL/kg after that (per hour). Quicker method forthat is take weight and add 40. So 22kg child would be 62kg/hr or about 1488mL/day.* Deficit can be calculated by physical exam or recent weight. So normal 10kg child now has diarrhea and is at 9kg.You know the kid isn’t trying to lose weight, so fluid loss is 1L of fluid.* Dehydrations are isonatremic (isotonic), hypernatremic (hypertonic), and hyponatremic (hypotonic).* Amount of fluid deficit is mild (5% infant, 3% adolescent), moderate (10% infant, 6% adolescent), or severe (15%infant, 9% adolescent). Older children have less proportion of body water.* Mild dehydration would be thirsty and alert patient, no tachycardia, normal perfusion.* Moderate dehydration would be weak pulse, tachycardia, normal perfusion.* Severe dehydration would be very weak pulse, tachycardia, decreased perfusion, mottled skin.* Skin turgor and fontanelle can be used to determine degree of dehydration (tented skin, sunken fontanelle).* Always treat shock. If hypotensive, give 20mL/kg of normal saline or Lactated Ringers.* Isonatremic and hyponatremic dehydration, replace fluid deficit in 24 hours. Give half deficit in first 8 hours andrest of deficit in next 16 hours.* Hypernatrmic dehydration, do not decrease sodium too quickly else cerebral edema, replace total deficit over 48hours. Remember to include maintenance as well and ongoing fluid loses (e.g. diarrhea, urine in DKA).* Best place to check for skin turgor is over the sternum.* Doughy feel with skin tenting seen in hypernatremic dehydration.--------------------------------------------------------------------------------------------------------------------------------------------Development & Behavior* Development is acquisition of functions.* Baby can sit up with its back straight, has started crawling, has a pincer grasp, and plays peek-a-boo. What age ismost appropriate for this baby?* Development classified into neurodevelopmental, cognitive, and psychosocial.* Denver Developmental Screening Test (DDST) is a developmental screening tests. Focus on a couple things thatdifferentiate one age group from another. There is a spectrum of normal for each milestone.* Moro reflex is when the child is stimulated by gently dropping the bassinette or the baby a few inches, baby willbring arms flexed in, draw legs up, and toes fan out like a Babinski. Present at birth, disappears at 4-6 months of age.* Grasp reflex is plantar or palmar, stimulation of hand will cause grasp. Present at birth and disappears at 4-6months of age.* Rooting reflex is stimulation of cheek and baby will turn head and open mouth, attempting to nurse.* Trunk incurvation (Galant reflex), baby held in ventral suspension and finger ran along one side, baby will movehip/butt to that side. Baby may pee a little too. Present at birth, goes away at 6-9 months of age.* Placing or stepping reflex is baby suspended and dorsum of foot touches examining table, baby will draw leg uplike taking a step. Goes away at 4-6 months of age.* Tonic neck reflex (fencer’s pose) is with baby on back, head turned to side, facing hand will be straight out andopposite arm flexed. If you turn the head to the other side, baby should reverse pose. Goes away at 4-6 months.* Parachute reflex is not present at birth. This reflex is when baby is sitting up, you tip them over, they will movetheir hand out in anticipation for falling. If you grab the baby and dive them a little head down, they will spread botharms out to prevent face-first falling. Present at 6-8 months of age and should not go away.* Babinski is normal until about 18 months. This is big toe up, other toes fanned out. UMN lesion after 18 months.* Prone positioning with ventral suspension is when you hold the child face down with one hand on their chest andbelly. One week old will look floppy because no good musculature. 1-2 month old will have better muscle tone.* Up to 2 months of age, head will lag if you pull baby up to sitting. This goes away at 2-4 months of age.* Newborn in prone will barely be able to get face over to side. At 1 month of age, baby will be able to clear examtable without nose rubbing. At 4 months of age, arms underneath with chest and head up.* Good pincer grasp seen at 9-10 months of age. Mnemonic is pointer finger makes a 1, pointer-thumb makes a 0.* Newborn will turn it’s head with nose touching in prone, flexed in ventral extension. Visually will prefer a faceand has doll’s eye movements.* 1 month of age will clear exam surface prone, lift head to plane of body, will follow moving object.
DO NOT DISTRIBUTE - 16 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Social smile at 2 months (4-8 weeks of age), lift head in prone position, keep head in plane of body for a littlewhile, still tonic neck, still head lag, “coos”.* 3 months of age can lift head and chest off exam table prone, still tonic neck, social smile still.* 4-5 months will roll over from stomach to back. 5-6 months roll over from back to stomach.* 6 months can start creeping or crawling, sitting with pelvic support and back rounded leaning forward on hands,raking at a pellet, babbles.* 9 months of age will sit by self, creep, crawl, walk with hands held, pincer grasp, plays peek-a-boo.* 12 months of age will cruise (walk holding onto things), may walk a little, will adjust position to help dressing.* 15 months of age will walk by self.* 18 months of age will say no, body parts, 10-20 words.* 24 months of age will put sentences together.* 30 months of age can walk up stairs but alternating feet.* 36 months can go down stairs with alternating feet, know age “free years old”, can tell you if they are boy or girl.* 48 months can copy a cross or square (4 years, 4 sides, 4 objects).--------------------------------------------------------------------------------------------------------------------------------------------Attention Deficit Hyperactivity Disorder (ADHD)* 6yo boy is doing poorly in school. Teachers report he is distractible, impulsive, and fidgety. Parents state he isalways on the go at home and has been a discipline problem.* Hyperactivity portion is not always there, more commonly seen in boys.* Characterized by inability to attend to the task at hand, increased motor activity, and impulsivity.* Etiology unknown. We do know they have problems filtering stimuli, e.g. flickering light bulb or bird chirpingoutside the classroom would be too distracting to accomplish a task.* ADHD kids have problems controlling their own behaviors to social accepted norms.* More commonly diagnosed in males overall, but inattentive-type more common in females. Probably 1:1.* DSM-IV criteria are inattentiveness (mistakes, difficulty paying attention, doesn’t seem to listen, doesn’t followthrough on tasks, difficulty getting organized, avoids sustained mental effort, loses things easily, distractible andforgetful), hyperactivity (fidgety, out of seat, don’t play quietly), and impulsivity (say or do things without thinkingabout the consequences). Criteria should be noted at home and at school.* There is no test for this. There is the Connors questionnaire and others, but no diagnostic tests.* Treatment is pharmacologic and psychosocial management (treat family situation).* If associated learning disability, that should be managed as well.* Medications include methylphenidate, dextroamphetamine, pemoline, tricyclic antidepressants.* Diet has nothing to do with ADHD (e.g. chocolate, red dye #40, sugar).* Children will learn to control some of the distractibility and impulsivity.--------------------------------------------------------------------------------------------------------------------------------------------Enuresis & Encopresis* 7yo boy has problems with bedwetting. Mother says during the day he has no problems but is usually wet 6 of 7mornings. He does not report dysuria or frequency, and does not have increased thirst. Mother says he is a deepsleeper. This is nocturnal enuresis, a disorder of arousal and sleeping.* Enuresis is defined as involuntary passage of urine after a normal age for toilet training (by age 3-5).* Every year there are fewer and fewer children with enuresis as children get older, so reassure parents.* Enuresis does run in the family.* Primary enuresis is a child that has never been dry for a significant portion of time. Secondary enuresis is the childthat has been dry and now is having accidents; ask about home or school issues (e.g. new sibling, parents gettingdivorce, bully at school, grandpa died).* Nocturnal enuresis is associated with development delay of the bladder.* Worry about urinary tract infections and diabetes, which could be causing enuresis.* Treat with reassurance, bed bell system (child changes sheets after wetting), and possibly medications.Recommend child does not drink fluids for 2 hours prior to going to bed.* Encopresis is fecal incontinence is more common in males and usually psychological, such as not wanting to go tothe bathroom at school and getting impacted then leakage around impaction.* Encopresis is triggered by voluntary holding then leakage around impaction.* Treatment of encopresis involves counseling and possibly cleaning out the patient’s bowels.--------------------------------------------------------------------------------------------------------------------------------------------Developmental Disorders* 4yo child speaks in unintelligible mumbles, prefers to play by himself, and rocks back and forth constantly.
DO NOT DISTRIBUTE - 17 -Study Notes – Pediatrics James Lamberg 01Apr2010
Parents state that as an infant he had a delayed social smile and was not very playful or interactive.* Autism is a developmental disorder, usually a problem with social relations. Also have verbal and non-verbalcommunication deficits, unusual responses to the environment.* Autism is usually picked up prior to 30 months of age.* Clinical features include failure to attach as an infant, delayed or absent social smile, failure to anticipateinteraction (will not reach out arms if you go to pick them up), tend to have repetitive movements, may have a needfor constancy, may have verbal or non-verbal communication delay, outbursts of anger, may hurt self or others.* No cure for autism, treatment consists of small educational groups and sometimes pharmacotherapy.* Prognosis for autism is very poor.* Asperger is a subset of autism, more communicative, appear more aware, do not have the language impairmentsthat are seen in autism. However, they do have social impairments, do have repetitive behaviors, and have obsessioninterests and constancy.* Rett syndrome only seen in females, X-linked dominant (MECP2 gene), normal until 1yo then losing milestonesor delay. Head stops growing. Will have hand-wringing movements and sighing sounds.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Poisoning with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Overview* Poisoning is the 4th most common cause of injury in children. Occurs most often under 5yo (when child can beginto walk) and in teenage years (intentional or non-accidental).* Any poisoning over age 5 is most likely non-accidental, things like suicide, child abuse, intentional injury.* Majority of poisonings occur in the home, most likely in the home and bathroom.* Anticipatory guidance is involved here, seatbelts, car seats (started at birth), poisons on higher shelves.* Poisonings occur when normal routine is disrupted, such as family vacation, visiting grandma (house not “childproofed”), after a home move.* Child safety caps are good for prevention of poisoning, but can give you a false sense of security. Just because ithas a child safety cap does not mean the child cannot get into it. The child is like a little burglar, if you give themenough time they can get into things. Idea is to slow them down so they get tired and do something else, or so youcatch them in the act.* All poisons should be properly labeled. If you mix a name-brand cleaner into a squirt bottle and the child drinks it,you may not know what is in the bottle if it is not labeled.* Keep poisons and medications in a high up and locked cabinet.* Do not take medications in front of children. This sends the message that if mom and dad do this then the childshould too. Example would be little girl presents with gynecomastia and says she wants to be like mommy. Thischild took mom’s menopause hormones (estrogen).* Dispose of medications properly, do not flush medications unless a medication insert specifically says to do so. Ifno instructions are given, remove medications from bottle and mix with undesirable trash (e.g. used coffee groundsor kitty litter). This helps keep animals (family pet) and children out. Place in a leak-proof bag to prevent leakage.* Always have the poison control number at home and in something that will be carried with the baby, such as adiaper bag. National U.S. number is 1-800-222-1222.* Many pharmacies no longer carry syrup of ipecac (emetic) and there is controversy about home activated charcoal.Best management is call poison control and go to ED.* If inhaled poison, remove child from source. If absorbed through skin, remove clothing and wash child off.* If poison swallowed, go to hospital. If poison in eye, flush eye with water for 15 minutes.* In ED, management is ABCs, quick history (e.g. how many pills, how long ago), fast focused exam.* Poisoning should be added to the differential anytime there is a bizarre constellation of symptoms.* Prevention of absorption can be done by causing emesis (rarely used), gastric lavage (best in first hours afteringestion), activated charcoal, cathartics (polyethylene glycol or other medications to speed GI transit), diuresis mayhelp with certain ingestions.* Emesis and gastric lavage are not indicated for corrosives as they will make things worse.* Do not do induce emesis or do gastric lavage if patient has reduced gag reflex or is comatose.* Activated charcoal has few contraindications, but do not give if you just gave an emetic as activated charcoal mayabsorb the emetic leading to poor emesis. Again, emetics rarely used.* Activated charcoal not helpful for cyanides, metals, sodium, potassium, chloride, acids, bases.* Cathartics decrease GI absorption. Magnesium cathartics should not be used if the patient is in renal failure.* Diuresis and dialysis are options as well. These are usually last ditch measures.
DO NOT DISTRIBUTE - 18 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Poisoning treatment of choice is supportive. There are few antidotes, so manage ABCs.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Acetaminophen* 3yo was playing doctor with his 4yo sister. The sister told him that he was very ill and prescribed 25acetaminophen tablet, which the child ingested. Another case would be a 16yo who takes a bottle of acetaminophentablets after an argument with her parents or breaking up with her boyfriend. Hepatotoxicity is worse in adults.Either way, we need to manage these patients.* Acetaminophen is used for analgesia and as an anti-pyretic. Metabolism is mainly via liver.* Toxic dose in children under 12yo is 150mg/kg. It is also important to know if the pill is extended release.* Stage I acetaminophen toxicity is first 24h after ingestion. Patients have nausea, vomiting, diaphoresis. This is agood time to get liver function tests because they will be normal.* Tests to get are liver enzymes (transaminases), coagulation studies, bilirubin, and albumin.* If patient is a girl in childbearing years (12 to 52), get a pregnancy test.* Stage II acetaminophen toxicity is 24-72h after ingestion and patient is starting to look better. However, if thepatient is going to have liver problems, this is when you’ll see changes in LFTs and coagulation studies.* Stage III acetaminophen toxicity is 72-94h after ingestion and patient will have a peak in LFTs. This is when youknow if the liver will recover or get much worse.* Stage IV acetaminophen toxicity is when the liver is recovering.* Majority of children will not have liver problems. However, acetaminophen toxicity is the number one cause ofliver transplant in the U.S.* Management also include ordering an acetaminophen level. Acetaminophen tends to peak at 4 hours.* Antidote for acetaminophen is N-acetylcysteine (NAC). Rumack nomogram will help you determine if we shouldgive NAC. If level is above the top line (probably hepatotoxicity area), give NAC. If level is between the twonomogram lines, this is possible hepatotoxicity, give NAC.* Why not give to everybody? There is a loading dose then a dose every 4 hours for 16x (17 total doses). Generallythe patient will not drink it because it tastes lousy and smells like rotten eggs so is given via NG tube.* Once you start giving NAC, it does not matter what the acetaminophen level is. The level will drop and will notchange management, keep giving NAC regardless of any subsequent acetaminophen level.* Activated charcoal is given not only for acetaminophen here but in case the patient took other poisons along withthe medication (e.g. anti-depressant medications).* If acetaminophen level greater than 150, treat patient with NAC. NAC best given within 8 hours of ingestion.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Alcohol* A high school senior arrives in the Emergency Department (ED) immobilized on a backboard with cervical spinecollar in place after a motor vehicle accident. The patient was a restrained passenger in the backseat passenger-side.He states that he and the 5 other teens in the car had just left the party when their car was struck. The smell ofalcohol is present on physical exam, the patient has no history of diabetes, and no broken liquor bottles were foundin the car or trunk at the scene of the accident.* One drink is 12oz can beer, 9oz glass wine, 1.5oz liquor shot.* Alcohol use is seen often in adolescence. Negatively affects the parachute reflex. Joking aside, it not only can leadto negative outcomes for the teen but for others (e.g. car accident) and their families.* Factors affecting intoxication include amount of alcohol ingested, patient size, if food was ingested, and tolerance.* Most states cutoff intoxication for driving at BAC 0.08. This is legally drunk regardless of effect due to tolerance.* From 50-150mg/dL there are affects, incoordination, blurred vision, slowed reaction time. BAC 150-300 givesvisual impairment, staggering, and slurred speech. BAC 300-500 produces stupor, hypoglycemia, coma. BAC over500 is fatal if patient has no tolerance.* Any comatose patient should get an alcohol level drawn as well as blood glucose.* No specific antidote, only supportive treatment. Treat metabolic acidosis and hypoglycemia.* Michaelis–Menten kinetics for alcohol is zero order. Zero-order drugs are PEA: phenytoin, ethanol, aspirin.* Zero order kinetics means alcohol will be constantly metabolized at the same rate regardless of other factors.* Activated charcoal can be used in case they got into anything else, but not too helpful for the alcohol.* If high blood alcohol levels and nothing is helping, then consider dialysis.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Amphetamines* The guidance counselor refers a 10th grade student to the school nurse for weight loss, insomnia, and depression.* Amphetamines are stimulants so why is he depressed? Because he’s coming down off of them.
DO NOT DISTRIBUTE - 19 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Patients will have either acute or chronic toxicity. Acute toxicity includes diarrhea, palpitations, arrhythmias,syncope, hyperpyrexia, hyperreflexia, seizures, coma.* Chronic toxicity due to tolerance includes restlessness, nervousness, depression, insomnia, suicidal behavior,weight loss. Diagnosis is via urine drug screen (UDS) will show amphetamines for up to 1-3 days andmethamphetamines for up to 3-5 days.* For acute intoxication, supportive therapy with ABCs, cooling blanket for hyperthermia, sedation if needed.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Salicylates* A teenage girl is brought by ambulance to the ED because her mother found her ingesting a bottle of aspirin. Thepatient states that she “wants to die” as her boyfriend has decided to date someone else.* Aspirin is used as an analgesic, anti-inflammatory, and antipyretic. Other medications with salicylate in theminclude bismuth subsalicylate (Pepto-Bismol) and methyl salicylate (Oil of Wintergreen).* Salicylates are the most common cause of drug poisoning in the United States.* 80yo woman presents with increasing back pain. Has been taking her pain medication more and more often overthe past week. Daughter asks about her mom’s ringing in the ear. The patient interrupts to say “It’s just cause I’mgetting old.” Think salicylate poisoning, not just in pediatrics.* Salicylates uncouple oxidative phosphorylation, increase metabolic rate, cause tachypnea, tachycardia, fever, andhypoglycemia. You try to put these symptoms together thinking, “Well what infection can cause this?”* By inhibiting the Kreb cycle, you get metabolic acidosis, liver damage, coagulation problems (platelets).* Presentation includes vomiting, hyperpnea, fever, lethargy, mental confusion all seen in mild. Seizures, coma,respiratory collapse seen in severe ingestions. Hyperventilation, dehydration, bleeding disorders, seizures, comaseen in chronic ingestion. Tinnitus is a common symptom associated with salicylate level over 30mg/dL.* Stage I salicylate toxicity last about 12h and involves respiratory alkalosis, losing potassium and bicarb in urine.This stage is 12h in adolescent but may not be seen in a small child. It can mimic diabetic ketoacidosis.* Stage II salicylate toxicity includes paradoxical aciduria, 12-24h after ingestion in adolescent. May be sooner inthe younger child.* Stage III salicylate toxicity includes metabolic acidosis, dehydration, hypokalemia. This stage occurs earlier ininfant, later in adolescent (> 24h).* White count, hematocrit, and platelets may be increased. BUN and creatinine may be increased* Labs can be all over the place, hypernatremia, hypokalemia or hyperkalemia, hyperglycemia or hypoglycemia,ABG showing metabolic acidosis with respiratory compensation in children. In adolescents, ABG will showrespiratory alkalosis alone.* Done nomogram is for salicylate overdose. Using the Done nomogram, you can determine how bad the ingestioncan be, even though there is no antidote.* Ferric chloride test is done by putting a drop of urine on a ferric chloride tablet. If tablet changes color, you knowthere is aspirin in the system. It does not say how much (quantitative), just qualitative. Obtain blood aspirin level.* Treatment is supportive care. Gastric decontamination if soon enough. May attempt to change urine pH by givingbicarbonate IV, which would speed excretion of aspirin. Severe cases may need hemodialysis.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Carbon Monoxide* 5yo is brought to the ED for a first time seizure. The child was previously well. The father states the child wastraveling across country in an older model vehicle when the seizure occurred. The child was sleeping on the car ofthe vehicle and there were 5 adults smoking tobacco at the time of the event. On physical examination, the childappears drowsy. Pulse oximetry reads 97%.* Carbon monoxide is colorless and odorless. Can come from a bad car, not necessarily a car running in a garage,many times because the CO is seeping into the car.* CO will bind hemoglobin a 250x better than oxygen does. Oxygen is thus displaced giving carboxyhemoglobin.* CO (carboxyhemoglobin) level of 0-10% has no symptoms. Smokers tend to have 3-5% as baseline.* CO level of 12-20% gives headaches, 21-30% gives worse headaches and irritability, 31-40% gives severeheadache, lethargy, nausea, vomiting, 41-50% gives confusion, syncope, tachycardia, tachypnea, 51-60% can causecoma and seizures, 61-70% gives hypertension and respiratory failure, > 70% is fatal.* Cherry red blood on ABG may be seen, cherry red skin is very rarely seen.* PO2 will be lousy even with red blood.* Acidosis will be seen on ABG.* Treatment is to remove patient from the source (replace car, fix house), put on 100% oxygen, severe cases gethyperbaric oxygen. Half life from 240mins to 47mins with 100% oxygen, down to 22mins with hyperbaric.
DO NOT DISTRIBUTE - 20 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Sequelae include behavior changes, memory loss, blindness, and can all occur with one exposure.* Cyanide intoxication, seen in house fires, is treated with amyl nitrate, then sodium nitrite and sodium thiosulfate.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Caustics (Acids & Alkali)* 2yo presents to the ED with his parents who say they found the patient drinking some lye. The patient is cryingprofusely with blisters and burns noted on inspection of the mouth. The patient is drooling.* Acids cause tissue necrosis. Alkalis cause liquefaction necrosis. Burns worse at extreme of pH (< 2, > 12).* Manage airway immediately due to airway burns and edema.* Esophageal strictures can occur. Pylorus strictures can lead to vomiting or delayed gastric emptying.* Endoscopy can be done to determine extent of burns.* Treatment is to remove caustic by removing from skin and flushing mouth.* Do not induce vomiting in these patients as it will burn. Do not do gastric lavage because you can perforate theesophagus as the NG or OG tube travels down.* No need for antibiotics. Role of steroids is questionable.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Cocaine* 15yo is brought to the ED with dilated pupils, tachycardia, and chest pain. A classmate reports that she thinks shesaw the patient snorting in the locker room.* Cocaine can be taken various ways, snorted, smoked, injected. Cocaine is a potent vasoconstrictor.* Cocaine has a short half-life. It gives a feeling of euphoria, CNS stimulation, restlessness, excitement, agitation.* Later symptoms include hypotension, seizures, coma, respiratory depression.* Chest pain can occur as well as myocardial injury.* Snorting the powerful vasoconstrictor can lead to perforated nasal septum due to ischemia.* Urine drug screen (UDS) to test for cocaine, in urine for up to 2-5 days.* May see packets on an abdominal film if patient is a drug smuggler.* Death can occur if a packet bursts and patient absorbs large amount of cocaine.* Treatment is supportive, no antidote. Since half-life is short, they will do alright after initial hump.* Hypertension can be profound due to vasoconstriction. Chronic users can develop cardiomyopathy.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Hydrocarbons* 2yo is brought to the pediatric ED because the patient ingested gasoline. The gasoline has been placed in a sodabottle to be used for the lawnmower. The patient does not appear to be in respiratory distress but wheezing is presentat the right base.* Main problem in not ingestion because it tastes lousy so they will not drink much. The problem is in aspiration.* Hydrocarbons found in fuels, solvents, cleaners.* Patient may have cough, emesis, fever. Symptoms may be delayed for 6 hours. So, if kid comes in right afteringestion do not listen to the lungs and send them home. Monitor for 6-8 hours.* Physical exam can show shortness of breath, wheezing, rales, dullness to percussion.* Aspiration pneumonitis on x-ray.* Treatment is supportive. Gastric lavage is contraindicated. Antibiotics are not indicated.* Complications are not common, but can have respiratory problems.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Organophosphates* A young boy who is visiting his grandfather’s farm is brought to the ED by his grandparents. The grandfather saysthe child had been playing in a newly fertilized field when he developed drooling, tearing, and emesis. At present,the patient is areflexive and has defecated and urinated in his trousers. The patient appears lethargic.* Organophosphates found in insecticides. They are acetylcholinesterase inhibitors.* Organophosphates lead to a hypersecretory state. Mnemonic is SLUDGE or DUMBELS: diarrhea, urination,miosis, bradycardia, emesis and edema, lacrimation, salivation.* Triad is bradycardia, miosis, and fasciculations.* Diagnostic tests include history and physical, RBC cholinesterase activity will be decreased (takes a while).* Treatment is ABCs, remove clothes if skin exposure, wash patient to prevent more absorption.* Treatment includes atropine and pralidoxime (2-PAM Cl).* Some organophosphates are carbonate esters and pralidoxime will not work as well for these.* Give atropine, sometimes a continuous infusion, until reversal of symptoms (until tachycardia, mydriasis,decreased secretions) then wean atropine.
DO NOT DISTRIBUTE - 21 -Study Notes – Pediatrics James Lamberg 01Apr2010
--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Iron* Iron poisoning is the most common cause of death from poisoning in childhood.* Severity of iron poisoning depends on the amount of elemental iron, not just mg of “iron” in the preparation.* Stage I iron intoxication occurs about 30min-6h after ingestion, symptoms are nausea, vomiting, diarrhea,abdominal pain. Mimics hemorrhagic gastroenteritis.* Stage II iron intoxication occurs 6-12h after ingestion and patient will clinically improve.* Stage III iron intoxication occurs 24-48h after ingestion, indicated more severe poisoning, progressive circulatorycollapse (shock), hepatorenal failure, bleeding, metabolic acidosis, coma.* Stage IV iron intoxication 1-2mo after ingestion, signs of GI scaring/obstruction, vomiting like pyloric stenosis.* Children’s vitamins with iron do not have enough iron to cause intoxication. Iron intoxication occurs when childgets into grandma’s vitamins or mom’s iron supplements or other adult preparations.* Serum iron level can be obtained. Levels > 500 is considered severe poisoning.* Sometimes can see iron tables on an abdominal film (radio-opaque tablets). If liquid, then won’t see on x-ray.* Treatment if no gastroenteritis is emesis (if early), whole bowel irrigation to flush tablets, endoscope to removetablets if they are still there.* Antidote is deferoxamine for symptomatic patients, hypotension, lethargy. Treatment is supportive.* If asymptomatic, wait for serum iron and TIBC. If serum iron > 350, can use deferoxamine.* Deferoxamine causes urine to change color, looks like wine.* Complications include GI scaring and obstruction.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Lead* 24mo has a lead level of 19 on a routine screening for a well-child check. The patient is asymptomatic but lives ina historic home being renovated by the parents.* Lead poisoning is a chronic disorder often seen in children near environmental exposure risks such as old housesbeing restored or old houses with paint chips. New houses do not have lead in the paint.* Other sources of lead include pottery, plates, fishing weights, aerosolized from stripping pain in old homes, leadpipes, lead-glazed pottery with folk remedies.* A good source of dietary iron is using iron-based skillets (joke). Lead-glazed pottery will put lead in food.* A majority of patients are found on routine screening and many will be asymptomatic.* Anorexia, apathy, lethargy, anemia, decreased play activity, aggressiveness, poor coordination, poor schoolperformance, are symptoms of lead intoxication. Encephalopathy or coma with acute active ingestion.* Chronic lead exposure can cause apathy, clumsiness, nausea, vomiting.* Diagnosis is via blood-lead level, gold standards. Best test is not free erythrocyte protoporphyrin.* Levels greater than 10 are considered abnormal.* CBC may reveal anemia, basophilic stippling. X-ray will show lead lines at joints (metacarpals, knee).* Treatment is to remove child from the environment.* Lead > 15-19 then screen q4mo, > 20 then confirm with venous blood, >45 begin medication treatments, >55-69treatment is EDTA or succimer (oral chelating agent), > 70 is EDTA and dimercaprol (BAL, British Anti-Lewisite).* Dimercaprol is mixed with peanut oil (BAL in oil) so ask about peanut allergy.* Usually seen in children < 3yo, encephalopathy can occur after 3-6 weeks of active lead ingestion.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Antihistamines* 2yo took his brother’s allergy medication and is brought to the hospital by ambulance because of tremors andhyperactivity. The medics report the child had a seizure before arriving at the hospital. On physical exam, the childhas fever, flushed skin, tachycardia, and fixed-dilated pupils.* Antihistamines can depress or stimulate the CNS. Some preparations contain alcohol. Some contain decongestantslike pseudoephedrine which will stimulate the CNS.* Presentation varies from drowsiness, to insomnia and nervousness. Can be hyperactive and experiencehallucinations. Can present with seizures. Anticholinergic effects (fever, tachycardia, flushed skin, mydriasis).* There is no diagnostic test and no antidote. Requires high index of suspicion and supportive care.* Activated charcoal can be given. If long-acting antihistamine, then can try cathartics or whole bowel irrigation.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Barbiturates* 3yo arrives with his parents after ingesting his brother’s seizure medication, phenobarbital. The patient hasconstricted pupils and appears to be in a coma.
DO NOT DISTRIBUTE - 22 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Barbiturates used for anticonvulsants. The increase the duration of GABA channel opening, depresses CNS.* Mild to moderate toxicity will mimic alcohol intoxication, slurred speech, clumsiness.* Severe acute intoxication will cause changes in level of consciousness and will cause respirator depression.* Look for constricted pupils, confusion, hypotension, poor coordination, respiratory depression, coma.* Treatment is ABCs, intubation if respiratory depression, manage hypotension, supportive care.* Gastric lavage and activated charcoal are options. Forced diuresis and alkalinization of urine can help with long-acting barbiturates, such as phenobarbital.* Complications include death from respiratory depression.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Tricyclic Antidepressants (TCA)* 3yo presents to the ED after taking her brother’s bedwetting medicine. She is noted to be drowsy. ECG showswidened QRS and prolonged QT and QTc.* TCAs produce sedation, alpha-blocking effects, anticholinergics.* Most important thing to worry about is the ECG. Monitor the patient.* Most common causes of death in TCA overdose patients is cardiac arrhythmias and seizures.* Symptoms include drowsiness, delirium, hallucinations, disorientations, seizures, coma. Initially hypertension andlater on hypotension.* Treatment is supportive therapy. Activated charcoal can be used. Sodium bicarbonate can be used to alkalinize andto prevent dysrhythmias. Arrhythmias can be managed with lidocaine. Seizures treated with anticonvulsants.--------------------------------------------------------------------------------------------------------------------------------------------Poisoning: Treatments* Acetaminophen treated with N-acetylcysteine (NAC).* Anticholinergics treated with physostigmine.* Anticholinesterase treated with atropine and pralidoxime.* Carbon monoxide treated with oxygen.* Cyanide treated with amyl nitrate then sodium nitrite and sodium thiosulfate.* Digoxin treatment is avoid hyperkalemia and digoxin-fab fragments (Digibind).* Ethylene glycol treatment is ethanol.* Opioids treated with naloxone.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Trauma & Orthopedics with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Head Trauma* 5yo fell approximately 6ft from a tree and is brought to the ED because of loss of consciousness at the scene for 1minute. Patient is awake and alert on arrival, Glascow Coma Scale is 15. There is an obvious deformity of the rightforearm, various bruises, and otherwise unremarkable exam. Next test should be CT scan of head.* Head trauma is a common cause of childhood hospitalization and even larger number of ED visits.* Serious head trauma is usually secondary to motor vehicle accidents, sports, recreation, violence (in that order).* Infants need to be in a car seat on their first ride home from the hospital. Infants face rear, safest place is back seatin the middle. At 1yr and 20lbs, car seat can face forward. Safest place is still back seat in middle. At age 4 or 40lbs,can get booster seat. By age 7, can use regular seatbelt. Adults should always wear seatbelts. No child under the ageof 13 should be in the front seat if passenger side airbag. Short adults shouldn’t be in the front seat either ifpassenger side airbag.* Anyone riding a bicycle should be wearing a bike helmet, children and adults. About 200 deaths per year under theage of 16 of children from riding bicycles.* 55,000 injuries per year from trampolines (2000), anything from twisting ankle to breaking neck.* Presentation of head injury depends on trauma, may be with or without deficit. Children with neurologic deficitsmay have a history of a lucid interval, suspect epidural hemorrhage.* Epidural needs craniotomy and evacuation, subdural probably does too.* Epidural hematoma is lenticular or lens shaped on head CT. Subdural hematoma is crescent shaped on head CT.* Battle sign bruising behind the ear, Raccoon eyes bruising around the eyes, and hemotympanum blood behind eardrum associated with basilar skull fracture. Do not place nasal tubes (NG, nasal airway) in this case.* Otorrhea or rhinorrhea after head injury, think CSF leakage and basilar skull fracture.* Ring test for CSF, put drop of fluid on filter paper and blood will stay in the middle with a yellowish ring aroundthe blood, implies this is CSF.* Concussion is the most common head injury seen in children. Usually brief loss of consciousness then returning to
DO NOT DISTRIBUTE - 23 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 24 -Study Notes – Pediatrics James Lamberg 01Apr2010
--------------------------------------------------------------------------------------------------------------------------------------------Thermal Injuries* 2yo comes to ED after being splashed by hot coffee after it was pulled from the table when he pulled the tablecloth. He has first and second degree burns.* Burns can occur from spillage, fire, chemical, electrical. Electrical burns can be deceptive in their destruction.* Burns are the second leading cause of death in children.* Scald burns are 85% seen in children < 4yo, typically story is child pulling something off the table or stove. Alsocan be seen in abuse, when child is dipped into very hot bath water.* First degree burn is erythema (e.g. sunburn), second degree burn has blister, third degree is full thickness. Fourthdegree is down to bone with carbonification.* Rule of 9s is different in children, more surface on head in infant. Rule of the palm used for < 10% where child’spalm is about 1% of burn surface area.* Parkland fluid resuscitation formula is 4mL/kg * BSI burned.* Do not include first degree burns for Parkland formula. Just include second and third degree burns.* Remember deficit (Parkland) is at time of burn, if child arrives 2 hours later you are 2 hours behind.* Give half of fluid deficit over first 8 hours then next half over 16 hours (24 hours total).* Do not forget analgesia. Burns hurt immensely. Also assess tetanus status.--------------------------------------------------------------------------------------------------------------------------------------------Orthopedics: Limping* Most common cause of limping in a child is acute trauma.* Age 0-4yo limping, think about developmental dysplasia of the hip.* Age 4-8yo limping, think about Legg-Calve-Perthes disease.* Adolescent limping, think about slipped capital femoral epiphysis.* 5yo boy has developed progressive limping. At first it’s painless, it now hurts to run and walk. The pain is in theanterior thigh and is relieved by rest. Parents recall no trauma. This is Legg-Calve-Perthes disease, ages 4 to about12yo. It is an avascular necrosis, hip femoral head vascular supply interrupted.* Legg-Calve-Perthes disease can occur after trauma, but cause unknown.* Transient synovitis or venous congestion can also cause Legg-Calve-Perthes disease.* Hyperviscosity and coagulation abnormalities have been implicated.* More commonly seen in boys, 20% bilateral. Usually painless limping initially, but can progress with pain worsewith activity and relieved by rest.* Pain may be referred to the groin, hip, thigh, or knee. If patient has knee pain, think about the hip as well.* First step in management is an x-ray of the hip, both sides. You’ll see destruction at the femoral head.* Follow-up films are also helpful, will show the femoral head coming back to normal (takes a couple of years).* Goal is to maintain joint mobility. Keep hip in the acetabulum, via bracing and maintain child activity.* Complications of Legg-Calve-Perthes disease includes osteoarthritis.* DDX for Legg-Calve-Perthes disease includes trauma.* Developmental dysplasia of the hip x-ray will show a wider hip (femoral head to acetabulum) on one side.* 20% family history with developmental dysplasia of the hip. Associated with breech positioning, torticollis.* Developmental dysplasia of the hip is a spectrum of disease from a loose hip to a dislocated hip.* Physical exam will feel a clunk or click on Barlow or Ortolani test* Ortolani, hold trochanters, hips brought in and out. Knees not involved as they can slip, which is normal.* Next step in management is hip ultrasound, which can be diagnostic in a newborn.* X-rays helpful later on, frog-leg position.* Treatment includes Pavlik harness, keeps femoral head in joint close to acetabulum, acetabulum grows around.* Treatment down the road could involve casting, so early diagnosis is better.* Overweight adolescent with limping and pain referring to knee. Think slipped capital femoral epiphysis.* Child tends to take antalgic position, leg rotated externally to reduce pain.* Test to order is suspecting slipped capital femoral epiphysis is TFTs (T4, TSH), FSH, LH because there is a higherrisk for endocrine problems and hypogonadism.--------------------------------------------------------------------------------------------------------------------------------------------Orthopedics: Scoliosis* 12yo girl is seen for routine physical exam. She voices no complains. Exam is remarkable for asymmetry of theposterior chest wall on bending forward. One shoulder appears higher than the other when she stands up.* Scoliosis is an abnormal curvature of the spine due to misalignment of the spine in the frontal plane.
DO NOT DISTRIBUTE - 25 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Scoliosis can occur at different ages. Most causes are idiopathic, other causes include hemivertebra.* Scoliosis is usually painless and diagnosed on routine physical exam via Adams test (forward bending).* Best test to diagnosis scoliosis is x-ray. Radiologist will tell you degree of curvature (Cobb angle).* Treatment usually not needed for mild curvatures.* Treatment for more severe curves includes bracing or even vertebra fusion.* Exercise and electrical stimulation have not been shown to help with scoliosis.* Complications include joint disease, cardiorespiratory disease if severe enough curve.* Infantile scoliosis (0-3yo), juvenile scoliosis, adolescent scoliosis.* Congenital scoliosis with hemivertebra and is associated with genitourinary abnormalities such as horseshoekidneys, congenital heart disease, and spinal dysraphisms (e.g. spina bifida).* Congenital scoliosis may require earlier surgical intervention to prevent worsening curvature.* Neuromuscular diseases associated include cerebral palsy.* Neurofibromatosis, Marfan, and VACTERL (VATER) syndromes associated with scoliosis.* VACTERL: Vertebral anomalies, Anal atresia, Cardiovascular anomalies, Tracheoesophageal fistula, Esophagealatresia, Renal (Kidney) and/or radial anomalies, Limb defects.--------------------------------------------------------------------------------------------------------------------------------------------Orthopedics: In-Toeing & Flat Feet* Newborn is noted to have a foot that is stiff and slightly smaller than the other. The affected foot is mediallyrotated and very stiff, with medial rotation of the heal. This is club foot, talipes equinovarus.* With medial rotation of the heal, think about club foot.* Half of club feet will be unilateral, half will be bilateral. More common in boys.* No known cause for talipes equinovarus, can be from in-utero positioning, can run in family.* Other disorders include amniotic bands, spinal dysraphisms, developmental dysplasia of the hip, arthrogryposis.* Differential diagnosis includes metatarsus adductus, tibial torsion, femoral anteversion.* With metatarsus adductus (metatarsus varus) you can bring the foot into neutral position and there is no healrotation, no need for special shoes or casts.* Tibial torsion diagnosed by looking at malleoli, medial malleolus is normally a little anterior to the lateral.Treatment is parental reassurance.* Femoral anteversion diagnosed by seeing the knees angled toward each other while child walks. Can be due tositting position so recommend child sits with legs out or legs out and crossed in front of them (not under).* Most children are born with fat pad on the bottom of their feet. As this disappears with age, they develop alongitudinal arch. They may look like flat feet early on and this is normal.* Management of flat feet is supportive, no need for arch support, no major problems.--------------------------------------------------------------------------------------------------------------------------------------------Orthopedics: Tumors* Bone tumors more likely seen in adolescents when there is rapid bone growth.* Primary neoplasms are osteosarcoma (most common) and Ewing sarcoma (more common in first decade of life).* Retinoblastoma associated with osteosarcoma, particularly bilateral retinoblastomas.* Osteosarcoma seen in long bones at the metaphysis.* Both osteosarcoma and Ewing sarcoma present with pain at the bone site. May be limitation of motion andpalpable visible tumor. Deep bone pain should make you suspicious, child waking up in the middle of the night.* Next step in management is x-ray. Osteosarcoma shows sunburst pattern on x-ray, Ewing shows onion-skinpattern. Ultimate diagnosis is made on biopsy.* Treatment is surgery and chemotherapy, worry about metastasis to other bones and lungs.* Ewing sarcoma will need surgery, chemo, and radiation. Prognosis worse if primary tumor in the pelvis or if thereis metastatic disease at the time of diagnosis.--------------------------------------------------------------------------------------------------------------------------------------------Orthopedics: Miscellaneous* Popliteal cyst (Baker cyst) is a non-pulsatile painless swelling on the back of the knee. Similar to ganglion cystseen on the wrist.* Treatment is reassurance.* Differential of popliteal cyst includes lipoma, aneurysm (pulsatile), neuroma, rarely tumor.* Osgood-Schlatter disease is an overuse injury (e.g. sports training), seen in ages 10-12yo commonly.* Knee pain is specifically over the tibial tubercle, traction apophysitis of tibial tubercle.* No real need for x-ray because you can palpate, but x-ray would show calcification at quadriceps insertion. Thecalcification is due to tearing at the insertion site with repetitive injury (e.g. doing drills for sports).
DO NOT DISTRIBUTE - 26 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Treatment is supportive, resolves over 1-2 years, mild analgesics (acetaminophen, ibuprofen).* Radial head subluxation (Nurse maid elbow) is associated with sudden traction. Baby being held and tractionoccurs, such as mother pulling child’s arm or child throwing them self on the ground in a temper tantrum.* Differential is broken bone. Next step is x-ray, but not completely necessary.* Treatment is gentle supination to slide radial head back into annular ligament.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Infectious Disease with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Immunizations* Actual immunization schedule months not as important as timing between immunization shots.* Baby had a temperature of 103F and cried consolably for 2 hours after receiving a DTaP vaccine. What is youradvice to the mother prior to administering the next set of immunizations?* This is a normal reaction to vaccination. Do not withhold vaccinations due to fever.* Immunity is resistance of a body to the effects of a deleterious agent, such as a pathogenic microorganism.* Types of immunity are acquired, active (antibody produced in response to vaccine or toxoid), passive (givingpreformed antibodies), natural (exposed to agent), herd.* Herd immunity means if enough immunizations are given in a certain population, those who are not immunized donot have to worry about disease since there will be no disease. This is a very important concept in almost allimmunizations as a group of people cannot get immunizations (e.g. chemotherapy, immunosuppressed, etc.) so theresponsible public protects these individuals by herd immunity.* Herd immunity is a great concept, but people may ask why does one child have to run the risk of an immunizationand another does not. This was part of the reasoning behind the vaccines/autism fiasco; the thought is that ifvaccines can cause autism then one can be selfish and let the rest of the population get vaccinated while the selfishindividuals reap the benefits of herd immunity. However, this increases risk for those who do not have the luxury ofchoice for vaccination (e.g. immunocompromised). Deaths from preventable disease have occurred in unvaccinatedpopulations, even today (2001-2009) such as the MN death in 2008 from Hemophilus influenzae B (Hib).* Vaccinated population must reach 90%, in general, for herd immunity protection.* DTaP is toxoids for diphtheria, tetanus, pertussis. Oral polio no longer used. Polio vaccine now is killed. MMR isa live vaccine, measles, mumps, rubella. HepB is a recombinant vaccine, so no live component. Varicella has livecomponent like MMR. Influenza is live also. Pneumococcal vaccine also available.* IM injections for non-live vaccines, subcutaneous injections for live component vaccines.* Inactivated vaccines can be given simultaneously at separate sites, except cholera, typhoid, and plague.* Live virus vaccines which are not given on the same day, should be given at least a month apart. So give MMRand varicella a month apart if they are not both available on the same day.* Pneumococcal and whole-virus influenza can be given simultaneously at different sites.* Egg hypersensitive is bad rash, angioedema, anaphylaxis, or other serious reaction.* Measles, mumps, influenza, yellow fever, and combined MMR vaccine are grown in eggs. Either avoid thevaccines with true egg hypersensitivity or desensitize first. If unknown egg hypersensitivity, risk is very low for ananaphylaxis reaction with vaccination. Must be known and/or documented serious egg reaction.* Neomycin and streptomycin are contained in killed polio and MMR. So avoid if neomycin allergy.* Vaccines have been free of thimerosal (mercury-component) since 2001. Risk of catching disease from non-vaccination is much higher than risk (if any) of thimerosal component issues.* Not vaccine contraindications: reaction to previous DPT with temperature less than 105F, redness sorenessswelling at shot site, mild acute illness in otherwise well child, child on antibiotics, preterm child, family history ofseizures, family history of sudden infant death syndrome (SIDS).* With delayed immunizations, rule is to give as many as you can when you can.* Immunization time frame is less important than the order of immunizations.* Hepatitis B (HBV) vaccine timing depends on if the mother is HBsAg positive. If mother is HepB surface antigennegative, then give vaccine at birth, one month, or two months of age. Next scheduled does will be 1-2 months afterfirst vaccine, third dose given 6-18 months after first vaccine. This is the same schedule used for anyone who hasnot received the vaccine before.* If mother is HBsAg positive, give HBV vaccine at birth and give baby HepB immune globulin (HBIG). Do notwait 1-2 months for next vaccine, give second vaccine 1 month later and give third vaccine 6 months after first. Thisschedule is more rigid. HBIG given at a separate site from the HBV vaccine because it can inactivate it.* DTaP is given at 2mo, 4mo, 6mo, and 15-18mo, then last dose around 4-6yo prior to starting school. Must get 4doses of DPT to get into school if the last does was after 4yo. Should get 5 doses ideally.
DO NOT DISTRIBUTE - 27 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Tetanus booster given every 10 years after DTaP series, unless you get a dirty cut/wound 5 or more years after thelast tetanus. If it has been 5+ years since last tetanus and patient has dirty wound (e.g. burns, stepped on nail) thenmust give the patient tetanus toxoid.* Tdap (tetanus and diphtheria toxoids with acellular pertussis) given at 11-12yo. Only one dose needed.* Acellular pertussis has greatly reduced side-effects (e.g. fever).* Hemophilus influenzae type B (Hib) given at 2mo, 4mo, 12-15mo. Another manufacturer is a 2mo, 4mo, 6mo, and12-15mo vaccination. So the 6mo shot for Hib is manufacturer dependent, do not mix and match the shots.* Oral polio no longer administered to anybody. Everyone gets the inactivated polio (IPV) at 2mo, 4mo, 6-18mo,and age 4-6 prior to starting school.* Pneumococcal vaccine was 23-valent, no 7-valent, newer 13-valent (2010). Given at 2mo, 4mo, 6mo, and 12-15mo of age.* MMR given 12-15mo age. Booster at 4-6yo prior to starting school.* Varicella given 12-18mo age as one vaccine. If older than 11yo give as two vaccines, 4 weeks apart.* Rotavirus shot or oral given at 2mo, 4mo.* Hepatitis A started after 12mo of age, 2 doses needed at least 6mo apart. Some controversy on need.* Meningococcal vaccine started after 2yo. Give MCV for those at high risk, such as persistent complementdeficiency or anatomic/functional asplenia.* Influenza vaccine (seasonal) given annually after 6mo. Now recommended for everyone.* When child gets immunization, you are not automatically protected. It takes a couple of weeks to developantibodies and get titers up. No vaccine is 100% effective.* If you get pertussis then you don’t really need the pertussis portion of the vaccine.* If you get invasive hemophilus influenzae B before 24mo of age, you still need the vaccination.* Once older than 15mo of age, you only need one vaccination of Hib. No need to get another for catch-up.* Hib should not be given after 60mo of age (5 years of age).* If there is a gap in immunizations, there is no need to start over again.* If patient has HIV, divide into mild versus moderate HIV (asymptomatic) and into severe immunosuppression.* DTaP can be given to any patient with HIV because it is not a live vaccine.* Oral polio should not be given to anyone. Killed polio is alright for HIV.* MMR is recommended for patients with mild to moderate immunosuppression but is not recommended withsevere immunosuppression as the vaccine could cause disease.* Hib is recombinant so it is not a problem. Pneumococcal is fine.* Influenza should be given even for severe immunosuppression.* Varicella vaccine should be considered even though it is a live attenuated vaccine.* Adverse side-effects seen with DTP are local redness, local swelling, local pain, fever > 38ºC (100.4F),drowsiness, fretfulness, anorexia, vomiting, crying > 3hrs. Fever is very common with DTP prior to DTaP.* MMR side effects do not occur right away, they occur about 7-10 days after vaccination.* Measles component can cause fever and measles-like rash. Mumps can cause swelling. Rubella can causearthralgia and adenopathy.* MMR side effects include febrile seizures and reversible encephalopathy.* Pregnant women should not get the MMR vaccine due to congenital rubella risk. If the women is pregnant and hasa child at home, the child at home can get the MMR vaccine because it is attenuated and even if they shed the virusthe mother is immune-competent so will not get the disease.* Delay getting MMR if gamma-globulin or immune-globulin was given in the past 3 months as this would decreasethe effect of the vaccine.* Contraindications to MMR include anaphylaxis, immunodeficiency (cancer, leukemia), severe HIVimmunosuppression, chemotherapy, radiation therapy.* There is no proof that the MMR vaccine causes autism. Autism is usually picked up before 30mo of age so it isusually diagnosed around the time of the MMR vaccine, a coincident. Get children immunized.* Hib side effects include local swelling, fever, invasive Hib disease under 2yo does not confirm immunity.* Pneumococcal vaccine given to prevent meningitis, not otitis media or sinus infections.* Influenza side effects are redness, tenderness, swelling, mild flu symptoms, now recommended for everyone. Priorrecommendation were chronic lung disease, health care workers, hemoglobinopathies, etc.* Meningococcal vaccine is recommended if traveling to endemic area, does not cover all serotypes.* HepB vaccine given because there are 5,800 deaths per year from HepB plus 300,000 new cases per year andabout a million carriers. The younger you are to get hepatitis, the greater the risk of liver failure later on.--------------------------------------------------------------------------------------------------------------------------------------------
DO NOT DISTRIBUTE - 28 -Study Notes – Pediatrics James Lamberg 01Apr2010
Fever* 5mo infant presents with 39ºC fever. Mother states child is less active and has a decreased appetite. On physicalexam, no focus of infection can be found. This is a common dilemma for the pediatrician.* Definition of fever is temp > 38ºC (100.4ºF) rectally.* Fever of short duration without localizing signs is short duration. Fever without focus is less than a week induration in children less than 36mo of age. Fever of unknown origin, a specific diagnosis meaning fever > 14d inchild and > 21d in adolescent or adult.* Fever without focus occurs in about 5% of children less than 36mo of age.* Babies are immuno-naïve. They are at higher risk to develop many infections, septic arthritis, meningitis, sepsis.* Children under 24mo are at very high risk for infection. Sometimes not very specific signs of symptoms.* Organisms that may be responsible are group B strep, E. coli, listeria. Others include salmonella, neisseria.* Most common cause of fever in children (and adults) is viruses.* Children older than 3mo of age with temps > 38.9 (102) are at risk for fever without a focus (occult bacteremia).* We can get bacteremia by brushing our teeth, but we clear it easily.* What should you order on these patients? CBC with differential and smear. May see Döhle bodies on a smear.* Risk factors for occult bacteremia include age < 24mo, fever > 104, WBC > 15000.* Order CBC and blood culture first. May toss in urine. Culture any suspicious lesions.* If child has sickle cell disease, be suspicious for pneumococcal infections.* Risk factors also include AIDS, immunodeficiencies, sick contacts, toxic clinical appearance and petechia.* All infants less than a month age with fever and suspicion for infection should be admitted to the hospital andstarted on antibiotics. If cultures are negative, then consider stopping antibiotics.* If less than a month of age, cover group B strep, listeria, E. coli, meaning start ampicillin and 3rd generationcephalosporin or ampicillin and an aminoglycoside.* Children > 1mo of age who appear well and have been in good health are unlikely to have serious illness if theircounts are between 5-15000 and absolute band count less than 1500. You may give ceftriaxone (or cefotaxime plusampicillin) if they appear well without a source for the fever while waiting for cultures. If they appear ill, admit.* Third generation cephalosporins to no cover listeria well so ampicillin is given.* Follow up with a phone call, have the child come back, check cultures.* 18mo child presents with temperature of 39ºC, the patient is alert and happy. The mother states that the child hasbeen eating well, has good urine output, and has no evidence of localized infection.* Most common organism for occult bacteremia is strep pneumonia in this age group.* Blood culture should be performed whenever you suspect occult bacteremia. Count > 15000 is high risk for havinga positive blood culture.* Without therapy, occult bacteremia may resolve spontaneously in this age group or lead to localized infection suchas meningitis or septic arthritis.* Non-toxic patients get empiric therapy with third gen cephalosporin and follow-up.* Toxic patients should consider spinal tap, start antibiotics, admit.* If positive blood culture and child looks better, may not need to treat further.--------------------------------------------------------------------------------------------------------------------------------------------Meningitis* 6yo presents to the ED with fever, headache, vomiting, neck ache, and photophobia. Physical exam reveals an ill-appearing child unable to flex his neck without pain. Kernig and Brudzinski signs are positive.* 6mo cannot have Kernig, Brudzinski, complaints of neck pain.* In infant, may get neck rigidity but best sign is bulging fontanelle. Examine fontanelle while child sitting up.* Meningitis is inflammation of leptomeninges. Bacterial meningitis is usually from hematogenous spread.* Neonates get group B strep meningitis. Anyone 2mo and up you should think about strep pneumonia.* Neisseria meningitidis is common in any age group. Scenario is college student in dorm or military recruits.* Risk factors for meningitis are splenic dysfunction, asplenia, meningomyelocele, day-care.* Patients with sickle cell disease specifically think about pneumococcus for meningitis.* Pneumococcus also seen with facial trauma leading to CSF leak.* Patients with ventriculoperitoneal (VP) shunts you should think staph.* Patients who are immunocompromised, all bets are off. Could be anything including pseudomonas.* Infants can just be irritable, restless, and feeding poorly, may have a fever or not.* Older children can have fever, headache, neck pain, photophobia, vomiting.* Purpuric lesions seen with DIC, not pathognomonic for meningococcus. If it is meningococcus, the lesions can bescraped and cultured. Pneumococcus can cause DIC as well.
DO NOT DISTRIBUTE - 29 -Study Notes – Pediatrics James Lamberg 01Apr2010
* CSF pyogenic: 200-5000 cells, PMNs, low glucose, high protein, high lactic acid, high pressures.* CSF partial treated: same as pyogenic but mostly PMNs, possibly negative cultures.* CSF granulomatous: 100-600 cells, lymphocytes, low glucose, high protein, high lactic acid, high pressure.* CSF aseptic: 100-700 cells, PMN to lymphocytes, normal glucose, slightly high protein, normal LA and pressure.* CSF neighborhood reactions: 100-500 cells, variable type of cells, normal glucose, variable protein, normal lacticacid, variable pressure.* Low glucose in CSF (hypoglycorrhachia) is related to blood sugar. Normal CSF glucose is 1/2 to 2/3 ofsimultaneous blood sugar.* High protein in CSF is 45 and above. Pre-term infants can get up to 100-140 for normal. After 3-5mo, use 45.* Granulomatous implies tuberculosis meningitis. Acid fast bacilli will not show on Gram stain but will culture.* Neighborhood reaction means another infection in the brain, e.g. abscess, causing meningeal irritation.* Meningitis treated with antibiotics and supportive care. Corticosteroids given if suspected Hib to decrease hearingloss. No major benefit shown, but if steroids given otherwise they should be given prior to antibiotics.* Aseptic meningitis occurs in the summer and fall, usually viral.* Sometimes bacterial meningitis CSF will not grow if patient is partially treated with antibiotics.* Treatment for aseptic meningitis is supportive, unless patient has herpes simplex meningitis then give acyclovir.* 4wk old presents with suspected meningitis, tap shows 15 cells, worry about herpes simplex meningitis.* Complications include death, neurologic complications are common such as hearing loss, mental retardation,seizures, developmental impairment, behavioral problems, hydrocephalus, ataxia, palsy, stroke, herniation, effusion.* Patient with meningitis is treated and spikes a fever a week later. Do a CT of the head looking for sub-duraleffusions. These are common with Hib.* Other complications during the disease include SIADH.* DDx includes toxins, ingestions, malignancies.* Prevention is via immunizations, treating close contacts with rifampin if they’ve had H. flu or neisseria exposures.--------------------------------------------------------------------------------------------------------------------------------------------Encephalitis* 10yo presents with fever and altered mental status. The parents state that over the past 24h the patient has beenextremely combative. There is no evidence of trauma or drug intoxication.* Encephalitis has more disorders of mental function than meningitis. Look for combative and hallucinations.* Encephalitis usually caused by arbovirus. Saint Louis encephalitis is spread by birds. California encephalitis isspread by rodents and mosquitoes. Western Equine carried by mosquitoes and birds. Eastern Equine carried bymosquitoes and birds. Colorado Tick Fever carried by ticks. West Nile by mosquitoes and birds.* Presentation is similar to aseptic meningitis but more confusion, delirium, combative, hallucinations.* History is important. Always ask about exposure to persons or animals, mosquitoes in the area.* Immunofluorescence testing, ELISA testing, IgM testing can be done. CSF may not show a lot.* If testing is needed, do polymerase chain reaction (PCR) on the CSF. Do not do brain biopsy.* MRI or EEG can be done. If anything is seen remotely close to the temporal lobe then think HSV and put them onacyclovir. Treatment is supportive.* Differential includes toxins, trauma, hypoglycemia, Reye syndrome, inborn errors of metabolism.* Post-infectious encephalitis can occur after MMR vaccine. Rarely trypanosomiasis and malaria.--------------------------------------------------------------------------------------------------------------------------------------------Osteomyelitis* 12mo infant presents to the physician with a chief complaint of refusal to bear weight on his left lower extremity.The mother states that the child had an ear infection one week ago. The patient was prescribed antibiotics but themother states she did not fill the prescription.* Osteomyelitis in children usually occurs from hematogenous spread, but can occur from contiguous spread fromsurround cellulitis or via direct inoculation from penetrating wounds.* Osteomyelitis seen in boys twice as often. Most common organism is staph aureus, so always cover staph.* Group B strep and Gram negative bacilli are important pathogens especially in the neonate.* Patients with sickle cell disease most commonly get staph aureus, but salmonella is second most common.* Pasteurella multocida is common if there is a dog bite.* Pseudomonas seen with puncture wounds as pseudomonas lives in the foam of the sneaker. Nail goes throughshoe, picks up pseudomonas from foam, then inoculates your foot.* Infants usually do not have systemic signs but will have pain on movement of the extremity.* Older children will have fever and complain of pain in the affected area. Will refuse to bear weight, decreasedrange of motion, physical exam will have cardinal signs of inflammation (calor, dolor, tumor, rubor).
DO NOT DISTRIBUTE - 30 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 31 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 32 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 33 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 34 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Patient comes in with gait disturbances, look for history of recovering from varicella.* DDx includes vesicular rashes (e.g. herpes, insect bites, staph). Get vaccinated.--------------------------------------------------------------------------------------------------------------------------------------------Scarlet Fever (Scarletina)* 7yo complains of a headache and sore throat. Physical exam shows temp of 103F, 3+ tonsils (large) with exudate,and a strawberry tongue. In addition he has circum-oral pallor and a sandpaper rash on his face, trunk and upperextremities. Dark red Pastia lines on the skin are noted.* Scarlet Fever is caused by group A beta-hemolytic strep.* Usually have with a sore throat pharyngitis. Can follow wounds, burns, streptococcal skin infection.* Abrupt onset of fever, chills, headache, sore throat. Can have abdominal pain due to mesenteric lymphadenitis.Can have vomiting, may look like appendicitis. Can have a rash in the axilla, groin, neck, which spreads.* Strawberry tongue, circum-oral pallor, and erythematous blanching feels-like-sandpaper rash.* Tonsils can be large and can peel, like in Kawasaki.* Quickest test is strep screen. Throat culture is better test.* Treatment is penicillin. Erythromycin, clindamycin, or cephalosporins can be used.* Complications include bacteremia, sinusitis, otitis media, osteomyelitis, cervical adenitis.* Rheumatic fever and glomerulonephritis can occur as well.* DDx includes roseola, but Scarlet Fever is rare in infancy. Seen in 5yo and older.--------------------------------------------------------------------------------------------------------------------------------------------Mumps (Parotitis)* 4yo unimmunized child presents with fever and unilateral parotid swelling.* Mumps caused by a paramyxovirus. Other virus causes parotitis, but talking about mumps virus here.* Spread by airborne droplets and saliva. Seen in the winter and spring. History of incomplete immunizations.* Patient contagious 1 day before swelling starts until 3 days after swelling starts.* Incubation period it about 2-3 weeks.* Presents with fever, headache, muscle pain, malaise, all non-specific. Then, they develop the parotitis.* If you look in the mouth (wearing a glove), you may be able to milk some stuff from the Stensen duct.* Pickle test is having patient drink something sour, which will cause pain due to increased salivation.* Occasionally there may be orchitis in males.* Diagnosis is usually clinical. Can see elevated serum amylase. Can culture virus in urine or CSF. Can do acuteconvalescent titers to see antibodies increase.* Treatment is supportive. Orchitis occurs in pubertal males, almost always unilateral.* Complications include meningoencephalitis (most common), otitis, infertility is rare.* DDx includes HIV, CMV, coxsackie virus, other parotitis viral forms, salivary calculus.--------------------------------------------------------------------------------------------------------------------------------------------Acquired Immune Deficiency Syndrome (AIDS)* 18mo has failure to thrive (FTT) and developmental delay. Patient has history of recurrent ear infections, oralthrush, and chronic diarrhea. On exam today, there is lymphadenopathy.* AIDS caused by HIV. Majority of cases are infants born to mothers with HIV. Adolescents is the second group ofchildren who get HIV, acquired the same way that adults get it.* Congenital transmission has been decreased immensely by treating mothers with zidovudine (antiretroviral).* Most children at birth look normal, but over time will develop FTT and recurrent infections.* Any child with lymphoid interstitial pneumonia should be considered to have HIV until proven otherwise.* Rarely, hepatosplenomegaly and recurrent bacterial sepsis.* Diagnosis is with ELISA and Western blot. Most common is Western blot, best test is PCR.* Children born to HIV-positive mother can be positive for up to 18 months before they turn negative.* DNA polymerase chain reaction is the preferred testing method for infants in developing countries.* HIV culture is not recommended for infants less than 1 month due to false positive results.* HIV disease in children > 18mo can be excluded if 2 antibody tests are negative, no hypogammaglobinemia, andno clinical evidence of HIV.* Treatment is the same as in adults. Aggressively treat secondary infections. Be aggressive with nutrition.--------------------------------------------------------------------------------------------------------------------------------------------Mononucleosis (Mono, “Kissing Disease”)* 17yo presents with fever, fatigue, and headache. He also complains of sore throat and left upper quadrant pain. Onphysical exam he is noted to have generalized lymphadenopathy, enlarged tonsils, and hepatosplenomegaly.* Epstein-Barr virus (EBV) causes mononucleosis and is spread by saliva and intimate contact.
DO NOT DISTRIBUTE - 35 -Study Notes – Pediatrics James Lamberg 01Apr2010
* May be asymptomatic as infants. More common in adolescents, flu-like symptoms for a couple of weeks.* Physical exam can be pharyngitis (very bad looking),* Up to 1/3 of patients can have a positive strep screen. If you treated this with penicillin and they broke out in arash, think about mononucleosis. This is an ampicillin (and amoxicillin) rash and is precipitated about 99% of thetime, virtually diagnostic.* Helpful test is CBC with atypical lymphocytes (Downey cells). Mono spot test (heterophile antibody test) is forscreening. With acute infection, heterophile antibodies are produced. Can also do EBV titers.* Treatment is supportive care, avoid penicillin drugs (rash reaction). Avoid contact sports for 2-3 weeks to allowfor the spleen to reduce in size (preventing rupture).* DDx includes group A beta-hemolytic strep infection.* Can get high WBC count with thrombocytopenia, consider leukemia.--------------------------------------------------------------------------------------------------------------------------------------------Influenza Virus & Adenovirus* 14yo is seen by his physician because of fever, headaches, myalgia, chills, and cough.* Every year this is a wave of influenza, vaccines developed based on yearly serotypes.* Types A and B are responsible for epidemics.* Older children present like adults with typical symptoms. Can get flushed face, myalgia, cough, chills for 2-5 days,nasal congestion and cough for 4-10 days. Younger children do not get as much influenza, but can have symptomsof laryngotracheitis or bronchiolitis or upper respiratory infections.* Diagnosis from nasal swab or nasopharyngeal washes, can do immunofluorescence antibodies.* Treatment is amantadine and rimantadine for serious cases, usually don’t help much. Antivirals have to be givenvery early and usually by the time the patient gets to the doctor it is too late.* Influenza treatment is generally supportive.* Worry about secondary bacterial infections. Hard to differentiate flu from other viral infections.* With adenovirus, patient presents with fever, sore throat, and conjunctivitis. Usually seen in the spring andsummer. Incubation period is 2-14 days. Can cause diarrhea. Look for pharyngitis, rhinitis, conjunctivitis.* Can do nasal washes for adenovirus, can do fluorescence antibodies and cultures.* Adenovirus treatment is supportive.--------------------------------------------------------------------------------------------------------------------------------------------Hand-Foot-Mouth Disease (Coxsackie A Virus)* 2yo presents with a vesicular rash in his mouth and on his palms and soles. Mother states he has a rash on hisbuttocks.* With hand, foot, and mouth disease there are blisters on an erythematous base. Lesions can be anywhere.* Incubation period is 4-6 days, usually in the summer and fall. Epidemics in 3-year cycles.* Diagnosis is clinical. Treatment is supportive care.--------------------------------------------------------------------------------------------------------------------------------------------Pinworm (Enterobiasis)* A mother brings her 4yo child to the physician with a history of anal itching. The patient attends daycare and youare told the child’s favorite activity is playing in the sandbox.* Enterobiasis is the most common parasitic infection of children in temperate climates.* Worms are white and at most 1cm in length.* Will have nocturnal anal pruritus. Female worms go to anal region and lay eggs usually at night. Child willconstantly re-infect because the scratch their butts (stick eggs) and touch their faces, eat with hands, etc.* Diagnosis is via microscopic examination of worms or eggs. Can get stool for ova and parasites.* Can get eggs from a tape test (Scotch tape test). Put tape on child’s anus prior to bed, remove tape in the morningand examine under the microscope for eggs. May be able to see worms at night in anal cavity.* Complications include excoriations from scratching.* Can get a massive infestation with pinworms in the appendix.* Almost all parasites cause eosinophilia. Enterobiasis is an exception, no eosinophilia.* Treatment is for infected/symptomatic individuals but consider for whole family. May need to repeat thetreatment. Treatment with benzimidazole compounds like albendazole and mebendazole.--------------------------------------------------------------------------------------------------------------------------------------------Roundworm (Ascaris Lumbricoides)* Infant is brought in because the mother found a worm in the diaper.* Ascaris is found in warm climates, transmitted from soil when using human feces as a fertilizer. Fecal oral.* Larva are ingested and they penetrate the intestinal wall. They work their way up to the lungs via circulation. Then
DO NOT DISTRIBUTE - 36 -Study Notes – Pediatrics James Lamberg 01Apr2010
they break through lung tissues, which can cause hemoptysis and Löffler (Loeffler) syndrome. The worms thencrawl up the tracheobronchial tree, you cough to clear throat, and swallow. Now the adults are living in your GItract. They do not attach, just swim against the peristaltic wave.* Children can have colicky abdominal pain, bile-stained emesis, pulmonary ascariasis (cough, blood-stainedsputum, pulmonary eosinophilia).* Best test is stool studies for ova and parasites. May see the worm in nose/mouth or in stool.* Treatment is albendazole, pyrantel pamoate, or mebendazole. Piperazine better for intestinal obstruction.--------------------------------------------------------------------------------------------------------------------------------------------Scabies (Sarcoptes Scabeii)* Mother brings her 3 children to you because they have a pruritic rash that has been present for the past threemonths. Mother states that she and her husband have a similar rash that began in the webs of the fingers. The itchinghas spread to the wrist, elbows, and axilla.* Children get it more than adults. In older children and adults it does not affect the face. Usually neck down.* Hallmark sign is itchiness. Burrow is characteristic lesion as mite digs under skin, more common in adults than inchildren and can be seen in webs of fingers or toes.* Infants present with rash, may be vesicular like atopic dermatitis. Unlikely that 3 kids get atopic dermatitis at thesame time, much more likely that they have scabies.* Children may not get burrows but get vesicles, pustules, scabs. May affect face in infants.* Diagnosis is clinical, but can scrape the skin at a vesicle and look under a microscope for eggs or mite.* Treatment is permethrin or lindane cream, cover entire body and keep on overnight. Do not use lindane in smallchildren due to neurotoxicity. Children under 6mo can use a sulfur petrolatum mixture. Treat everybody. Can giveantipruritics too, like antihistamines.* Complications include impetigo or secondary skin infections due to persistent scratching.--------------------------------------------------------------------------------------------------------------------------------------------Lice (Pediculosis)* The school nurse refers a first grade child to you because of nits in the child’s hair.* Lice are obligate parasites of the human. They affect body, head, pubic.* Risk factors include poor hygiene. Pubic lice is transmitted via sexual contact. Body louse hardly every seen inchildren. Most common is head lice.* Hallmark sign is itchiness. Exam will show nits (eggs) and possibly louse. The lice like to stay close to the scalp,so if a nit is at the end of long hair it means you’ve had it for a very long time, likely an empty egg.* Treatment is permethrin for body lice, also kills the nits. Petrolatum (petroleum jelly) for eyelashes.--------------------------------------------------------------------------------------------------------------------------------------------Hookworm (Necator Americanus, Ancylostoma Duodenale)* 5yo presents with complaints of anorexia, abdominal pain, and diarrhea. The patient is noted to have a yellow-green pallor.* Hookworm is a helminth and can cause blood loss. Hookworm attaches (unlike ascaris) and can suck blood, up tohalf a mL per day per organism.* Hookworms found in warm moist soil especially in rural areas. Wear shoes. They penetrate through the skin or canbe ingested. Eventually attach to the wall of the intestine.* Can have itch at penetration site. Can have abdominal pain or fullness with larger infections, diarrhea.* Yellow-green pallor is known as chlorosis, “green sickness”, this is hypochromic anemia.* Best test is stool for ova and parasites.* Treatment is mebendazole or albendazole.--------------------------------------------------------------------------------------------------------------------------------------------Other Parasites* Rectal prolapse seen in Trichuris trichiura (whipworm).* Cutaneous larva migrans (CLM) seen in Ancylostoma braziliense, “creeping eruption”. From dog stool. Causesintense itching but is self limiting.--------------------------------------------------------------------------------------------------------------------------------------------Fungal Infections: Topical* Newborn is noted to have white plaques on his buccal mucosa that are difficult to remove.* Oral thrush is caused by candida. They look like milk curds, but will not scrape off.* Candidiasis can affect the diaper area with erythema and satellite lesions.* Scraping candida plaques with KOH prep will show hyphae on microscope.* Candida occurs in infants because they like a dark, warm, moist place (mouth, diaper area). Can also occur in the
DO NOT DISTRIBUTE - 37 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 38 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 39 -Study Notes – Pediatrics James Lamberg 01Apr2010
* DDx includes scabies, allergic contact dermatitis (e.g. on toe from glues used in shoes, poison ivy, poison sumac,poison oak).--------------------------------------------------------------------------------------------------------------------------------------------Immunology: Deficiencies Overview* With immune deficiencies, there is a history of recurrent infections. May not present right at birth because themother’s immune globulins are circulating.* History of recurrent sinus infections, failure to thrive, recurrent pulmonary infections, recurrent bacterial sepsis.* The best test for suspected immune deficiencies is serum immunoglobulins.* Patients could have skin lesions, autoimmune disease, hepatosplenomegaly.* Order CBC with manual differential, sed rate (not specific), immunoglobulin levels. Can get antibody titers andIgG subclasses. So if you suspect B-cell deficiencies then order immunoglobulin levels. For T-cell deficiencies,order absolute lymphocyte counts and skin testing for delayed hypersensitivity. For phagocyte deficiency orderabsolute neutrophil count (CBC) and neutrophil respiratory burst testing. Complement deficiencies order CH50.* 15mo child presents to the physician with fever of 39C. Exam reveals right tympanic membrane that iserythematous and bulging, has obscured landmarks and no mobility. This is otitis media. On review of medicalrecords, you note that since 9mo this child has had multiple infections with otitis media, sinusitis, and pneumonia.--------------------------------------------------------------------------------------------------------------------------------------------Immunology: Agammaglobulinemias* Bruton disease (X-linked congenital agammaglobulinemia, panhypogammaglobulinemia) is due to defects in theB-lymphocytes. This is X-linked (q22 chromosome) and involves all three classes of immunoglobulins.* Most boys with Bruton will present after maternal antibodies fall at about age 6-12 months.* Patients will get repeated infections. Exam may show hypoplasia of tonsils and adenoids, no LAD, no HSM.* Carriers are detected by direct mutation analysis. Prenatal detection is done by mutation analysis.* With suspected Bruton, draw serum immunoglobulins from patient. All three classes will be decreased.* Treatment is antibiotics for infections and immunoglobulin therapy (IgG injection once a month).* Paralysis after polio vaccination has occurred but is not likely anymore with killed vaccination.* Bruton patients at risk for mycoplasma, hepatitis, enteroviruses are difficult to handle.* 3yo is brought to your office because of recurrent URIs and UTIs as well as chronic diarrhea. IgA deficiency.* You suspect immune deficiency here so you order all immunoglobulins.* IgA deficiency is the most common humeral antibody deficiency. Unknown transmission, autosomal dominant?* Patients susceptible to recurrent respiratory infections and can have chronic diarrhea.* Patients with IgA deficiency need blood screening. If they need blood transfusion, the blood bank must knowabout the IgA deficiency because there can be an incompatibility reaction.* High association with lupus, arthritis, increased cancer risk. Be careful with blood products because they developanti-IgA antibodies, can have anaphylactic reaction.* 2yo presents to your office with greater than 7 sinopulmonary infections in the past year. The patient does not havesiblings and does not attend daycare. No one is ill in the household. The patient does not have any pets or animalexposure, no recent travel, no FTT, is at 50% for height and weight at age.* Four subclasses of IgG. When one or more is low the you get IgG subclass deficiency. Order immunoglobulinlevels.* Most patients with IgG-2 deficiency will also have IgA deficiency.* Diagnosis is via IgG subclasses. Gamma replacement therapy is indicated.--------------------------------------------------------------------------------------------------------------------------------------------Immunology: DiGeorge Syndrome* 3week old infant presents with a generalized seizure. The patient was born to a 22yo G1P1 Caucasian at full termwith spontaneous vaginal delivery. The mother had good prenatal care and denies tobacco or drug use. There wereno complications at delivery. Patient weighed 7lbs 6oz at birth and had gained weight. The patient has been feedingand sleeping well. Exam shows hypertelorism (eyes wide spaced), low set ears, micrognathia, and fish-mouth. Thisis DiGeorge syndrome.* DiGeorge syndrome associated with conotruncal defects of the heart. T-cell defect. Thymic hypoplasia from injuryto cephalic crest cells, which contribute to the 3rd and 4th pharyngeal pouches.* Hypoplasia of thymus and parathyroid glands.* Other structure that form at the same time can be affected, heart disease, hypertelorism, esophageal atresia, bifiduvula, micrognathia. May look like fetal alcohol syndrome.* First manifestation may be hypocalcemia or seizure due to hypocalcemia from parathyroid hypoplasia.* DiGeorge occurs in both boys and girls, on chromosome 22.
DO NOT DISTRIBUTE - 40 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Some children will have partial DiGeorge syndrome/sequence and not have problems. Complete DiGeorge hasmany complications, including graft versus host disease from non-irradiated blood transfusion.* Exam can show epicanthal folds, wide-spaced eyes, low-set ears, short philtrum, ASD, VSD, truncus arteriosus.* Genotyping with PCR can be done to get diagnosis. Normally diagnosis is clinical.* Treatment is thymic tissue transplants, bone marrow transplants.--------------------------------------------------------------------------------------------------------------------------------------------Immunology: B & T-Cell Deficiency* 1yo infants presents to the physician with severe eczema. Exam shows draining ears and petechial rash. Review ofrecord reveals recurrent infections including otitis media and pnemonia.* Wiskott-Aldrich syndrome is a B-cell and T-cell defect. X-linked recessive.* Recurrent infections, thrombocytopenia, eczema. Maybe HSM.* Wiskott-Aldrich mnemonic MR TEXT: IgM decreased, Recurrent infections, T-cell and B-cell, Eczema, X-linkedrecessive, Thrombocytopenia.* IgA and IgE will be high, IgG will be normal or low, IgM will be low.* Splenectomy is treatment, can take care of thrombocytopenia. Higher risk of infection though especially withencapsulated bacteria like pneumococcus. Need antibiotic prophylaxis.* Wiskott-Aldrich syndrome definitive treatment is bone marrow transplant.* Complications include bleeding due to thrombocytopenia, higher risk of malignancy.--------------------------------------------------------------------------------------------------------------------------------------------Immunology: Ataxia Telangiectasia* 3yo presents with ataxia, mask-like facies, drooling, tics, and irregular eye movements. According to the mother,the ataxia began at about 1yo. Exam shows eyes with telangiectasia. History involves recurrent respiratoryinfections.* Ataxia telangiectasia can involve telangiectases of the eyes/skin, chronic pneumonias, endocrine abnormalities.* Humeral and cellular immunodeficiencies.* Ataxia telangiectasia is autosomal recessive and on chromosome 11.* What are the odds of having another affected child? Answer is 1 in 4.* First neurologic sign is ataxia, starts after the child begins walking.* Testing includes immunoglobulins levels, showing IgA deficiency, low IgE and IgM. CD3 and CD4 countsmoderately lowered, CD8 count moderately high.* Children usually end up in wheelchairs by the age of 12. High risk for varicella.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Respiratory with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Development of the Eye* Babies are born with large eyes, 65-75% of adult size at birth.* When babies are first born, their eyes go all over, cross, etc. It takes 3-4 months for them to fix and give binocularfixation. You can get strabismus before but do not worry much.* Normal eyesight is not present at birth. At birth, normally 20/200 to 20/300. Can only see about 12-19 inchesclearly, about the distance from the mom’s face to the baby’s face when nursing (not a coincidence).* By age 5-6, eyesight is 20/20.* Newborns see black and white better than color and see patterns better. Black and white cutout checkerboard ortarget patterns in the newborn nursery helps stimulate the baby sitting in the crib.* Color blindness is usually red-green and X-linked recessive disease (from mother).* Coloboma is a defect of the eyelid but can do deeper layers into the eye (iris, lens, retina, choroid). Opening in thelid can lead to ulceration and scarring due to scaring.* Coloboma may be isolated but associated with chromosomal disorders and malformation syndromes.* Epicanthal folds may be very prominent in infants, giving pseudo-strabismus due to wide nasal bridge.* Ptosis (upper eyelid drooping) is the most common anomaly of the eyelid, usually isolated, usually no treatment.Can be associated with botulism and myasthenia gravis. Can be surgically corrected.* Infections of the lid include blepharitis (inflammation of lid margins, associated with pain, itching, burning, eyelidredness), hordeolum (stye, staph infection of ciliary follicles/glands along the lid margin, treat with warmcompresses and topical antibiotics), chalazion (granulomatous inflammatory response, below lid margin, retention ofsecretions of meibomian glands, scrape out via incision looks like tapioca pudding).* 12-hour-old newborn is noted to have bilateral conjunctival injection, tearing, and left eyelid swelling. Exam isotherwise normal.
DO NOT DISTRIBUTE - 41 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Conjunctivitis is inflammation of conjunctival vessels. If newborn less than 24h old, think chemical fromsomething like silver nitrate drops (used prior to erythromycin).* Gonococcal ophthalmia can be prevented with erythromycin drops. Purulent bilateral conjunctivitis, about 5d ofage or later if failed topical antibiotics. Bacterial conjunctivitis not seen in the first 24h of life.* Chlamydia is the most common cause of conjunctivitis, 5-23d after birth.* Purulent conjunctivitis is usually bacterial, seen in older children. Viruses can cause conjunctivitis (pertussis,measles, Kawasaki). Allergies can cause conjunctivitis.* Conjunctivitis exam will show tearing, conjunctival erythema, lid redness, discharge.* Pain with photophobia, stop thinking about conjunctivitis and think about corneal problems.* Gram stain discharge (quick answer) and culture (day or two wait).* Treatment for gonococcal conjunctivitis is ceftriaxone. Prevention with silver nitrate or erythromycin topical.* Treatment of chlamydial conjunctivitis is with erythromycin topically and systemically to prevent pneumonia.* Older children with acute purulent conjunctivitis use topical antibiotic drops.*Allergic conjunctivitis with decongestant drops or mast cell stabilizers or antihistamine drops, cool compress.* Ophthalmia neonatorum can cause corneal problems. Most other conjunctivitis does not have complications.* DDx dacryostenosis which is nasal lacrimal duct obstruction, usually unilateral, newborn or infant, treated withgentle massage about 3-4x/day.* Subconjunctival hemorrhage from birth trauma or forceful vomiting or coughing. Bright red patch seen in theconjunctiva. Can occur with mild trauma, coughing, sneezing, conjunctivitis. Resolves on its own.* For strabismus and amblyopia, do cover test and Hirschberg test, where you shine light and see where it bouncesoff the eyes. It should bounce off the center of the pupil in both eyes. Then do cover test, cover the eye that isstraight ahead. If there is amblyopia, the lazy eye will go straight ahead.* Strabismus is a misalignment of the eyes (divergent, convergent). Results from abnormal innervation of themuscles from the supranuclear nerve. Can have transient or pseudo-strabismus up to 4mo.* Extraocular movements normal in strabismus.* Treatment for strabismus is glasses and possibly surgery to correct the muscle, shorten/trim muscle.* 5yo boy is seen in the office because his left eye turns in. Exam reveals turning in of the left eye. Extraocularmovements are intact. Covering the right eye cause the left eye to straighten out. Visual acuity is affected in the lefteye, needs glasses. Patching the good eye helps, but do not patch for too long, refer to ophthalmologist.* Amblyopia is a decrease in visual acuity as a result of an unclear image falling on the retina. It can be caused bystrabismus or by an opacity in the visual axis (deprivation).* Treatment is remove opacity if it exists. If no opacity, patch the good eye.* 7yo boy presents with swelling around the eye two days after suffering an insect bite to the eyelid. There is edema,erythema, and proptosis of the eye. Marked limitation of eye movements are noted. He has a low grade fever. This isorbital cellulitis (versus periorbital cellulitis).* Key for orbital cellulitis is proptosis and limited eye movements.* Periorbital cellulitis is an inflammatory condition involving the tissues of the orbit. It most commonly arises fromsinusitis. Organisms are H. influenzae type B, staph, group A beta hemolytic strep, strep pneumonia, anaerobes.* Periorbital cellulitis can occur after direct infection from a wound (e.g. trauma, bug bite).* Patients with orbital cellulitis will complain of orbital pain, decreased vision, proptosis (eye pushed forward),conjunctival edema, and eyelid swelling.* Stage I orbital cellulitis is swelling of the eyelid still confined to the sinus.* Stage II is sub-periosteal abscess.* Stage III is true orbital cellulitis with limitation of eye movement.* Stage IV is an orbital abscess.* Orbital and periorbital cellulitis both diagnosed clinically. Can get CT scan if needed.* Treatment is antibiotics. Orbital cellulitis may need to be drained.* Complications include loss of vision.* Periorbital cellulitis with violaceous color is more specific for H. influenza type B.* Retinoblastoma is diagnosed with white reflex, leukocoria.* Eyelid ecchymosis (black eye) occurs after trauma and resorbs spontaneously (goes away).* Foreign bodies to the eye produce discomfort, tearing, irritation. Foreign body under the eyelid can mimic acorneal foreign body. Pull down eyelids, evert eyelids.* Intraocular foreign body would be someone hammering a nail then feels something go into their eye. In this case,call the ophthalmologist.* Pain and photophobia in the eye, corneal abrasion. Do a fluorescein stain, look under a cobalt blue lamp.
DO NOT DISTRIBUTE - 42 -Study Notes – Pediatrics James Lamberg 01Apr2010
Treatment is topical antibiotics, tape, and leave alone for about 24h, check next day. If not getting any better, call theophthalmologist. Know what you’re dealing with before starting steroid drops in the eye. If viral infection and youstart steroids, you may be hurting them more than helping them.--------------------------------------------------------------------------------------------------------------------------------------------Development of the Teeth* 7mo infant is very fussy, drooling, and grabs at her left ear. Exam reveals normal tympanic membranes, mildswelling of the gingiva.* Ear infections do not really cause fever, rashes, diarrhea, these are folk-tales.* Teething starts about 6-8mo of age, as teeth erupt. Signs and symptoms are local discomfort, bluish discolorationof the gums (hematoma or eruption cysts), drooling, fussy.* No substantial evidence relating teething to diarrhea, rashes, rhinorrhea, fever.* Treatment consists of teething rings and cool compresses, nothing frozen because they can stick.* Incisors erupt about 6-9 months. 1st molars at 10-15 months. Canines and 2nd molars at 16-27 months. Somechildren are born with a tooth. Some a year old with only one tooth.* First teeth to erupt are the lower central incisors, then upper central incisors, then upper lateral incisors, then lowerlateral incisors. By age 1yo, 6-8 teeth. By 2yo, 12-16 teeth. By 3yo all teeth.* Milk bottle (nursing) caries caused by diet, particularly sticky carbohydrates. Bacteria can cause cavities,particularly strep mutans. Repetitive/continued exposure can cause caries. Don’t let baby go to bed with a bottle.Lesions are usually easy to see, may complain of pain because of tooth decay. Fluoride started at 6mo if breast fed,use fluoride water with any formula mix. Brush teeth as soon as they erupt. Best first dental checkup is age 3.* Tetracycline can cause yellow discoloration of the teeth, enamel hypoplasia.* Gingival hyperplasia caused by phenytoin, reversible. Need good oral hygiene.* Cleft lip is a cosmetic problem. Cleft palate affects speech, aspiration, and ear infections. Surgical repair necessaryat 10 weeks and 10lbs.* Geographic tongue is common, normal variant, sometimes normal with viral infections.* No such thing as a hairy tongue. Black hairy tongue is elongated papilla.--------------------------------------------------------------------------------------------------------------------------------------------Development of the Ears* Otitis media is related to 30million visits/year to the doctor. Expenditures > $2billion/year in 2000. Ventilationtubes (T-tubes, PE-tubes) most common minor surgical procedure. Tonsillectomy/adenoidectomy most commonmajor surgical procedure.* 4yo seen in the office with three day history of fever and cold symptoms. He now complains of right ear pain.Exam shows a bulging tympanic membrane with loss of light reflex and landmarks.* Risk factors for otitis media include being younger than 6yo, males, daycare, second-hand smoke, formula feeding(breast is best, less infections, higher IQ), craniofacial anatomy.* Caused by allergy, immunologic deficiency, ciliary dyskinesia, eustachian tube dysfunction, viruses (RSV,parainfluenza, adenovirus), bacteria (S. pneumonia, nontypable H. influenzae, M. catarrhalis).* Most common bacterial cause is S. pneumonia. Many H. influenzae are beta-lactamase producers. M. catarrhalisare all beta-lactamase producers. S. pyogenes type A also commonly beta-lactamase positive.* Child eustachian tube is more horizontal. With more colds, pressure differences can force pathogens into the ear.* Acute otitis media (AOM) symptoms include earache (otalgia, most common complaint) or ear pain, ear drainage,fever, diarrhea, irritability, anorexia.* Diagnosis by looking at tympanic membrane, pneumatic otoscopy (blow ear into canal to see membranemovement) best test, good for chronic serous otitis media too.* Treatment is antibiotics, amoxicillin preferred. If resistance, amoxicillin/clavulanic acid (covers beta-lactamaseproducers) plus amoxicillin, third-gen cephalosporins.* Fever or earache after 72h of treatment, think beta-lactamase producers and change antibiotics.* Complications include persistent middle ear effusion (no treatment), recurrent otitis media (myringostomy tubes),hearing loss (most common complication), ear drum perforation, mastoiditis, cholesteatoma (squamous epithelialcells caught in tympanic membrane, can spread and destroy temporal bone structures), meningitis (most commonintracranial complication), labyrinthitis (vertigo, nystagmus, tinnitus, hearing loss, vomiting).* Treat to avoid hearing loss, impaired speech/language development, cognition, school performance.* Otitis externa (swimmer ear) differentiated from AOM by exam. Otitis externa usually caused by repeated wettingof the ear canal or repeated trauma to the ear canal. Pain with external ear manipulation, pulling on pinna.* Exam may show red canal with macerations. Otitis externa and AOM both cause ear ache.* Causes of otitis externa include pseudomonas and staph aureus.
DO NOT DISTRIBUTE - 43 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Treatment with antibiotic drops. Tell not to put anything into ears. Rule of thumb is not to put anything in your earthat is smaller than your elbow. Do not use ear swabs, this packs wax in or causes otitis externa from trauma.* Best way to remove a live insect foreign body from the ear is with viscous lidocaine. The lidocaine irritates thebug and it works its way out. If you use mineral oil or something else, you’ll end up having to dig out the dead bug.* If foreign body is a dry vegetable (corn, bean) do not flush it out because if it does not come out it will swell.--------------------------------------------------------------------------------------------------------------------------------------------Development of the Nose* A newborn is noted to be cyanotic in the well-born nursery. On stimulation he cries and becomes pink again. Thenurse has difficulty passing a catheter through the nose. This is choanal atresia.* Choanal atresia is a septum between the nose and pharynx. Presents at birth because babies are obligate nosebreathers. When they get stimulated they cry and breath through their mouth.* Choanal atresia key is blue baby that pinks up with crying.* Associated with CHARGE syndrome: Coloboma, Heart disease, choanal Atresia, Retarded growth/development,Genital anomalies (e.g. hypogonadism), Ear anomalies (e.g. deftness).* Diagnostic test is inability to pass catheter through nose. Fiber-optic rhinoscopy can be done to see the plate.* Treatment is ABC (establish airway), surgical correction.* Common colds usually caused by rhinoviruses.* Children are the major reservoirs for the common cold. Residents and medical students will catch these illnessesbecause they haven’t been exposed to these germs in a long time.* Incubation period for common cold is 2-5 days, large droplet or small aerosol transmission (coughing, sneezing)and gets on hands, especially in kids who get snot all over and don’t wash their hands.* Symptoms are fever, nasal congestion, rhinorrhea, sneezing, pharyngitis, malaise may be present.* Treating with antihistamines does not help. It will last a week without treatment and 7 days with treatment (joke).* Decongestants may help. Vitamin C, Zinc, Echinacea, all not proven to help.* Sinusitis is caused by strep pneumonia, moraxella, nontypable h. influenza, sometimes staph or anaerobes.* Look for purulent nasal drainage and coughing with sinusitis.* If child has had a cold for more than 10 days, think sinusitis. If child has been improving with a cold then spikes afever, think sinusitis. If drainage become purulent after 7-10 days, think sinusitis.* Older children and adolescents will complain of headaches, tenderness to palpation of frontal or maxillary sinuses.Little children will not because they do not have developed sinuses.* Diagnosis is clinical. Can get x-rays in older children who have developed sinuses, seeing air-fluid levels.* CT scan would be diagnostic, but much more expensive.* If you suspect sinusitis, have to order a test, and child is old enough (like > 6yo), you can order sinus x-ray films.* Treatment is antibiotics for 14-21 days. May need to treat for 21 days if antibiotics cannot fully penetrate.* Complications include orbital cellulitis, abscesses, meningitis.* Majority of nose bleeds occur due to nose trauma or picking nose.* 8yo has repeated episodes of nosebleeds. Past history, family history, physical exam are unremarkable. Mostcommon cause is picking your nose. Other causes include allergic rhinitis or recurrent URIs (inflammation).* Rarely nosebleeds are caused by vascular anomalies or coagulation problems.* Epistaxis is rare outside of childhood, seen again in elderly.* Angiofibroma should be considered in pubertal boys with profuse bleeding and associated nasal mass.* Foreign bodies can cause nosebleeds, but usually you see purulent unilateral nasal discharge.* 3yo seen in the office due to foul-smelling unilateral purulent nasal discharge. Strep screen in the ED is negativethe night before. You walk into the room and it smells foul. Exam shows normal ears and throat. Exam of the noseshows a piece of foam.* Nosebleeds usually occur without any warning, are usually unilateral, and can recur soon after.* Most nosebleeds will resolve spontaneously.* Treatment is nasal compression with leaning forward (do not lean backwards).* Local vasoconstrictor spray can be used (e.g. epinephrine). Nasal packing can be used for severe bleeds. Nasalpacks are usually left in for a day or two. Clean out the nose (blowing) prior to placing nasal packs.--------------------------------------------------------------------------------------------------------------------------------------------Development of the Throat* 8yo girl complains by acute sore throat of 2 days duration accompanied by fever and mild abdominal pain.Physical exam reveals large erythematous tonsils with exudate and large slightly tender lymph nodes. This ispharyngitis. Is this strep throat? You don’t know yet.* Pharyngitis caused by viral infections in 50-55% of cases. Most causes of viral pharyngitis follow “colds and flu”
DO NOT DISTRIBUTE - 44 -Study Notes – Pediatrics James Lamberg 01Apr2010
due to viruses. Most viral cases are self-limiting and resolve without treatment.* Most common pathogen in bacterial pharyngitis is S. pyogenes (25%). Probable co-pathogens are H. influenza(18%), M. catarrhalis (16%), and S. aureus (2%).* Pharyngitis caused by S. pyogenes particularly affects children between ages 5 and 10 years.* Most common causes of pharyngitis are viruses or group A beta hemolytic strep. You cannot tell the difference bylooking in the throat.* Gold standard test is throat culture. A negative rapid test needs to be backed up with a culture.* Pharyngitis is rare under 1yo, usually acute. More common in 5-15 years of age. Under 5yo, think viruses.* Both viral and bacterial have erythema, exudates, petechia, enlarged tonsils, cervical adenopathy.* Viral pharyngitis is usually gradual onset preceded by cold symptoms. If vesicles or ulcers in the mouth, you canbe more confident in saying it is viral. Conjunctivitis associated with adenovirus.* Group A strep may have more headache, more abdominal pain, usually no URI symptoms.* Palatal petechia seen in both but more suggestive in strep.* Exam shows swollen red tonsils, red swollen uvula, palatal petechia. Strep of virus? Answer is you don’t know.* Kissing tonsils (Grade IV, 4+ tonsils) when tonsils are so large they touch. Strep or virus? You don’t know.* Circum-oral pallor, erythematous fine blanching sandpaper rash with strep pharyngitis usually.* White strawberry tongue seen with Scarlet fever. Probably strep.* Complications include peritonsillar abscess, bacteremia, acute rheumatic fever, glomerulonephritis.* Treatment of viral pharyngitis is supportive, treat the symptoms, throat lozenges, salt water gargles, whatever.* Treatment of strep pharyngitis is penicillin. If allergic, erythromycin or cephalosporins.* Retropharyngeal abscess may have drooling, airway obstruction, respiratory distress. Treatment is ABCs,antibiotics, drainage.* Peritonsillar abscess may have enlarged tonsil pushing uvula away, “hot potato” voice sounding like they havesomething too hot in their mouth. Treatment is ABCs, antibiotics, drainage (even a teaspoon worth of fluid).* In general, with cervical lymphadenopathy in children think about infections. TB, atypical mycoplasma, group Abeta hemolytic strep, viruses, infected branchial cleft cyst. After all that, then think about neoplasms.* DDx includes branchial cleft cyst, cystic hygroma, thyroglossal duct cyst.* Indications for tonsillectomy include persistent oral obstruction, recurrent peritonsillar abscesses, recurrentcervical adenitis, suspected tonsillar tumor.* Indications for adenoidectomy include persistent nasal obstruction and mouth bleeding, snoring and snorting, nasalspeech, repeated or chronic otitis media.* Indications for tonsillectomy and adenoidectomy (T & A) include cor pulmonale from persistent hypoxia, sleepapnea, recurrent aspiration pneumonias.* Invalid reasons for T & A include many colds, recurrent strep less than 7 infections a year for one year, less than 5infections per year for two years, less than 3 infections per year for three years, parents want tonsils/adenoids out.--------------------------------------------------------------------------------------------------------------------------------------------Respiratory: Foreign Body Aspiration & Ingestion* Toddler presents to the ED after choking on some coins. Child’s mother believes the child swallowed a quarter.Exam shows drooling and moderate respiratory distress. There are decreased breath sounds on the right withintercostal contractions. This is foreign body aspiration.* Best method to diagnose foreign body aspiration is bronchoscopy.* Right main-stem is most common location of foreign body.* Most commonly aspirated foreign body is a peanut. Most commonly ingested foreign body is a coin.* Aspirated foreign body is a sudden event, usually a witness event. Children < 4yo are at higher risk due to smallertrachea and curiosity (putting things in their mouth).* Should avoid giving children peanuts until 5yo. Avoid grapes, small hard candies, etc.* Exam may show respiratory problems, wheezing, decreased unilateral breath sounds. Stridor if in larynx.* Larynx most common site of foreign body if < 1yo, trachea and bronchi are most common if > 1yo.* Non-obstructing foreign bodies are relatively rare.* Inspiratory and expiratory films are helpful if the child can cooperate. You will look for signs of hyperinflation onthe side of the obstruction since air cannot get out.* Place child on the side you suspect has the foreign body (usually right) and do inspiratory and expiatory decubitusfilms. When you’re laying down and you breath out, the mediastinum should shift down a little. But, if there is aforeign body you will not get the shift because air (foreign body obstruction) is holding up the mediastinum.* You see an object in the center of an AP film. How can you determine if it is in the esophagus or trachea? Shouldyou do a lateral film? No. Test is “en fos”. If aspirated it will be turned, if swallowed it will be on face on AP film.
DO NOT DISTRIBUTE - 45 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Tracheal rings are cartilage on three sides, so easier for object to accommodate itself with an edge facing the backpart (soft part), on edge via AP film. Esophagus is soft all the way around and fits in better on face via AP film.* Why is the tracheal rings C-shaped, with a soft back? Because every time you swallow a food bolus it would beslamming into the trachea if the trachea were hard all the way around. This way it gives a little bit.* Treatment is remove foreign body. Complications include aspiration pneumonia.* Avoid peanuts, hot dogs, popcorn, other small foods that can get stuck.--------------------------------------------------------------------------------------------------------------------------------------------Respiratory: Croup (Laryngotracheobronchitis)* 12mo child is brought to your office because of a barky cough. Mother states that for the past three days the childhas developed a runny nose, fever, and cough. The symptoms are getting worse and the child seems to havedifficulty breathing when he coughs. The child sounds like a seal when he coughs.* Croup has a barky cough and possibly some inspiratory stridor.* Laryngotracheobronchitis is caused by viruses, most commonly parainfluenza virus. RSV is second.* History may include other family members having colds.* Age range is 3-4mo up to about 5-6years of age. Typically 6mo to 2yo.* Presents as child with cold for few days then develops cough with stridor. Or, child wakes up suddenly with barkycough and stridor (spasmodic croup, seen in allergic children).* Exam may show fever, barking cough, stridor, tracheal tugging, nasal flaring.* Most patients will exhibit the symptoms of stridor and slight dyspnea before they get better. Hypoxia is rare.* Best first test to order is a neck film (AP, PA) to distinguish epiglottitis from croup.* Croup has a steeple sign or pencil sign. Looks like a church steeple with narrowing of trachea superiorly.* Treatment of croup is home management, humidity, keep child calm, cool air.* Racemic epinephrine treatment aerosolized can help due to vasoconstrictor effects. Worry about rebound edema.* IM corticosteroids have been shown to help with croup.* Croup is self limiting. Antibiotics will not help.* Complications include middle ear and lung infections from virus, bacterial tracheitis (staph aureus).* DDx include diphtheria (serous discharge, gray/white pharyngeal membrane), epiglottitis.--------------------------------------------------------------------------------------------------------------------------------------------Respiratory: Epiglottitis* 2yo child presents to the ED with her parents because of high fever and difficulty swallowing. Parents state thechild was healthy but awoke with a fever of 104F, hoarse voice, and difficulty swallowing. On exam, patient issitting in tripod position (trying to straighten the airway for easier breathing), drooling, expiratory stridor, nasalflaring, and retractions of the suprasternal notch, supraclavicular and intercostal spaces.* Epiglottitis is inflammation of the epiglottis, causes airway obstruction, is an airway emergency.* Children with epiglottitis look sicker than croup children. Epiglottitis usually seen in older kids.* Epiglottitis has less stridor, less barky cough, more drooling, more air hunger, higher fever than croup.* Epiglottitis most commonly caused by H. influenzae type B, incidence greatly decreased due to immunization.* Usually nobody else ill in the household.* Look for sudden onset of high fever, dysphagia, drooling, muffled voice, and tripod positioning.* Exam shows respiratory distress, air hunger.* This is an emergency. Do not send this child off to x-ray with a technician or the parents. Do not struggle with thispatient to lay them down and look at their throat, because their airway can close while you are examining it.* When looking at a lateral film of the neck, the soft tissue structure should never be wider than the vertebral body.* To find epiglottis on lateral film, find the hyoid bone and look straight back. Thumbprint sign is when theinflamed epiglottis is so thick it looks like a thumbprint. Exam shows a cherry-red epiglottis.* Management, next best step, is secure an airway. Once the airway is secure, you are safe. Now you can giveantibiotics and treat the patient.* Diagnosis is made on clinical and physical findings, as well as visualization of the enlarged epiglottis as you areintubating the patient (done by experts in endotracheal intubation and tracheostomy). Airway is usually obtained inthe operating room under controlled conditions if possible.* Treatment for antibiotics is third generation cephalosporins. Keep the patient intubated for a couple of days, about48-72h after starting antibiotics.* A tongue blade should never be used to examine the pharynx of a patient with epiglottitis. They will getlaryngospasm and the airway will close and they can die.* DDx include croups, abscess, foreign body. Complications include death.--------------------------------------------------------------------------------------------------------------------------------------------
DO NOT DISTRIBUTE - 46 -Study Notes – Pediatrics James Lamberg 01Apr2010
Respiratory: Asthma* 6yo boy presents to his physician with end-expiratory wheezing scattered throughout the lung fields. He is noted tohave nasal flaring, tachypnea, and intercostal retractions. These symptoms are triggered by changes in the weather.There is a family history of asthma and atopic dermatitis. He has never been intubated or admitted to the pediatricICU. His last hospitalization for asthma was 6mo ago, he takes medicine only when he starts to wheeze.* Asthma is a reversible obstructive airway disease. Symptoms come and go. It affects both small and large airways.* If you think of your airways as a pipe organ cause there are different sizes, you get different pitches of wheezing.* Three components of asthma are bronchospasm (muscles constrict), mucus production, airway edema.* Obstruction caused during asthma attack increases airway resistance and decreases FEV1 and flow rates.* Lungs will be hyperinflated and premature airway closure (air trapping).* Take a deep breath and let half out, then take another deep breath and let half out, continuing this will not last longin a healthy person (try it for yourself). That’s what an asthmatic feels like due to air trapping.* Etiology is unknown, does run in families, can be related to the environment, lots of different factors involvedsuch as endocrine, immunologic, infectious.* Presentation varies for asthma. Acute attacks and insidious attacks.* Asthma has a tight “bronchospastic” cough. Wheezing is the hallmark of asthma.* Not everyone that has asthma wheezes and not everyone that wheezes has asthma.* Top three causes of chronic cough are asthma, post-nasal drip, and GERD.* Some people will have cough that is worse at night, or cough worse with exercise, or with cold weather, of afterbeing exposed to smoke, or when cutting grass, and so on.* Asthma has wheezing, dyspnea, and a prolonged expiratory phase (to make room for next breath).* See symptoms of respiratory distress, accessory muscle use, nasal flaring, intercostal retractions.* Can complain of abdominal pain due to use of these muscles for breathing, like doing lots of sit ups.* Liver and spleen may be palpable on physical exam because diaphragm pushes them down with hyperinflation.* Clubbing is not a hallmark sign of asthma, they oxygenate well be asthma attacks so no clubbing.* No single diagnostic test for asthma. Usually clinical diagnosis.* Peripheral smear can show eosinophilia (NAACP mnemonic). Sputum will have eosinophilia also.* Allergy skin testing can help. Exercise testing in older children can help. Response to bronchodilators helps.Pulmonary function testing (PFT) before and after bronchodilators is helpful, but not pathognomonic.* X-rays show hyperinflation, flattened diaphragm, ribs more horizontal and maybe further apart, atelectasisparticularly in the right middle lobe, peri-hilar inflammation. Also to rule out other parts of DDx.* No need to get CXR on patient every time they get an asthma exacerbation. For first time get a CXR to rule out amass. If fever, CXR to rule out pneumonia.* Blood gases are not done routinely on asthma patients. However, sicker patients get ABGs. Initially, patients arehyperventilation so PCO2 low-normal. As attack progresses, PCO2 rises. At late stage, pH drops because you’veused up all the buffers.* Best treatment is to avoid triggers if patient knows what they are. Daily management of the asthmatic varies.* Categories are acute, mild-intermittent, mild-persistent, moderate-persistent, severe-persistent.* Acute attack of asthma managed with bronchodilators (usually beta2 agonists), oxygen, and steroids.* Mild-intermittent asthma is symptoms occurring less than twice a week. Nocturnal symptoms (e.g. coughing).These patients do not need daily medications. Use short-acting inhaled beta2-agonists when symptoms.* Mild-persistent means symptoms occur more than twice a week, nocturnal symptoms more than twice a month.Need daily medications, such as cromolyn (mast cell stabilizer), nedocromil (stopped in 2008), or inhaled steroids.These days (2010), leukotriene antagonists (montelukast, zafirlukast, zileuton) have largely replaced cromolyn.Inhaled corticosteroids used as drug of choice for maintenance therapy. Beta2 agonist for break through.* Moderate-persistent is more frequent symptoms and wheezing between exacerbations. Use inhaled corticosteroids,long-acting beta2-agonists, and short-acting beta2-agonists for breakthrough.* Severe-persistent asthma is daily symptoms with more frequent hospitalizations. Use inhaled corticosteroids, long-acting beta2-agonists, and short-acting beta2-agonists for breakthrough. Leukotriene receptor antagonists daily formaintenance therapy as well.* Treatment of exercise-induced asthma is using beta2-agonists prior to exercise. Giving a beta2-agonist likealbuterol after an attack starts (trying to play catch-up) can be a dangerous game.* Complications of asthma include pneumothorax, respiratory distress, death.* Causes of wheezing include asthma, foreign body, Loeffler syndrome (pulmonary eosinophilia), cystic fibrosis,bronchiolitis.--------------------------------------------------------------------------------------------------------------------------------------------
DO NOT DISTRIBUTE - 47 -Study Notes – Pediatrics James Lamberg 01Apr2010
Respiratory: Bronchiolitis* 6mo presents with a three day history of URI, wheezy cough, and dyspnea. Exam shows temp of 39C, 60/min,nasal flaring, accessory muscle use, is air hungry, and O2 sat at 92%.* Bronchiolitis most commonly caused by respiratory syncytial virus (RSV). Usually seen under age of 2yo.* Generally upper respiratory symptoms prior to developing coughing and wheezing.* Bronchiolitis is not really a bronchoconstrictive disease, more inflammatory. Since these children under the age of2 have narrower airways, they can get into trouble with airway resistance and lower respiratory tract infections.* Causes include parainfluenza, mycoplasma, adenovirus, and second-hand smoke predisposes.* History of upper respiratory tract infections, developing fevers, rattling cough with respiratory distress.* Exam shows rapid breathing, wheezing and crackles possible, respiratory distress signs.* Little children with bronchiolitis can get apneic and cyanotic because they are getting tired.* X-rays usually reveal hyperinflation, peri-hilar atelectasis, viral pneumonitis or streaking, all not specific.* CBC usually normal. Best test to diagnose RSV bronchiolitis is a nasopharyngeal wash.* Quick fluorescence antibody of wash, if shows nothing then can culture.* Treatment is supportive for mild cases, humidified air (clean vaporizer daily), bronchodilator trial.* Some patients with bronchiolitis have a component of asthma, so those would respond to bronchodilators.* Some centers will give aerosolized epinephrine, can be helpful.* Corticosteroids are not indicated. Antibiotics are not necessary because it is viral.* Hospitalize if sick, like breathing very fast or lower than 95% sats for an infant. Hospitalize premature babies orbabies less than 3mo. Worst stage of disease is 3-5 days in, so if kid is pretty sick at day 2 you should observer in thehospital. Patients with chronic lung disease of congenital heart disease should be hospitalized due to greater risk.Hospitalize any baby with respiratory rate > 60/min or PO2 < 60 on room air.* Some children do well after getting suctioned out, e.g. nasal suctions.* Ribavirin is aerosolized, can be used for patients with impending respiratory failure, immunodeficiencies,bronchopulmonary dysplasia, neuromuscular diseases, congenital heart disease.* Mortality from RSV bronchiolitis is < 1%. Death can occur from prolonged apneic episodes or due to dehydration.Dehydration because they do not feed due to constant breathing and due to respiratory water loss.* At risk babies can receive monoclonal antibodies as prevention. RSV IV immunoglobulin not used anymore.Palivizumab used now, monoclonal antibody against RSV given IM once a month during peak season (winter,November to March). High financial cost for this treatment.* Patients with congenital heart disease go not get IV or IM monoclonal antibody against RSV.* DDx includes asthma.--------------------------------------------------------------------------------------------------------------------------------------------Respiratory: Cystic Fibrosis (CF)* 3yo Caucasian girl presents with rectal prolapse. She is in the less than 5th percentile for her weight and height.The parents also note that she has a foul-smelling, bulky stool each day that floats. They also state that the child hasdeveloped a repetitive cough over the last few months.* Exam can show nasal polyps.* Cystic fibrosis is autosomal recessive on chromosome 7.* CF is a multisystem disease, old name was pancreatic mucoviscidosis.* CF characterized by thick secretions anywhere (not just lungs), recurrent lung infections, airway obstruction,malabsorption, and failure to thrive.* It is the most common fatal inherited disease of white children. Seen in 1:3500 white live births. 1:17000 black.* Carrier rate is 1:20. Odds of couples finding each other is 1:200. Odds of an affected kid is 1:4 of that. Incidenceof live births runs anywhere from 1:1600 to 1:3500.* Gene codes for a protein, transmembrane conductance regulator. A defect in this protein leads to an abnormality inchloride transport. That produces abnormal thick mucus, in lungs, GI tract, sweat glands, GU system.* CF patients will have an elevated salt content in their sweat and other secretions. Have difficulty clearing mucussecretions which leads to chronic lung infections.* Meconium ileus or meconium plug in a newborn should be considered to have CF until proven otherwise.* Some babies will present with recurrent upper respiratory infections. Parents may say kid tastes salty when theykiss him. Some may present with GI symptoms like malabsorption of failure to thrive. Presentation varies.* When meconium plug is stuck in the bowel and does not move (ileus), patient gets micro-colon distally.* Rectal prolapse is very common in CF. Child may have decreased fat due to malabsorption and chronic disease.* Exam includes increased AP diameter, crackles, wheezing, meconium ileus, delayed sexual development.* CF patients can have malabsorption so chronic diarrhea with fatty stools. Problems absorbing fat-soluble vitamins
DO NOT DISTRIBUTE - 48 -Study Notes – Pediatrics James Lamberg 01Apr2010
(ADEK). Can have biliary tract problems rarely. Pancreas problems can lead to diabetes even though they have anexocrine pancreatic insufficiency.* 95% of CF boys will be sterile.* CF kids can get dehydrated easily when exercising, should drink much more fluids.* Best test for diagnosis is sweat chloride level. Can do genetic test but does not pick up every mutation.* Sweat chloride level > 60 is considered positive.* Treatment is intensive pulmonary toilet (bronchodilators, chest percussion, suctioning), aggressive management ofinfections (many get quickly colonized with pseudomonas or staph aureus in lungs), calories and vitaminsupplementation, pancreatic enzyme supplementation for absorption.* Complications include infections, pneumothorax (due to mucus plugging and coughing pressure), severe chroniclung disease (do get clubbing), respiratory tract colonization, pancreatic insufficiency, pancreatitis.* DDx is wide since it covers GI, pulmonary, endocrine, electrolyte. Should do lots of sweat test.--------------------------------------------------------------------------------------------------------------------------------------------Respiratory: Apnea* 5yo is brought to the physician because her mother states that the child snores and keeps the other family membersawake at night. She also stops breathing each night for approximately 20s and then wakes from sleep. Additionallythe mother states the child is not growing well and has poor school performance. Exam shows pleasant patient in noapparent distress. Findings include mouth breathing, hypo-nasal voice, and 4+ tonsils without exudates.* Apnea is the cessation of breathing for greater than 20 seconds. Obstructive sleep apnea is a combination ofprolonged partial upper airway obstruction and intermittent cessation of breathing.* Apnea can be central (from brain), obstructive (upper airway), or mixed (most common form).* Risk factors include large tonsils, large adenoids, trisomy 21 with large tongue, cleft palate, isolated macroglosia.* Usually patient with obstructive apnea will have snoring.* Child may have history of mouth breathing and hypo-nasal speech with large tonsils with airway obstruction.* Diagnosis is made by sleep study (polysomnography).* Treatment if enlarged tonsils/adenoids is a T&A surgery, remove the problem.* Complications include poor growth, cor pulmonale due to hypoxia, poor school performance due to increasedsleepiness, death.* DDx includes apnea of prematurity (apnea and associated bradycardia, treat with caffeine or theophylline),cyanotic breath holding (caused by prolonged expiration, can have cerebral anoxia, less than 3yo, hold breath due toanger, treatment is reassurance), pallid breath holding (after painful stimulus, turns pale/white, asystole, seizure,treatment is atropine because of asystole), obesity-hypoventilation (Pickwickian syndrome, seen with Prader-Willisyndrome, caused by airway obstruction, polycythemia, cor pulmonale, treatment is weight loss if possible).--------------------------------------------------------------------------------------------------------------------------------------------Sudden Infant Death Syndrome (SIDS)* Still not single cause determined for SIDS.* 2mo infant born without any complications via spontaneous vaginal delivery is brought to the ED by ambulancewith cardiopulmonary resuscitation in progress. According to the mother the patients was in his usual state of healthuntil 4am when she found the patient cyanotic and not breathing. The mother states that at midnight the infant wasfed 4oz of formula without difficulty. After feeding the child was placed to sleep in the crib. At 4am she returned tocheck on the infant and found the child unresponsive. She immediately called EMS and began CPR. The child waspronounced dead on survival in the Emergency Department.* Sudden infant death is an unexplainable death by history of after a thorough autopsy, in infants (< 1yo).* SIDS is the most common cause of death in infants 1mo to 12mo of age. < 1mo they die from prematurity,congenital malformations, etc.* No single etiology for SIDS, lots of investigations on the cause.* Peak incidence is around 2-3mo of age. Peak time of year is winter January to February. Peak time is aroundmidnight to 9am.* There is some relationship with sleep positioning. Put babies on their backs. “Back to sleep”. Exception would beobvious GE reflux issues. “Tummy time” is used during the day for development.* Risk factors are lack of prenatal care, prematurity, maternal smoking, lower socioeconomic status.* There is no diagnostic test because by definition a SIDS baby is already dead.* Acute life-threatening events or near-miss-SIDS can occur, may be a cause or may not be a cause. May go homeon a home apnea monitor, which does not prevent the problem only helps recognize it quicker.* Sleep positioning is the most important thing for prevention, place baby on their back.--------------------------------------------------------------------------------------------------------------------------------------------
DO NOT DISTRIBUTE - 49 -Study Notes – Pediatrics James Lamberg 01Apr2010
Respiratory: Pneumonia* 3yo child presents to the physician with a 104F temperature, tachypnea, and a wet cough. Patient’s sibling hassimilar symptoms. Child attends daycare but has no history of travel or pet exposure. Child has a decreased appetitebut is able to take fluids, has urine output, immunizations are up to date.* Pneumonia is inflammation of the parenchyma (pulmonary tissue). It is difficult to differentiate viral frombacterial at times.* Definitions are pneumonitis, lobar pneumonia, and bronchopneumonia depending on localization.* Risk factors are infectious agents (viruses, bacteria, fungi, parasites), aspiration.* Viral pneumonia is the most common cause of pneumonia in children.* Generally, children with viral pneumonia do not look as sick as children with bacterial pneumonia.* Bronchiolitis is considered a viral pneumonitis. Viral pneumonia presents with wheezing, cough, maybe stridor,some crackles possible, diffuse lung symptoms.* Bacterial pneumonia signs include cough, higher fevers, more shortness of breath, more respiratory symptoms, andmost localized lung findings like decreased breath sounds.* Remember percussion. With bacterial pneumonia there will be dullness to percussion over a localization.* Mycoplasma (“walking”) pneumonia will be a patient that doesn’t look so bad but x-ray looks terrible.* Chlamydia pneumonia has staccato cough and history of eye discharge, low grade or no fever.* Aspiration pneumonia with preceeding history of something happening.* CXR helpful. Difficult to get sputum sample in children. Transtracheal suction (past vocal cords) is best.* CXR with viral will show a diffuse bilateral streakiness. Bacterial will show consolidation, round pneumonia inchildren looks like coin lesion.* Mycoplasma CXR shows interstitial pattern in the lower lobes.* Chlamydia CXR shows hyperinflation or ground-glass appearance like RDS.* Aspiration CXR shows pneumonitis in locations of aspiration.* CBC helpful in differentiating viral from bacterial. Bacterial will have elevated WBC with predominantlyneutrophils. Viral will have elevated WBC with predominantly lymphocytes.* If you tap a pleural effusion, send that for cultures.* If mycoplasma suspected, do mycoplasma titers. Can do cold agglutinins but titers are better.* Treatment for viruses is symptomatic. For bacteria is antibiotics, most commonly caused by strep pneumonia.* If you suspect strep pneumonia as the cause of severe invasive disease (e.g. meningitis), start patient onvancomycin and ceftriaxone until sensitivities come back. Increasing numbers of strep pneumonia that areintermediately resistant to cephalosporins.* Treatment for chlamydia pneumonia is erythromycin.* Treatment for group B strep, E. coli, or listeria is ampicillin and third generation cephalosporin or ampicillin andaminoglycoside.* Treatment for strep pneumonia is penicillin, but start broader until sensitivities come back.* Treatment for mycoplasma is macrolides (erythromycin, azithromycin, clarithromycin).* If pneumatoceles (abscesses) seen on CXR, think staph aureus.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Cardiovascular with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Syndromes & Trisomies* Down syndrome: septal defects, patent ductus, aortic arch findings.* Hold-Oram syndrome: atrial and ventricular septal defects, arrhythmias.* Marfan syndrome: dilatation and aneurysms of aorta, aortic and mitral valve insufficiency, mitral valve prolapse.* Noonan syndrome: atrial septal defect, pulmonic stenosis.* Turner syndrome: coarctation of the aorta, bicuspid aortic valve.* Williams syndrome: supraventricular aortic stenosis, pulmonary artery stenosis.* Trisomy 13: patent ductus, septal defects, pulmonic and aortic stenosis (atresia).* Trisomy 18: ventricular septal defect, polyvalvular disease, coronary abnormalities,--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Overview* Children, particularly infants, do not present in heart failure like adults do. Can’t ask an infant how far they crawlbefore they get tired, or how many stuffed animals they have to put under their head when they sleep.* Infants in possible heart failure will have problems with feeding, get tired easily (because of feeding), can sweatduring feeding, tachypnea.
DO NOT DISTRIBUTE - 50 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Older children will have shortness of breath, can have dyspnea on exertion.* Orthopnea, edema, nocturnal dyspnea are uncommon in children. So not the same as with adults.* Physical exam will show tachycardia (know normal rates for kids).* Height and weight are always helpful. Severe congenital heart disease kids are usually small, may have FTT.* On exam, always palpate upper and lower extremity pulses. Should get upper and lower extremity BPs. A delay inpulses should make you suspicious for coarctation.* Exam may be helpful by demonstrating crackles on auscultation. This is indicative of pulmonary edema and left-sided heart failure. Hepatomegaly is indicative of right-sided heart failure.* With congenital heart disease, can get cyanosis and clubbing because of persistent chronic hypoxia.* Murmurs can be heard. Grade I murmur is difficult to hear, “the cardiologist murmur”. Grade II is faint but can beheard with background room noise. Grade III is louder than II but no associated thrill, may be heard when baby iscrying for example. Grade IV-VI has an associated thrill, feels like a cat purring if you’ve felt that. Grade V hasthrill that can be heard if stethoscope is touching chest wall at an angle. Grade VI is thrill heard with stethoscope justabove (not touching) the chest wall.* Diagnostic tests include chest x-rays (size of heart, lung field flow, rib notching, position of aorta and pulmonarytrunk), electrocardiogram (right axis deviation, left ventricular hypertrophy, right ventricular hypertrophy, bundlebranch blocks), MRI (double aortic arch), cardiac catheterization, angiography, exercise testing.* The test of choice for most of these congenital defects is an echocardiogram.* Differential clubbing, toe has clubbing but the hand does not, think longstanding patent ductus arteriosus.* If you see gross malformation of the upper extremities, think about associated cardiac defects (ASD, VSD).* In utero, oxygenation occurs at the placenta. Right side of the heart does a lot of pumping. Lungs are a high-resistance low-flow field. Communication between atria via foramen ovale and between pulmonary artery and aorticarch via ductus arteriosus.* When cord is clamped and baby takes a breath, we begin to convert to adult circulation. Foramen ovale starts toclose, ductus arteriosus starts to close as response to oxygen tension (takes a couple of days).* In certain heart defects, we can keep the ductus open to our advantage. Symptoms may not appear until the ductusbegins to close. These are ductal dependent lesions.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Innocent Murmurs* 5yo male is seen for routine physical examination. Parents voice no concerns. Weight and height are at 75%. Vitalsigns are normal. Physical exam is remarkable for a soft musical grade II/VI murmur best heard at the left lowersternal border.* Important notes here are that the kid made it to age 5, so probably not a bad murmur. Weight and height are fine,vital signs are normal. So probably an innocent murmur (e.g. functional murmur, flow murmur).* Pathophysiology is simply hearing flow through a normal heart, no holes, no valvular disease.* Most innocent murmurs heard between ages 2 and 7 years.* More than 30% of children may have an innocent murmur heard at some point in their lives.* Innocent murmurs usually heard on routine physical exam, maybe more likely when there is increased cardiacoutput such as with fever, infection, nervous.* Rarely can you say always or never in medicine. But, an innocent murmur is never in diastole. There arepathologic murmurs in systole. Any diastolic murmur is pathologic.* Innocent murmurs are not greater than II/VI grade.* Typical sound is soft vibratory “musical” murmur. Heard best at left lower to mid-sternal border.* What is the next step? Answer is reassurance. Do not do an echo or any other tests. Reassure parents.* DDx includes pulmonary flow murmur (form of innocent flow murmur, higher pitched, blowing, heard in earlysystole, heard at left parasternal border), venous hum (heard in neck or anterior chest, systolic and diastolic, goesaway when you compress a jugular vein).--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Congenital Heart Disease* Congenital heart disease occurs in about 0.5-0.8 per 100 live births. Lesions occur early on about 15-80 days ofgestation. Diagnosis is usually made early on in life. Over half of patients diagnosed by 1mo of age.* Murmurs may not be heard initially. Murmurs are only heard when there is flow through a defect. The only timethere is flow through a defect is if there is a different in pressures. When babies are born, their pulmonary vascularresistance tends to be high still. So you may not hear a murmur. When the resistance drops so that flow changes,then you’ll heard murmurs.* So it isn’t that an ASD was missed until 3-4mo of age or that the baby developed the ASD at that point. The baby
DO NOT DISTRIBUTE - 51 -Study Notes – Pediatrics James Lamberg 01Apr2010
was born with the defect but it was not heard until 3-4mo because that is when the pressures changed enough for theflow to be heard across the defect.* 30% of patients with congenital heart disease have other anatomical abnormalities (e.g. limbs, TE fistula).* Congenital heart defects are most commonly idiopathic. Other causes include congenital rubella, fetal alcoholsyndrome, maternal lithium use, Noonan syndrome, Down syndrome, and so on.* Murmurs are split into stenotic and shunting. Stenotic divided into aortic stenosis, pulmonic stenosis, coarctationof the aorta. Shunting divided into right-to-left (cyanotic), left-to-right (acyanotic), mixing-lesions.* Cyanotic-lesions are the 5Ts and a P: Tricuspid atresia, Tetralogy of Fallot, Transposition of the great vessels,Truncus arteriosus (mixing lesion), Total anomalous pulmonary venous return (maybe), Pulmonic stenosis.* For cyanotic heart disease, think the 5 Ts and 1 P. Could toss in hypoplastic left heart.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Ventricular Septal Defect (VSD)* 3mo child presents with poor feeding, poor weight gain, and tachypnea. Physical exam reveals a harsh pansystolic3/6 murmur at the left lower sternal border. Hepatomegaly is found.* Pansystolic implies you will not hear S1 and S2 well. Sounds like grind pause grind pause grind pause.* VSD is the most common congenital heart defect. One of the reasons that it is so common is because it is found inassociation with other heart defects.* VSD is a left-to-right shunt, acyanotic shunt. LV beats, pushing some blood out aorta and some into the RV.* Presentation depends on the size of the shunt. May not hear a lot of murmur initially when the pulmonary vascularresistance is high and there is not a lot of shunting. Large defects allow for a lot of shunting.* If you have persistent high flow from left-to-right, there is more flow to the lungs. The pulmonary vasculature willhypertrophy to help limit the amount of flow to the lungs. This will cause remodeling, eventually pulmonaryvascular resistance increase and pulmonary hypertension. When pulmonary hypertension gets high enough, theshunt will change right-to-left, turning the acyanotic disease to a cyanotic disease (Eisenmenger complex).* Small defects are usually asymptomatic.* VSD murmur is usually harsh holosystolic/pansystolic murmur.* Large defects can lead to heart failure, manifested by dyspnea, poor feeding, poor weight gain, tachypnea,sweating while they feed.* CXR for VSD will show an enlarged heart. If small defect, won’t see much.* Electrocardiogram will show left ventricular hypertrophy (LVH). Large defects will show biventricularhypertrophy (LVH + RVH).* Best test is echocardiogram. Echo will show defect(s).* Small defects will resolve on their own, usually in 1-2 years.* Treatment includes antibiotic prophylaxis for dental or surgical procedures to prevent endocarditis.* Medical management is to manage heart failure, diuretics, digitalis, eventually surgical closure +/- patch.* Eisenmenger syndrome generally cannot be corrected once there is right-to-left shunting. Definitive surgicaltreatment is a heart-lung transplant. 10 year post-transplant survival rate is around 25%.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Atrial Septal Defect (ASD)* In ASD, most blood goes from LA to LV but some gets into RA due to lower pressure.* ASD occurs anywhere along the atrial septum. Most common is ostium secundum defect. Most asymptomatic.* Can have some exercise intolerance as they get older.* Murmur is systolic, wide fixed-split of S2.* Normally you get an S2 split with a deep breath. When you breath in you get a decrease in intrathoracic pressureand a little bit of extra blood gets sucked from systemic venous circulation into the RA. So there is a little bit moreblood to the RV to pulmonary trunk, meaning it takes a little bit longer for the pulmonary valve to close.* With ASD, you hear the murmur in systole because there is increased pulmonary blood flow.* Fixed S2 in ASD occurs because there is always more blood returning to the RA (from the defect coming throughLA), more blood to RV, and more blood out pulmonary trunk thus later closure of the pulmonic valve.* Most patients do not have problems, some exercise intolerance later in life.* CXR can show enlarged RA and enlarged RV, depending on how big the shunt it.* ECG could show RA enlargement and RA conduction delay.* The best test is an echocardiogram.* Treatment is surgical correction. Can be done transvascular (femoral) or open heart with patch closure.* In general, ASDs do not close on their own.* Not a high flow lesion so no major risk of endocarditis, prophylaxis not really needed.
DO NOT DISTRIBUTE - 52 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Complications include heart failure (3rd decade of life), dysrhythmias, valvular insufficiency.* Most children are fixed by about 4-5 years of age so they do not have to miss school.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Patent Ductus Arteriosus (PDA)* In PDA, blood goes out aorta then through ductus back into the lungs, left-to-right shunt.* PDA more common in girls. Associated with congenital rubella. Common in premature infants.* Premature infants tend to respond better to medical management than term infants with PDA.* PDA could be helpful with other defects to help bypass flow. RV outflow tract obstruction would normally befatal, but a PDA would allow for mixing of blood.* Small PDAs usually do not cause problems. Large PDAs can cause problems similar to large VSD.* With PDA, can have wide pulse pressure. Instead of 120/80, could get 120/40.* Physical exam will show bounding pulses on the palms and soles of the foot in premies.* Sometimes there is a heave.* Typical murmur is a machinery or to-and-fro murmur. Heard in systole and diastole. Sometimes in infants you willonly hear a systolic ejection murmur.* CXR shows prominent pulmonary artery due to increased flow, increased pulmonary vascular markings due toincreased flow, heart size may be normal or slightly enlarged.* Best test is echocardiogram.* Some PDAs can close spontaneously in premature babies. They respond to indomethacin.* Best medication to close the PDA is indomethacin. Does not work as well with term babies.* With term babies, do surgical closure (ligation) with a rib incision for entry, so not open heart surgery.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Endocardial Cushion Defects* Endocardial cushion defect is a common AV canal, an ASD and VSD. Even through left-to-right, they becomecyanotic because of increased flow to the lungs, pulmonary hypertension, then Eisenmenger syndrome.* Endocardial cushions are where the valves come from and the septum. So ASD, VSD, and cleft mitral valve.* Endocardial cushion defects more common in Down syndrome, trisomy 21. Since there is a huge flow to thelungs, these patients will go into heart failure very easily (1-3mo of age). Now you’re stuck, you have to wait for thechild to be big enough so the surgery is feasible, but many times the kid can’t get big enough due to illness.* Patients will have heart failure early in infancy, hepatomegaly indicative of right sided failure, and FTT.* CXR shows increased pulmonary blood flow. Will have pulmonary hypertension so can develop Eisenmenger.* Exam can show a thrill. S2 will be widely split because of increased pulmonary blood flow. Diastolic murmur canoccur due to mitral valve insufficiency.* Best test is echocardiogram. CXR will show enlarged heart. ECG will show LAD, biventricular hypertrophy, RVconduction delay. Color flow Doppler with echo will show blood shunting at both levels, atrium and ventricles.* Treatment is medical management of heart failure until surgery. Surgery is patching ASD and VSD then fixing thecleft mitral valve if possible. Technically that is easy to do, the problem is post-operatively because now you haveno pop-off valve, right side of the heart is not use to pumping against high pressures, if high pulmonary hypertensionthe right side of the heart can fail.* Just because you hear a murmur doesn’t mean jump to the echo. Do a CXR and ECG first, then echo.* Fetal echocardiography is not a screening test. It is for diagnosis.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Coarctation Of The Aorta* Coarctation of the aorta is a constriction of the aorta that can occur at any point but most commonly (98%) occursjust below the origin of the left subclavian. Majority have some ductal-type tissue.* 9day old is brought to the ED because of difficulty feeding and having problems breathing. Physical exam revealsBP of 150/100 in arm, baby is tachypneic, retracting, with poor capillary refill.* Next test is lower limb pressures. Lower extremities show BP 50/30. Baby has coarctation until proven otherwise.* What is the next step in management? Give prostaglandin to keep the ductus open, The coarctation has ductaltissue in it and keeping it open will help get forward flow to the rest of the body.* Coarctation more common in boys, increased incidence in Turner syndrome (with bicuspid aortic valve also).* Coarctation can be missed in the newborn because the ductus is still open during exam in the nursery. When theductus closes is when you get problems, which is why you re-open the ductus until you can fix it.* Patients can presents with heart failure, metabolic acidosis, and lower body hypoperfusion, hypotension in thelower extremities, hypertension in the upper extremities, differences in blood pressure between arms possible(probably coarctation around the left subclavian), may hear a murmur.
DO NOT DISTRIBUTE - 53 -Study Notes – Pediatrics James Lamberg 01Apr2010
* CXR findings depend on the age of the patient. Rib notching seen in older patients with smaller coarctation so theyhave time to develop collateral circulation (internal thoracics to intercostals).* Other cause of rib notching is Von Recklinghausen because of the neurofibromas along the intercostal nerves.* CXR will show cardiac enlargement in the infant with severe coarctation, increased pulmonary vascular markings,rib notching in older patients.* ECG shows RVH in infants, LVH seen later in childhood as you try to overcome the obstruction if mild.* Test of choice for the diagnosis is echocardiogram.* Treatment is prostaglandin in ductal dependent coarctation and then surgical correction.* Complications include hypertension because kidneys are not seeing blood, premature coronary artery disease,heart failure, encephalopathy, intracranial hemorrhage. Adults at higher risk for endocarditis.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Tetralogy Of Fallot (TOF)* 6mo infants is prone to episodes of restlessness, cyanosis, and gasping respirations. Symptoms resolve when he isplaced in the knee-chest position. Exam reveals an underweight infant with a harsh holosystolic murmur and a singleS2 heart sound.* TOF is pulmonary (infundibular) stenosis, over-riding aorta sitting over VSD, right ventricular hypertrophy.* Spasm of the infundibular area just below the pulmonic valve can lead to “tet spells.” Increased R-to-L shunting.* Pentology of Fallot is less common, add an ASD to pulmonary stenosis, VSD, over-riding aorta, RV hypertrophy.* Symptoms depend on the size of the VSD and the size of the RV outflow tract obstruction.* TOF is the most common cyanotic congenital heart disease.* TOF may not present with cyanosis in the first 24h of life. If a heart disease presents with cyanosis within the first24h of life, think of transposition of the great vessels.* Acyanotic TOF “pink tet” if there is enough pulmonary blood flow, so not as much shunting or RV outflow tractobstruction.* Most patients present with cyanosis, delayed growth and development, heart failure, hypoxia, can have dyspnea,have paroxysmal hyper-cyanotic attacks known as “hypoxic attacks” or “blue spells” or “tet spells.”* Tet spells are relieved by putting infant in the knee-chest position. Older children will squat down. This increasesthe systemic vascular resistance and thus decreases the amount of shunting that occurs.* Will see clubbing because of chronic hypoxia, will hear loud harsh systolic ejection murmur.* S2 will be single because the pulmonic stenosis prevents closure so you only hear the aortic valve closing.* CXR will have a “boot shaped heart” (cor en sabot), decreased pulmonary blood flow will result in less fluid in thepulmonary vasculature so the lungs will be very radiolucent.* ECG will show RVH and right axis deviation (RAD).* Test of choice is echocardiogram for diagnosis.* Medical management if severe right-sided lesion keep ductus open for a little while (prostaglandin).* Surgical repair of the defects is the definitive treatment.* Blue spells are treated with beta blockade, sedation, oxygen, knee-chest position, and avoiding acidosis. Keepthese kids properly hydrated. Since chronically hypoxic, tend to have high hematocrit levels.* Complications include cerebral thrombosis because of the polycythemia due to chronic hypoxia (usually less than2yo), brain abscesses, bacterial endocarditis.--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Transposition Of The Great Vessels* Blood from systemic circulation comes into the RA to RV then out the aorta back out to the body. Meanwhile,blood from the lungs goes into the LA to LV then out the pulmonary trunk and back to the lungs. So you get twoseparate circulations, which is incompatible with life. To save this, there has to be a mixing communication, eitherthrough ductus, ASD, or VSD.* Transposition of the great vessels is the most common cyanotic heart disease seen in first 24h of life.* What is the next step in management? Answer is prostaglandin.* Transposition more common in infants of diabetic mothers and in boys.* Symptoms are cyanosis in first 24h of life and rapid onset heart failure. May or may not hear a murmur.* CXR shows “egg on a string”, egg shaped heart.* Definitive test is echocardiogram for diagnosis.* Keep kid on prostaglandin until you figure out what is going on.* Treatment is surgical repair of great vessels.* Surgical repair is arterial switch procedure, Senning of Mustard procedure if at atrial level, Rastelli for ventricular.--------------------------------------------------------------------------------------------------------------------------------------------
DO NOT DISTRIBUTE - 54 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 55 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 56 -Study Notes – Pediatrics James Lamberg 01Apr2010
--------------------------------------------------------------------------------------------------------------------------------------------Cardiovascular: Hypertension* 5yo girl is noted to have blood pressure above the 95% on routine physical exam. The rest of the physical exam isunremarkable. Her blood pressure remains elevated on repeat measurements over the next few weeks. Historyincludes treated urinary tract infection a year ago. CBC normal. UA normal. BUN 24, Creatinine 1.8.* Hypertension in older children (adolescents) is similar to hypertension in adults, essential hypertension.* Hypertension in a young child always has to be worked up.* BP needs to be repeated to confirm hypertension.* In children, a majority of hypertension is renal in relation.* Systemic hypertension is defined as BP above 95% for age on repeated measurements over a 6-week period.* Hypertension can be primary (essential) or secondary. Can be hereditary, salt intake, diet, obesity.* 75-80% of hypertension in children is caused by renal disease.* Look for prior UTI, hydronephrosis, premie with umbilical artery catheter causing thrombosis.* Hypertension usually does not cause symptoms and is usually found on routine physical exam.* DDx include coarctation so take pressures on all extremities.* All children with secondary hypertension should get a renal evaluation (start with ultrasound).* Echocardiography done to assess ventricular size and function.* Treatment is diet, exercise, limit salt intake, medications like diuretics, ACE-I, Ca-blockers, beta-blockers.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Gastrointestinal with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Abdominal Pain* Acute abdominal pain most commonly caused by gastroenteritis in children.* Look for age of child, male or female, quality of abdominal pain, localization.* Diagnostic tests vary by problem. Can order CBC, urinalysis, pregnancy test, serum amylase, CXR, abdominalfilms, CT scan of abdomen.* DDx < 2yo, trauma, intussusception, incarcerated hernias, volvulus, urinary tract infections, gastroenteritis.* DDx age 2-5, sickle cell anemia, lower lobe pneumonia, urinary tract infections, Meckel diverticulum,appendicitis (any child).* DDx adolescent females, Mittelschmerz, ectopic pregnancies, pelvic inflammatory disease.* Other DDx includes pancreatitis, Henoch-Schönlein purpura, mesenteric adenitis (e.g. from strep pharyngitis),lead poisoning, diabetic ketoacidosis, renal stones, cholecystitis.* Chronic abdominal pain is three or more episodes of abdominal pain severe enough to affect activities, occurringover a three month period.* Chronic abdominal pain occurs in 10-15% of children between the ages of 5-15. Causes include constipation,lactose intolerance, parasites, inflammatory bowel disease (IBD), peptic ulcer disease (H. pylori), pancreatitis,cholelithiasis, urinary tract infection, abdominal epilepsy (rare), porphyria (rare).* Abdominal epilepsy is the manifestation of the epileptic seizure.* Non-organic causes of recurrent abdominal pain in children include functional abdominal pain (irritable bowelsyndrome, IBS).* May ask a child how it feels and they’ll say oh it hurts. Ask where it hurts and they say all over.* Child has episodes of abdominal pain occurring every school-day morning, doesn’t wake them up at night, goesaway by noon, doesn’t affect play activity, doesn’t happen on weekends/holidays. This is school anxiety, maybe abully. Similar to the kid who doesn’t want to use the toilet at school and has constipation.* Stressors can produce abdominal pain, exams, school, relocating to another house/town, family member illness,sibling rivalry. The patient has real pain here that they feel in their abdomen.* Irritable bowel syndrome can present as recurrent abdominal pain, can produce pallor, nausea, vomiting, lethargy,diarrhea, constipation. 30% will have nocturnal enuresis, fears, and sleep disturbances. Parents may have sufferedfrom abdominal pains.* No one best test here. History is key. Physical exam may be normal.* If recurrent abdominal pain, reassure parents. Order CBC, sed rate, urinalysis.* Abdominal film may show a calcified mass (fecolith) near the appendix, ileus, obstruction.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Diarrhea* 13mo child has had a three day history of green watery stools. She has also been vomiting for one day. Examreveals a febrile, irritable baby, with dry mucous membranes, and sunken eyes.
DO NOT DISTRIBUTE - 57 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 58 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Constipation can occur secondary to defects in filling or emptying of the rectal vault. Other causes includeimperforate anus, Hirschsprung syndrome, infantile botulism (no honey in first year of life).* Constipation causes hard stools, sometimes liquid stools (looks like diarrhea) then encopresis.* Think about Hirschsprung anytime a neonate presents with constipation.* Diagnosis for Hirschsprung is by biopsy. Encopresis more commonly with functional constipation.* Functional constipation can occur with toilet training too early, child will toilet train on its own when ready.* Physical exam shows abdominal distension and poor weight gain in Hirschsprung. Anal tone normal inHirschsprung and functional constipation. Rectal exam likely no palpable stool in Hirschsprung. With functionalconstipation, you will palpate hard stool immediately in the rectal vault.* Monometry can be done for functional constipation. Biopsy can be done too but shouldn’t need to get to that point.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Vomiting* Celiac disease causes bloating due to malabsorption and diarrhea. Will have buttocks wasting due to FTT andchronic diarrhea.* Just vomiting in neonate think obstruction (volvulus, malrotation).* Infant differential for vomiting includes GE reflux, food allergies, milk protein intolerance, overfeeding, inbornerrors of metabolism (galactosemia, phenylketonuria).* Just vomiting in infants and up, think gastroenteritis. Then systemic infections, toxic ingestions, appendicitis,ulcers, pancreatitis.* Newborn presents with bilious vomiting with every feed. Abdominal film reveals a double bubble. Suspectduodenal atresia. Associated with trisomy 21.* Duodenal atresia presents early, usually first day of life, no abdominal distension. Treatment is surgical.* 4mo is admitted with episodes of apnea occurring 20-30mins after feeds. The mother states the baby has beenspitting up since birth. She is at the 5th percentile for weight. This is GE reflux. Most babies will spit up a little bit,but the problem is when the baby is not gaining weight.* With GE reflux, lower esophageal sphincter pressure is reduced or inappropriate relaxation of sphincter, or hiatalhernia, or delayed gastric emptying which can back things up.* GE reflux occurs and then there is a reflexive laryngospasm, causing apnea. Can aspirate (coughing, wheezing).* Patients with developmental delay and cerebral palsy tend to have more reflux.* Symptoms of GE reflux vary, can have spitting up, forceful vomiting “gushes out”, apnea as presenting sign,chronic cough and wheezing due to aspiration, poor weight gain is significant.* Sandifer syndrome is GE reflux with opisthotonus positioning (spasmodic torsional dystonia). The back arching isa reflex mechanism to relieve the pain and prevent the reflux.* Best way to diagnose GE reflux is a pH probe.* Treatment is anti-reflux measures (sitting up when feeding/sleeping), thickening the feeds, medications (e.g. H2blockers, prokinetics).* pH probe is placed in distal 1/3 of the esophagus and measures pH overnight, if pH drops too low for too long thenyou have your diagnosis.* Other studies for GE reflux include technetium “milk” scan or barium swallows. Best is pH probe though.* Anti-reflux measures include elevating the head of the bed, adding cereal to feeds to thicken, antacids, H2 receptorblockers, protein-pump inhibitors, pro-kintetics.* If medical management fails, surgical measures including Nissen fundoplication where a cuff is made around theesophagus to help prevent reflux.* Majority of patients will get better without treatment as they get older.* 4week old boy has non-bilious projectile vomiting. Exam is remarkable for a small mass palpated in the abdomen.* Pyloric stenosis is a gastric outlet obstruction, more common in males, more common in first born child, tends tobe genetic predisposition. If one child with pyloric stenosis, 5% chance of another. If mother had pyloric stenosis,25% of her having a child with pyloric stenosis.* Symptom is non-bilious projectile vomiting, usually around 3-4 weeks. Baby is hungry after vomiting. Vomitingis very forceful, gushes, shoots, like a hose, like exorcist.* May palpate abdominal “olive” mass on exam. May see/feel peristaltic wave on exam. May be jaundiced, mayhave weight loss, may be dehydrated.* Best test is abdominal ultrasound. Barium could be done but has to be sucked out.* Other lab findings include hypokalemic hypochloremic metabolic alkalosis due to repeated vomiting.* Pylorus will be elongated with a small outlet, showing a “string sign” with “mushroom cap” or “umbrella” asbarium is squirted out into duodenum.
DO NOT DISTRIBUTE - 59 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Ultrasound will show thickened wall, “donut sign”. Hole of donut is the opening, donut is muscular wall.* Treatment is surgical. First, rehydrate, correct electrolytes. Do pyloromyotomy and patient is eating again 8h later.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Bleeding* GI bleeding can be hematemesis (blood stained vomitus, upper GI), melena (soft black tarry stools, from any partof GI tract), hematochezia (bright red stool, lower GI, could be upper). Children have a quicker GI transit time andblood itself is a cathartic, so bright red blood in the stool could be from higher up, but generally is not.* Upper GI < 1yo think gastritis, swallowed maternal blood, peptic ulcer (duodenal and gastric), malrotation,volvulus. Upper GI > 1yo, think peptic ulcer, varices, gastritis.* For swallowed maternal blood, best test is Apt test. Apt test differentiates from fetal hemoglobin (belongs tonewborn) versus adult hemoglobin (swallowed maternal blood). Swallowed blood could be from delivery or duringnursing if mother has cracked/bleeding nipple.* Lower GI < 1yo think anal fissure (most common). Anal fissure could be from irritation due to diarrhea or hardstool that tore the wall. Other causes include intussusception, necrotizing enterocolitis, malrotation, volvulus.* Lower GI > 1yo think peptic polyp, intussusception, Meckel diverticulum, diarrhea, IBD, hemorrhoid.* 13yo girl complains of chronic cramping abdominal pain and diarrhea. She has noticed occasional blood in herstools. She has had fever off and on for three months and has complained of persistent right wrist pain. CBC showsanemia and elevated sed rate (ESR).--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Inflammatory Bowel Disease* Inflammatory bowel disease (IBD) includes Crohn and ulcerative colitis. Both are characterized by exacerbationsand remissions. Look for onset during adolescence. More common in Jewish and Caucasians, runs in families.* Crohn disease can have insidious onset and has more extra-intestinal manifestations than ulcerative colitis (UC).Can have fever of unknown origin, arthritis, skin manifestations, weight loss from chronic disease andmalabsorption, cramping abdominal pain, diarrhea +/- blood, perianal disease. Sed rate is usually elevated, plateletcount is usually high because it is an acute phase reactant, abdominal films can show small bowel obstruction, upperGI shows thicker folds and narrowing of GI tract (“string sign”).* Crohn has skip lesions affecting one segment then skipping to the next. May have fistula formation.* Best test to diagnose Crohn is colonoscopy (endoscopy) and biopsy.* Treatment is symptom relief including steroids, aminosalicylates (sulfasalazine, 5-aminosalicylate), chemotherapy(azathioprine), metronidazole for fistulas, cyclosporin, tacrolimus immune suppression, TNF-alpha, antibiotics canbe used if you are unable to tell if there is underlying infectious disease so treat empirically.* Treatment for Crohn can involve hyper-al (hyperalimentation) if they are unable to gain weight with PO feeding,helps rest the gut that is inflamed.* Surgical management is reserved for failure of medical management, fistula formation, intestinal obstruction, andgrowth failure.* Complications include remissions/exacerbations, GI obstruction, malabsorption, anemia of chronic disease.* Ulcerative colitis is limited to the colon, can be insidious or fulminant. There is a mild, moderate, severe form.* UC associated bloody diarrhea and mucus, abdominal pain, tenesmus (straining at stool).* Mild to moderate UC is the most common manifestation, about 6 stools/day, no fever, usually no anemia.* Moderate disease will present with some anemia due to blood loss in the stool.* Severe fulminant disease can cause bad enough anemia that they need transfusion. Can have high fevers,leukocytosis, tachycardia.* UC is a diagnosis of exclusion. Need symptoms for 3-4 weeks prior to entertaining the diagnosis of UC. Sed rate isnon-specific and not helpful.* Best test to diagnose UC is colonoscopy (endoscopy) and biopsy.* Treatment is symptom relief including steroids, aminosalicylates (sulfasalazine, 5-aminosalicylate).* Surgical treatment of UC is for failure of medical management. Surgery is total colectomy.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Intussusception* 15mo child is seen for cramping, colicky abdominal pain of 12h duration. He has had 2 episodes of vomiting andfever. Exam is remarkable for a lethargic child. Abdomen is tender to palpation. Leukocytosis is present. Duringexam, the patient passes a bloody stool with mucus.* In intussusception, part of the intestine (the intussusceptum) telescopes into the intussuscipiens, the distal part.Usually it is ileocolic, but can happen anywhere.* Intussusception usually idiopathic. Peak age is 6-24mo. Not usually older than 4 years of age. There has been
DO NOT DISTRIBUTE - 60 -Study Notes – Pediatrics James Lamberg 01Apr2010
some association with lymphoid hyperplasia (mesenteric lymphadenitis), Meckel diverticulum, lymphosarcoma,polyps, cystic fibrosis, Henoch-Schönlein purpura, preceding gastroenteritis.* If surgery is done for intussusception, the entire intestine should be scanned for lead points such as polyps.* Rotavirus vaccine was originally associated with intussusception. There was a high amount of monkey serum inthe oral vaccine, leading to mesenteric lymphadenitis and then intussusception.* History is acute onset of vomiting and colicky abdominal pain (pain comes and goes). May develop fever,lethargy, bloody stool with mucus (“current jelly stool”).* Exam may show sausage shaped mass in abdomen, the intussusception itself.* Patient can come in in shock, hypoperfusion, tachycardia, hypotension.* Best diagnostic test is barium enema, showing “coil spring sign”. It is also therapeutic by hydrostatic force,reducing the intussusception. If that does not work or it recurs, then call the surgeon.* DDx includes gastroenteritis, Meckel diverticulum (painless bleeding), Henoch-Schönlein purpura.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Meckel Diverticulum* 2yo boy presents with a one-week history of painless rectal bleeding. Physical exam is normal, rectal exam isunremarkable. Meckel diverticulum is the most frequent congenital anomaly of the GI tract.* Meckel diverticulum is a remnant of the omphalomesenteric (vitelline) duct.* Disease of 2s: 2% of infants, 2 years of age, 2 types of tissue (ectopic gastric mucosa), 2cm of size, 2ft fromiliocecal valve.* Presents as painless rectal bleeding, can cause intussusception, can mimic appendicitis if inflamed.* Best test for Meckel diverticulum is the technetium “Meckel” scan. Technetium is taken up by gastric tissue. Sincethis is ectopic gastric mucosa, it will be taken up in the stomach and in the lower abdomen.* Treatment is surgical removal.--------------------------------------------------------------------------------------------------------------------------------------------Gastrointestinal: Reye Syndrome* 8yo is seen in the ED with persistent vomiting and mental status changes. Exam shows he is combative and has aseizure, becomes apneic and requires intubation. Laboratory tests are remarkable for hypoglycemia and elevatedammonia. The patient had recently recovered from a viral URI.* This is not commonly seen anymore because we avoid aspirin in children who have viral infections. Anotherreason the incidence has dropped is because we are better at diagnosing other problems (e.g. mitochondrial, liverdiseases) that mimicked Reye syndrome.* Reye syndrome is an encephalopathy with fatty degeneration of the liver. Look for history of recent viral infection.May say the patient was recently taking aspirin, but not as common these days.* Typical scenario: child has viral illness, gets over it, a week later starts having mental status changes and vomiting.* Stage I Reye syndrome is lethargy, vomiting, sleepiness.* Stage II Reye syndrome is confusion, lethargy.* Stage III Reye syndrome is decorticate positioning.* Stage IV Reye syndrome is decerebrate positioning.* Stage V Reye syndrome is flaccid, with apnea but still reactive pupils.* DDx includes encephalitis so lab testing would include spinal tap, showing normal CSF.* Lab tests tend to show elevated ammonia, transaminases, CK, lactate dehydrogenase, plus hypoglycemia.* Prothrombin time may be elevated. Liver biopsy shows fatty infiltration.* Treatment is supportive, maintain airway, treat seizures, treat hypoglycemia.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatric Renal with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------Renal: Vesicoureteral Reflux* 2yo girl presents with urinary tract infection. She has had multiple UTIs since birth but no follow-up studies.Exam is remarkable for ill-appearing child who has a temperature of 40C and is vomiting.* Vesicoureteral reflux is abnormal backflow back up toward the kidney. Can be caused by congenital incompetenceof the ureterovesicular (UV) junction, can be familial, can be secondary to UTIs.* UTIs more common in males during 1st year of life. 10x difference between circumcised and uncircumcisedmales. Uncircumcised males have 1% incidence of UTI, circumcised males have 0.1% incidence of UTIs.* After first year of life, UTIs are much more common in females then males.* Incompetence of the UV junction means whenever you void the bladder pressure causes backflow up to thekidneys, even when it appears like you are urinating normally.
DO NOT DISTRIBUTE - 61 -Study Notes – Pediatrics James Lamberg 01Apr2010
* Vesicoureteral reflux is a cause of hypertension in young children. Most of the time, hypertension in children iscaused by a kidney issue.* Testing includes voiding cystourethrogram, kidney and bladder ultrasound.* Grade I reflux occurs without ureter dilatation.* Grade II reflux is into the upper collecting system without dilatation.* Grade III reflux is into the upper collecting system with dilatation of ureter and kidney.* Grade IV reflux is grossly dilated ureter with reflux into kidney.* Grade V reflux is tortuous dilation of the ureter with reflux into the kidney.* Grade I-II usually gets better as the child gets older, so prophylactic antibiotics are all that is needed.* Grade IV-V need surgical reimplantation of the ureters to prevent reflux. Treatment is aimed to prevent renalscaring and nephropathy associated with vesicoureteral reflux.--------------------------------------------------------------------------------------------------------------------------------------------Renal: Post-Streptococcal Glomerulonephritis* 10yo presents with cola-colored urine and edema of his lower extremities. Exam shows BP 185/100, no apparentdistress, lungs clear, regular rate and rhythm without murmurs/gallops/rubs. Medical history is remarkable for a sorethroat that was presumed viral by his physician two weeks ago.* How do you tell the difference between viral and strep throat? Only with a culture.* Treat strep throat to prevent peritonsillar abscess, retropharyngeal abscess, glomerulonephritis, rheumatic fever.* Glomerulonephritis can occur 1-2 weeks after a streptococcal infection of the throat or of the skin (impetigo), withor without antibiotic treatment.* Post-Streptococcal Glomerulonephritis Triad: hematuria, edema, hypertension.* Patients may complain of fever, malaise, abdominal pain. May have anemia and decreased C3.* Urinalysis will show RBC casts and may show protein.* Need to demonstrate past infection with group A beta-hemolytic strep via DNAase antigens.* Antinuclear antibodies may be done to rule out lupus. Renal biopsy is usually not necessary.* Best test if kid has hematuria, edema, hypertension is DNAase looking for previous infection with strep.* Treatment is antibiotics to prevent spreading of this kidney-attacking strain, but this does not change the diseaseprocess. Treat symptoms, decrease BP with antihypertensives, watch fluids.* 95% will have complete recovery. Some may develop renal failure.* DDx includes lupus, hemolytic uremic syndrome, glomerulopathies.--------------------------------------------------------------------------------------------------------------------------------------------Renal: Alport Syndrome* School nurse reports a boy because he failed his hearing test at school. The men in this patient’s family have ahistory of renal problems and a few of the uncles are deft. A urinalysis shows microscopic hematuria.* Alport syndrome is the most common type of hereditary nephritis.* Alport is X-linked dominant (Mom’s uncles).* Look for hematuria and proteinuria, even microscopic. Hearing loss is the key. Cataracts can occur as well.* Renal biopsy should be done, showing thickened basement membrane. The membrane will then atrophy as thedisease gets worse and will contain foam cells.* Treatment is supportive. They will develop end-stage renal failure later and will need dialysis and transplant.* Women tend to do better and have subclinical hearing loss. For males look for hearing loss and/or cataracts.--------------------------------------------------------------------------------------------------------------------------------------------Renal: Hemolytic Uremic Syndrome* 3yo child presents to the ED with a history of bloody diarrhea and decreased urination. The mother states that thesymptoms began 5 days ago after the family ate at a fast food restaurant. At that time the patient developed fever,vomiting, abdominal pain, and diarrhea (food poisoning). Exam shows ill-appearing kid, pale, lethargic.* Many things can cause hemolytic uremic syndrome (HUS), not just E. coli O157:H7.* E. coli is transmitted from undercooked hamburger meat or unpasteurized milk. Hamburger should be cookedmedium-well to well. Steak has E. coli on the surface, so when you put it on the grill it is hot enough to kill the E.coli. With the steak it is only on the surface. With hamburger, it is grinded all the way through.* HUS can be associated with contaminated swimming pools and apple cider.* Associations will include kidney problems, clotting problems, anemia.* Child usually < 4yo, may be recovering from viral gastroenteritis, maybe bloody diarrhea, maybe URI. One weekafter symptoms getting better, patient has oliguria, pale (anemia), weak, lethargic.* Will see a dehydrated patient on physical exam, could have hepatosplenomegaly. May have petechia because ofthe coagulopathy.
DO NOT DISTRIBUTE - 62 -Study Notes – Pediatrics James Lamberg 01Apr2010
DO NOT DISTRIBUTE - 63 -Study Notes – Pediatrics James Lamberg 01Apr2010
* If reflux is severe (Grade IV-V) they need surgical reimplantation of the ureters.--------------------------------------------------------------------------------------------------------------------------------------------Kaplan Videos (2001) – Pediatrics with Dr. Eduardo Pino, MD--------------------------------------------------------------------------------------------------------------------------------------------* Video 10 of 12, To Be Completed--------------------------------------------------------------------------------------------------------------------------------------------
DO NOT DISTRIBUTE - 64 - | https://de.scribd.com/document/38349821/Study-Notes-Pediatrics | CC-MAIN-2019-39 | refinedweb | 36,239 | 51.14 |
Error handling in NuxtJS
There are a lot of ways to handle errors in NuxtJS and they are all documented. Despite that, it's sometimes still difficult to determine what options are available in a specific scenario. This post is my attempt at creating an overview to use as a reference in the future.
Handling Errors
Error handling works differently in SSR (server-side rendering) and SPA (single page application) mode. Since the pages rehydrate as SPAs even in SSR mode, you always need to implement the SPA error handling. But you only need the SSR error handling if you're going to serve the application in SSR mode.
The three main sources of unhandled errors are the following:
- asynchronous data loading, (e.g. in the
asyncDatamethod)
- template rendering
- event handlers
In SSR mode, only the first two types of errors can happen. If they aren't handled, the application will fail and the static server error page will be shown:
You won't see it in development mode because the Youch error page will be shown instead:
You need to build the application in production mode and serve it to see the actual static error page:
npm run build npm run start
You can log the unhandled errors in server error middleware but you can't handle them there to prevent the static server error page from being shown. The server error middleware is defined as a hook in
nuxt.config.js:
export default { // ... hooks: { render: { errorMiddleware(app) { app.use((error, _req, _res, next) => { if (error) { console.log("Logged in errorMiddleware", error); } next(error); }); }, }, }, };
To avoid this error page in your application, you need to handle the errors beforehand. For the
asyncData method, this means that you must handle the asynchronous promise rejection in code. You can still call the Context
error method from code:
import { Vue, Component } from "vue-property-decorator"; import { Context } from "@nuxt/types"; @Component({ asyncData: (ctx: Context) => { // ... ctx.error({ message: "Error fetching data..." }); }, }) export default class AsyncErrorPage extends Vue { // ... }
This will show the NuxtJS error page that's served by the NuxtJS application:
Template rendering errors can be handled in the
errorCaptured lifecycle hook of any Vue.js component. The best central place to implement this hook in a NuxtJS project is in a layout (either the default one or a custom one):
import { Vue, Component } from "vue-property-decorator"; @Component({ errorCaptured(this: SafeLayout, err: Error, vm: Vue, info: string) { this.renderError = info === "render"; // indicates a template rendering error console.log("error handled in layout", err, vm, info); return false; // stops the error from propagating further }, }) export default class SafeLayout extends Vue { renderError = false; }
The hook will handle any rendering errors in pages that use this layout and stop the static error page from showing in SSR mode. It will also handle other types of unhandled errors. Because of that, I'm setting a flag when it's a render error. Only in this case, the page wasn't rendered (correctly). Therefore, I want to render an alternative page notifying the user about the error:
<template> <div> <Nuxt v- <div v-Render error occured</div> </div> </template>
The same lifecycle hook will also handle client-side rendering errors and unhandled synchronous errors in event handlers. However, if these errors aren't handled in the
errorCaptured lifecycle hook, they won't result in the static error page:
- Unhandled client-side rendering errors will show the NuxtJS error page.
- Unhandled synchronous errors in event handlers will be quietly logged by the browser in the console.
Both types of errors can be intercepted and logged in the Vue.js global error handler but they can't be stopped from propagating to prevent the error page from being shown:
import Vue from "vue"; Vue.config.errorHandler = (err: Error, vm: Vue, info: string) => { console.log("Logged in Vue global error handler", err, vm, info); };
Unhandled asynchronous errors can be intercepted and logged in the
onunhandledrejection browser event but also can't be stopped from further propagation:
window.onunhandledrejection = (event: PromiseRejectionEvent) => { console.log("Logged in window.onunhandledrejection", event); };
If they originate from the
asyncData methods, the NuxtJS error page will be shown. If they happened in an event handler, they will be quietly logged by the browser console.
In a NuxtJs application, both the Vue.js global error handler and the
onunhandledrejection event handler must be defined in a client-side plugin in a file placed in the
plugins folder. This file is then registered in the
nuxt.config.js file:
export default { // ... plugins: [{ src: "plugins/globalErrorHandler.ts", mode: "client" }], };
All of the options described above are shown in the following two diagrams:
Errors in event handlers can only happen on the client:
Other types of errors can happen on the client or the server:
Customizing Error Pages
Even if you intend to handle all errors in your application, there's always a risk that you'll miss something and still see one of the default error pages. Fortunately, you can customize both of them to make them more consistent with the rest of your application.
You can customize the NuxtJS error page as a component in
layouts/error.vue:
import { Vue, Component, Prop } from "vue-property-decorator"; import { NuxtError } from "@nuxt/types"; @Component export default class ErrorLayout extends Vue { @Prop({ type: Object, required: true }) readonly error!: NuxtError; }
You can use the error details passed to it in the
error prop to provide more information to the user:
<template> <div>Custom error page: {{ error.message }}</div> </template>
You can also replace the default static error page with your own. But unlike the NuxtJS error page, it's not a part of the NuxtJS application and is served as a simple static HTML page. ALthough it can include CSS and JavaScript, it might still be difficult to make it appear as a regular part of your application. The HTML file must be named
error.html and placed in the
app/views folder (you also need to create the folder yourself).
An example NuxtJS project with all the described error types and methods to handle them is available in my GitHub repository.
In a universal NuxtJS application, many different types of errors need to be handled. It's a good idea to create a plan for that early in the project. Usually, you'll want to handle all the errors explicitly yourself and only fall back to the default error pages when you fail to do that. To improve the user experience, it still makes sense to customize those error pages. It's also a good idea to intercept unhandled errors and log them so that you're aware of them and can fix them. | https://www.damirscorner.com/blog/posts/20200904-ErrorHandlingInNuxtjs.html | CC-MAIN-2021-10 | refinedweb | 1,112 | 52.9 |
From: Jonathan Wakely (cow_at_[hidden])
Date: 2005-02-28 08:18:38
On Mon, Feb 28, 2005 at 08:24:42AM +0000, Jonathan Wakely wrote:
> I might be wrong, but does 12.5/4 mean it is ill-formed to call delete
> on a pointer-to-base if base::~base is not virtual?
It's undefined ...
12.5 [class.free]
-5- When a delete-expression is executed, the selected deallocation
function shall be called with the address of the block of storage to
be reclaimed as its first argument and (if the two-parameter style
is used) the size of the block as its second argument.*
[Footnote: If the static type in the delete-expression is
different from the dynamic type and the destructor is not
virtual the size might be incorrect, but that case is already
undefined; see expr.delete. --- end foonote]
5.3.5 [expr.delete]
-3-.
In other words, you cannot guarantee substitutability if a base type
does not have a virtual dtor and derived objects will be created on the
free store and destroyed via pointers to base - however trivial the
derived destructor.
Therefore this program does invoke undefined behaviour:
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
using namespace boost::posix_time;
time_duration* t = new seconds(5);
delete t;
}
jon
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/2005/02/81075.php | CC-MAIN-2021-04 | refinedweb | 236 | 52.9 |
24 April 2009 17:23 [Source: ICIS news]
HOUSTON (ICIS news)--Honeywell lowered its outlook for 2009 due to indications that the global recession would last longer than it had previously anticipated, the US diversified technology firm said on Friday.
The company now forecasts yearly earnings of $2.85-3.20/share, down 35 cents from projections made last December.
“It pains me significantly to do this,” said CEO Dave Cote on a conference call. “I am embarrassed over the EPS outlook reduction, and it is not going to happen again.
“While the times are unprecedented, we’re disappointed in ourselves for not being even more conservative [with the previous outlook],” he added. “We’re adjusting with the assumption that the Q1 market reductions continue for the rest of the year.”
Honeywell’s specialty materials and chemicals segment recorded a 53% decline in first-quarter profit to $125m (€95m) as sales fell 25% on lower volumes and price declines.
Honeywell said the end markets of commercial aerospace and transportation were much tougher than anticipated in December, and any earnings improvement for the duration of 2009 would come almost exclusively from cost-cutting actions and not market improvement.
“We’re counting on no market changes, other than an inventory correction in autos that should be done where the production will finally start to match the anaemic sales level,” ?xml:namespace>
However, the decline in auto production could be offset by previous cost-cutting measures as well as a slight pickup in construction due to the US stimulus bill, he added.
While the overall picture remains gloomy,
“We don’t see it getting worse than the first quarter,” he said. “The rate of decline is clearly stabilising.”
For more on Honeywell | http://www.icis.com/Articles/2009/04/24/9211134/honeywell-lowers-2009-outlook-on-fears-of-longer-recession.html | CC-MAIN-2014-52 | refinedweb | 289 | 51.58 |
RicePad
Joined
Activity:![]
Hi all, I'm new to this community and also new to Ruby on Rails. I recently watched the Braintree integration screencast by Chris and I've been playing around with its Sand box integration.
I was able to make a successful check out with a hard coded amount i.e:
def checkout nonce = params[:payment_method_nonce] result = Braintree::Transaction.sale( ** :amount => "15.00",** :payment_method_nonce => nonce, :options => { :submit_for_settlement => true} ) end
Let's say I want a current_user to be able to purchase access to my portofolio for a specific "price" which has been stored in the database. Is there a way to set the amount by pulling it from an a object's attributes from the database i.e: "<[email protected]_item.price>" ?? I've tried multiple attempts and didn't have any luck. I feel like I'm not understanding how Braintree really works. | https://gorails.com/users/7976 | CC-MAIN-2021-21 | refinedweb | 147 | 67.76 |
#include "avfilter.h"
#include "libavutil/avassert.h"
Go to the source code of this file.
Definition at line 55 of file bufferqueue.h.
Referenced by ff_bufqueue_add(), and ff_bufqueue_peek().
FFBufQueue: simple AVFilterBufferRef.
Add a buffer to the queue.
If the queue is already full, then the current last buffer is dropped (and unrefed) with a warning before adding the new buffer.
Definition at line 63 of file bufferqueue.h.
Referenced by end_frame(), end_frame_over(), filter_samples(), process_frame(), and start_frame_main().
Unref and remove all buffers from the queue.
Definition at line 103 of file bufferqueue.h.
Get the first buffer from the queue and remove it.
Do not use on an empty queue.
Definition at line 90 of file bufferqueue.h.
Referenced by end_frame(), ff_bufqueue_discard_all(), flush_segment(), try_start_frame(), and try_start_next_frame().
Get a buffer from the queue without altering it.
Buffer with index 0 is the first buffer in the queue. Return NULL if the queue has not enough buffers.
Definition at line 79 of file bufferqueue.h.
Referenced by end_frame(), filter_samples(), request_frame(), try_start_frame(), and try_start_next_frame(). | http://ffmpeg.org/doxygen/1.0/bufferqueue_8h.html | CC-MAIN-2017-04 | refinedweb | 170 | 71.71 |
BBC micro:bit
Neopixels
Introduction
If you have used Neopixels with an Arduino, then you know what a joy it is to find out that they can be used with the micro:bit and MicroPython.
Neopixels is the name used by the electronics company Adafruit for a type of RGB LED that they package in different ways. Their guide to Neopixels can be found here. The products they make, sell and distribute are all really good. You can power around 8 LEDs directly from the micro:bit but, for more than that, you need to power them separately. They are meant to work at 5V but they play quite nicely with a few of the 3V3 microcontrollers like the micro:bit.
The Neopixels come in lots of different flavours, strips, individually, on circuit boards, rings. They all have a few things in common. They are chained together and have constant current drivers that means you supply a power and ground connection and one digital pin to control all of the LEDs.
For the programs on this page, I used the Neopixel Jewel and powered it directly from the micro:bit. It looks like this,
The Jewel is a nice choice because it's cheaper than the more impressive items but still pretty bright and well, pretty. Even one of these costs around £7. You need to do a good amount of programming to make sure you make the component earn its keep.
You can see 4 connections in the image. PWR should be connected to 3V on the micro:bit or to an external source 4-5V. GND should be connected to GND, naturally. The pin marked IN needs to be connected to one of the GPIO pins. Here I used pin 0.
Programming
This first program is good place to start with testing your connections and seeing some of the main features of the neopixel module.
from microbit import * import neopixel npix = neopixel.NeoPixel(pin0, 7) while True: for pix in range(0, len(npix)): npix[pix] = (255, 0, 0) npix.show() sleep(500) npix.clear() sleep(500)
The variable npix is set in the third line of code. When we instantiate the object, we select a pin and state the number of Neopixels. The pixels are indexed so that we can refer to them using a number in square brackets after our object variable npix. We change the colour of a pixel by supplying a value from 0-255 for each of the colours red, green and blue. To make the whole display update, we call the show() method.
The point of this program is to test the appearance of different colours and to see how the neopixels are numbered. The order in which they light up is their index, the first pixel being at index 0. This is the order in which they are connected electrically after being connected to the IN pin on the PCB. This information will be useful for using the Neopixels in your own projects.
The next program shows that you can find easier ways to work with setting the colours if you write a function. This one lights all of the LEDs a particular colour. 4 colours are defined at the start of the program. Read a bit more about Python and you can work out some better ways to store this kind of value.
from microbit import * import neopixel npix = neopixel.NeoPixel(pin0, 7) red = (255,0,0) green = (0,255,0) blue = (0,0,255) purple = (255,0,255) def LightAll(col): for pix in range(0, len(npix)): npix[pix] = col npix.show() return while True: LightAll(red) sleep(1000) LightAll(green) sleep(1000) LightAll(blue) sleep(1000) LightAll(purple) sleep(1000)
RGB LEDs, of any variety, are among my favourite components. Once you have made the electrical connections and learned the few statements you need for basic control of the LEDs, the rest is about programming and creativity. Without connecting any more components, you have hours of experimentation ahead to make the coolest light shows. The trick is to make more functions like these that light up the LEDs for you the way that you want.
This final example uses a loop to fade a colour in and out.
from microbit import * import neopixel npix = neopixel.NeoPixel(pin0, 7) def LightAll(col): for pix in range(0, len(npix)): npix[pix] = col npix.show() return while True: for i in range(0,255,5): LightAll((i,0,0)) sleep(20) for i in range(255,-1,-5): LightAll((i,0,0)) sleep(20)
Challenges
- Write a new function to light up all of the LEDs in the strip, one at a time, using the colour of your choice. Have a second argument for the function and make it so that you can specify the delay between each pixel taking on its new colour.
- On the Jewel and the Rings, the lights are in a circle. You can make it look like a pixel is going around the circle if you set a background colour for all of the pixels and then use a loop to quickly turn each pixel to another colour and then back again. Do this with each one in order (except the centre one on a Jewel) and it looks like the pixel is travelling around the circle.
- The Neopixels make great mood lighting. Experiment with different ways of varying the amount of red, green and blue over time and different ways of fading in and out. Try lighting the odd and even numbered pixels with different colours.
- Dancing pixels. It sounds good, whatever it means. You could combine this with some background music played through a buzzer or some hacked headphones.
- Make a function to generate a random colour for you.
- Use a potentiometer, button or accelerometer input to allow the user some control over the colour or pattern shown with the pixels.
- A nice challenging project is to work out how to fade smoothly from one colour to another. Imagine you have the colour (0,128,255) and you want to fade this into (255,255,128). It will need to take the same amount of time for each of the different colour channels to be changed to its new value. Since the amount of change required varies from one channel to the next, you need to work out different sized steps for the changes you make.
- Connect a microphone and you can make a sound-reactive circuit.
- Make some more pretty patterns with the lights. | http://www.multiwingspan.co.uk/micro.php?page=neopix | CC-MAIN-2019-09 | refinedweb | 1,093 | 80.11 |
There are so many exciting new technologies and features that have just been released or are soon-to-be-released: Visual Studio 2008, LINQ, MVC Framework, Entity Framework, AJAX, WCF, just to name a few. This is great news but there is a price to pay. There is more to read, more to learn and more to keep up with; but I believe it is worthwhile.
The first problem I ran into writing this article was “what to write about?” After hours of thinking, I decided to write a small application that covers many of these topics and then concisely discusses each one. So, don’t expect an in-depth analysis of all these topics. Instead, I will show you how powerful all these technologies are when combined together.
For my sample application, I will create a simple web-based feed/RSS reader. In this application, I will explore the following technologies:
I will also point out some of the new features of the Visual Studio 2008 throughout the article.
Let's start by creating a new web site
This will automatically create a website that has full support for Microsoft AJAX - but NOT the AJAX toolkit. To use the AJAX Toolkit, you need to download and install the version targeting the 3.5 .NET Framework.
Now, let's create the UI. The main components in the user interface are a tree view and a list view. The tree view will contain all your feeds and the list view will display the feed items for the selected feed.
A feed reader is no good, if you cannot add feeds to it. So, the first thing we need to do is add feeds. There is a text box and an add button at the top of the page. You simply type the feed URL and click the add button. Here is where the new and powerful Syndication API comes in play. You don’t have to parse XML, make HTTP calls and write messy code. All you have to do is write two lines of code. Yes, this is not a typo TWO lines of code.
Dim xmlReader = System.Xml.XmlReader.Create(feedUrl)
Dim feed = SyndicationFeed.Load(xmlReader)
The first line creates an XML reader using the feed URL supplied by the user. The second line retrieves the feed and feed items. Remember to import the System.ServiceModel.Syndication namespace to easily use the syndication API. That’s all we have to do. Now we have a strongly typed feed of type SyndicationFeed with a collection of SyndicationItem. Let’s display it.
System.ServiceModel.Syndication
SyndicationFeed
SyndicationItem
When the user selects a feed from the tree view, we need to display the feed items in the list view. You can of course use any data control you want like a DataList or Repeater. But since we are exploring new things, let's use the ListView control. There are two important steps you need to take to render a ListView:
LayoutTemplate
ItemTemplate
The LayoutTemplate must contain an element named “itemPlaceholder” that has the attribute runat=”server”. This – as the name implies – acts as a placeholder.
runat=”server”
<LayoutTemplate>
<table runat="server" id="table1" runat="server">
<tr runat="server" id="itemPlaceholder"> </tr>
</table>
</LayoutTemplate>
The ItemTemplate should contain an element of the same type as the itemPlaceholder defined in the layout template. In this case the placeholder is a TR element.
<ItemTemplate>
<tr runat="server">
<td id="Td1" runat="server">
<asp:Panel
<%#Eval("Title.Text") %>
[<a href='<%#Eval("Links(0).Uri.AbsoluteUri") %>'
target="_blank">link</a>]</asp:Panel>
<asp:Panel
<asp:Label</asp:Panel>
</td>
</tr>
</ItemTemplate>
The ListView will basically replace the itemPlaceholder item in the layout template with the code in the ItemTemplate. You could pretty much do the same thing in a DataList or Repeater, but the ListView control can let you edit, insert, delete, sort, page and group data without code. I would strongly recommend looking into this new and powerful control.
Now that all the UI elements are in place, let’s display the information. We simply loop through a list of SyndicationFeeds and add each feed title to the tree nodes list. When a user clicks on a node then we get that feed’s items and bind them to the ListView.
SyndicationFeeds
Private Sub BindListView(ByVal feed As SyndicationFeed)
Me.ListView1.DataSource = feed.Items
Me.ListView1.DataBind()
End Sub
To make the webpage more useable, I wrapped the entire page in an AJAX UpdatePanel and associated it with an UpdateProgress panel.
<asp:UpdateProgress
<ProgressTemplate>
<div class="progresspanel">
</div>
</ProgressTemplate>
</asp:UpdateProgress>
I applied a neat style to the progress panel that gives it the same look and feel as the “Loading” message you get on Gmail. It is a red rectangle with "Loading..." displayed in white at the top right hand corner of the page.
.progresspanel
{
background-color: RED;
color: White;
top: 1px;
color: white;
position: absolute;
right: 16px;
z-index: 999;
}
I also wanted to make the items in the ListView expand/collapse when the feed title is clicked. To do that, I used the CollapsiblePanelExtender from the AJAX Toolkit. Since the items in the ListView are dynamically generated, I had to create the extender in code. I did that in the ItemCreated event of the ListView. I assigned the item content panel to the TargetControlID property of the extender and the title panel to the ExpandControlID and CollapseControlID properties. I also set all items to default to the collapsed state.
CollapsiblePanelExtender
ItemCreated
TargetControlID
ExpandControlID
CollapseControlID
Protected Sub ListView1_ItemCreated(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles
ListView1.ItemCreated
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim lblTitle As WebControl = e.Item.FindControl("lblTitle")
Dim pnlContent As WebControl = e.Item.FindControl("pnlContent")
Dim cpx As New AjaxControlToolkit.CollapsiblePanelExtender()
cpx.ID = "cpx"
cpx.TargetControlID = pnlContent.UniqueID
cpx.CollapseControlID = lblTitle.UniqueID
cpx.ExpandControlID = lblTitle.UniqueID
cpx.Collapsed = True
e.Item.Controls.Add(cpx)
End If
End Sub
In order to make the first item expand, I added an event handler to the ListView PreRender event.
PreRender
Protected Sub ListView1_PreRender(ByVal sender As Object,
ByVal e As System.EventArgs) Handles ListView1.PreRender
If ListView1.Items.Count > 0 Then
Dim cpx As AjaxControlToolkit.CollapsiblePanelExtender =
ListView1.Items(0).FindControl("cpx")
If Not IsNothing(cpx) Then cpx.Collapsed = False
End If
End Sub
I also used a couple of TextWatermarkExtender to display a watermark on the text boxes.
TextWatermarkExtender
I love so many things about the new framework and Visual Studio but if I had to pick one feature/technology that I am very excited about, it would have to be LINQ – Language Integrated Query. This is a pretty big topic on its own and I am barely scratching the surface here.
I wanted to let the user search the title of the feed items for a specific text. Without LINQ, I would have to loop through the items and search the title. But now that I have LINQ, I can just write a simple query that looks very familiar to anyone who has ever written a SQL statement.
Dim matches = From item In CurrentFeed.Items _
Where item.Title.Text.ToUpper _
Like String.Format("*{0}*", txtFilter.Text.ToUpper)
The above statement, I am simply running a "select" statement against the feed items with a condition that it returns only items where the title contains the filter/search text. As you can see, this looks very similar to SQL but it is so much more. First of all the returned results are strongly typed as you can see from the tooltip below:
Second, you cannot really make syntax error here because the compiler wouldn’t let you. Compare that with SQL where you will not find out that your SQL statement had a problem until you compile and run the application. Third, you get full IntelliSense support in the IDE as you type your query – take a look at the series of screenshots below:
There are a few things worth mentioning in the LINQ query above that are new the framework.
As you can see in the IntelliSense "matches" is strongly typed based on the results of the query. This is the equivalent of:
Dim matches As IEnumerable(Of SyndicationItem)
Keep in mind that implicit types are not the same as Dim x as object. These are strongly typed objects, but instead of being explicitly declared as a specific type, the compiler and IDE deduce the type based on the assignment.
For example, these two statements are identical:
And
But these are not equivalent to:
LINQ is only possible because of the miracle of extension methods. Extensions methods are simply a way of "injecting" a static/shared method into a class without inheriting it. Let's say for example, that we wanted to write the query above as a Search method inside the class IEnumerable(Of SyndicationItem) and we want to do it easily. The first thing to do is create the extension method:
IEnumerable(Of SyndicationItem)
<Extension()> _
Function Search(ByVal Items As IEnumerable(Of SyndicationItem), _
ByVal SearchTerm As String) As IEnumerable(Of SyndicationItem)
Return From item In Items _
Where item.Title.Text.ToUpper _
Like String.Format("*{0}*", SearchTerm.ToUpper)
End Function
The steps to create an extension method are:
To use the extension method you simply call it like any other method on the object:
If this is not awesome then I don't know what is!!!
Although, I didn't go in depth in any specific technology or feature, I wanted to show how fast and easy you can create interesting applications using the .NET 3.5 framework and Visual Studio 2008 with very little code. We covered WCF's syndication API, ListView web control, AJAX, AJAX Toolkit, LINQ, extension methods and implicit types.
I would like to hear your opinions on these new technologies and on this article. I hope you find it mildly useful. Let me know what you think through comments, email or on my. | http://www.codeproject.com/script/Articles/View.aspx?aid=22494 | CC-MAIN-2015-22 | refinedweb | 1,669 | 64.3 |
This forecasts if we compare them to what is not: a forecast is non binary. A binary trading system will decide whether to go long, or short, but it does not get more granular than that. It will buy, or sell, some fixed size of position. The size of the position may vary according to various factors such as risk or account size (enumerated in this recent post) but importantly it won't depend on the level of forecast conviction.
In my two books on trading ('Systematic' and 'Leveraged' Trading) I confidently stated that non binary forecasts work: in other words that you should scale your positions according to the conviction of your forecasts, and doing so will improve your risk adjusted returns compared to using binary forecasts.
I did present some evidence for this in 'Leveraged Trading', but in this post I will go into a lot more detail of this finding, and explore some nuances.
This will be the first in a series of four broadly related posts. The second post will explore volatility forecasting, and whether it improving it can improve forecasting.
In the third post I explore the issue of whether it makes sense to fix your expected portfolio risk (a question that was prompted by a comment on a recent post I did on exogenous risk management). This is related to forecasting, because the use of forecasts imply that you should let your expected risk vary according to how strong your forecasts are. If forecasting works, then fixing your risk should make no sense.
The final post (as yet unwritten) will be about the efficient use of capital for small traders. If forecasts work, then we can use capital more efficiently by only taking positions in instruments with large forecasts. I explored this to some degree in a previous post where I used a (rather hacky) non linear scaling to exploit this property. I have recently had an idea for doing this in a fancier way that will allow very large portfolios with very limited capital. This might end up being more than one post... and may take a while to come out.
Let us begin.
<UPDATE 6th July: Added 'all instruments' plots without capping>
Forecasts and risk adjusted returns
Econometrics 101 says that if you want to see wether there is a relationship between two variables you should start off by doing some kind of scatter plot. Forecasts try and predict future risk adjusted returns, so we'll plot the return for the N days, divided by the daily volatility estimate for the return. We get N days by first estimating the average holding period of the forecast. On the x-axis we'll plot the forecast, scaled to an average absolute value of 10.
# pysystemtrade code:
from syscore.pdutils import turnover
import numpy as np
from systems.provided.futures_chapter15.basesystem import futures_system
system = futures_system()
def get_forecast_and_normalised_return(instrument, rule):
forecast = system.forecastScaleCap.get_scaled_forecast(instrument, rule)
# holding period
Ndays = int(np.ceil(get_avg_holding_period_for_rule(forecast)))
raw_price = system.data.get_raw_price(instrument)
## this is a daily vol, adjust for time period
returns_vol = system.rawdata.daily_returns_volatility(instrument)
scaled_returns_vol = returns_vol * (Ndays**.5)
raw_daily_price = raw_price.resample("1B").last().ffill()
## price Ndays in the future
future_raw_price = raw_daily_price.shift(-Ndays)
price_change = future_raw_price - raw_daily_price
# these normalised change will have E(standard deviation) 1
normalised_price_change = price_change / scaled_returns_vol.ffill()
pd_result = pd.concat([forecast, normalised_price_change], axis=1)
pd_result.columns = ['forecast', 'normalised_return']
pd_result = pd_result[:-Ndays]
return pd_result
def get_avg_holding_period_for_rule(forecast):
avg_annual_turnover = turnover(forecast, 10)
holding_period = 256 / avg_annual_turnover
return holding_periodLet's use the trading rule from chapter six of "Leveraged Trading", EWMAC 16,64*; and pick an instrument I don't know Eurodollar**.* That's a moving average crossover between two exponentially weighted moving averages, with a 16 day and a 64 day span respectively** Yes I've cherry picked this to make the initial results look nice and bring out some interesting points, but I will be doing this properly across my entire universe of futures later
instrument="EDOLLAR"
rule = "ewmac16_64"
pd_result = get_forecast_and_normalised_return(instrument, rule)
pd_result.plot.scatter('forecast', 'normalised_return')
That is quite pretty, but not especially informative. It's hard to tell whether the trading rule even works, i.e. is a positive forecast followed by a positive return over the next 17 business days (which happens to be the holding period for this rule), and vice versa? We can check that easily enough by seeing what the returns are like conditioned on the sign of the forecast:
pos_returns = pd_result[pd_result.forecast>0].normalised_return
neg_returns = pd_result[pd_result.forecast<0].normalised_return
print(pos_returns.mean())
print(neg_returns.mean())
print(stats.ttest_ind(pos_returns, neg_returns, axis=0, equal_var=True))
The returns, conditional on a positive forecast, are 0.21 versus 0.02 for a negative forecast. The t-test produces a T-statistic of 7.6, and the p-value is one of those numbers with e-14 at the end of it so basically zero. Incidentally there were more positive forecasts than negative by a ratio of ~2:1, as Eurodollar has generally gone up.
Is the response of normalised return linear or binary?
So far we have proven that the trading rule works, and that a binary trading rule would do just fine thanks very much. But I haven't yet checked whether taking a larger forecast would make more sense. I could do a regression, but that could produce the same result if the relationship was linear or if it was binary (and the point cloud above indicates that the R^2 is going to be pretty dire in any case).
Let's do the above analysis but in a slightly more complicated way:
from matplotlib import pyplot as plt
def plot_results_for_bin_size(size, pd_result):
bins = get_bins_for_size(size, pd_result)
results = calculate_results_for_bins(bins, pd_result)
avg_results = [x.mean() for x in results]
centre_bins = [np.mean([bins[idx], bins[idx - 1]]) for idx in range(len(bins))[1:]]
plt.plot(centre_bins, avg_results)
ans = print_t_stats(results)
return ans
def print_t_stats(results):
t_results = []
for idx in range(len(results))[1:]:
t_stat = stats.ttest_ind(results[idx], results[idx-1], axis=0, equal_var=True)
t_results.append(t_stat)
print(t_stat)
return t_resultsdef get_bins_for_size(size, pd_result):
positive_quantiles = quantile_in_range(size, pd_result, min=-0.001)
negative_quantiles = quantile_in_range(size, pd_result, max=0.001)
return negative_quantiles[:-1]+[0.0]+positive_quantiles[1:]
def quantile_in_range(size, pd_result, min=-9999, max=9999):
forecast = pd_result.forecast
signed_distribution = forecast[(forecast>min) & (forecast<max)]
quantile_ranges = get_quantile_ranges(size)
quantile_points = [signed_distribution.quantile(q) for q in quantile_ranges]
return quantile_points
def get_quantile_ranges(size):
quantile_ranges = np.arange(0,1.0000001,1.0/size)
return quantile_ranges
def calculate_results_for_bins(bins, pd_result):
results = []
for idx in range(len(bins))[1:]:
selected_results = pd_result[(pd_result.forecast>bins[idx-1]) & (pd_result.forecast < bins[idx])]
results.append(selected_results.normalised_return)
return results
Typing plot_results_for_bin_size(1, pd_result) will give the same results as before, plotted on the worlds dullest graph:
Ttest_indResult(statistic=7.614065523409865, pvalue=2.907839550447572e-14)
Now let's up the ante, and use a bin size of 2, which means plotting 4 'buckets'. This means we're looking at normalised returns, conditional on forecast values being in the following ranges: [-32.3,-6.6], [-6.6, 0], [0, 9.0], [9.0, 40.1]. These might seem random but as the code shows the positive and negative region have been split, and then split further into 2 'bins' with 50% of the data put in one sub-region and 50% in the next. Roughly speaking then 25% of the forecast values will fall in each bucket (although we know that is not the case because there are more positive than negative forecasts).
Each point on the plot shows the average return within a 'bucket' on the y-axis, with the x-axis point in the centre of the 'bucket'.
What crazy non-linear stuff is this? Negative forecasts sure are bad (although this is Eurodollar, and it normally goes up so not that bad), and statistically worse than any positive forecast. But a modestly positive forecast is about as good as a large positive forecast. We can see a little more detail with 12 buckets (bins=6):
It's clear that, ignoring the wiggling around which is just noise, that there is indeed a roughly linear and fairly monotonic positive relationship between forecast and subsequent risk adjusted return, until the final bin (which represents forecast values of over 17). The forecast line reverts at the extremes.. Neithier of these explain why the result is assymetric; but in fact it's just that positive trends are more common in Eurodollar.
Here's the plot for Gold for example:
There is clear reversion in both wings. And here's Wheat:
Here there is reversion for negative forecasts, but not for extreme positive forecasts.
Introducing forecast capping
There are different ways to deal with this problem. At one extreme we could fit some kind of cubic spline to the points in these graphs, and create a non linear response function for the forecast. That smacks of overfitting to me.
There are slightly less mad approaches, such as creating a fixed sine wave type function or a linear approximation thereof. This has very few parameters but still leads to weird behaviour: when a trend reverses you initially increase your position unless you introduce hysteresis into your trading system (i.e. you behave differently when your forecast has been decreasing than when it is increasing).
A much simpler approach is to do what I actually do: cap the forecasts at a value of -20,20 (which is exactly double my target absolute value of 10). This also makes sense from a risk control point of view.
There are some other reasons for doing this, discussed in both my books on trading.
We just need to change one line in the code:
forecast = system.forecastScaleCap.get_capped_forecast(instrument, rule)
And here is the revised plot for Eurodollar with a bin size of 2:
That's basically linear, ish. With bin size of 6:
There is still a little reversion in the wings, but it's more symmetric and ignoring the wiggling there is clearly a linear relationship here. I will leave the problem of whether you should behave differently in the extremes for another day.
Formally testing for non-binaryness
We'll focus on a bin size of 2 (i.e. a total of 4 buckets), which is adequate to see whether non binary forecasts make sense or not without having to look at a ton of numbers, many of which won't be significant (as the bucket size gets more granular, there is less data in each bucket, and so less significance).
We have the following possibilities drawn on the whiteboard. There are four points in each figure and thus 3 lines connecting them. From top to bottom:
- binary forecasts make sense
- linear forecasts make sense
- reverting forecasts make sense
In black are the results we'd get if the forecast worked (a positive relationship between normalised return and forecast). In red are the results if the forecast didn't work.
So we want a significantly positive slope for the first and third lines as in the middle black plot. But we'd also get that if we had a reverting incorrect forecast (bottom plot in red). So, I add an additional condition that a line drawn between the first and final points should also be positive. We don't test the slope of the second line. This means that we'd ignore a response with an overall positive slope, but which has a slight negative 'flat spot' in the middle line.
Note: the first and third T-test comparisions are (by construction) between buckets of exactly the same size, which is nice.
The lines will be positive if the T-test statisics are positive (since they're one sided tests), and they will be significantly positive if the T-statistics give p-values of less than 0.05.
Let's modify the code so it reports the difference between the first and final points as well:
def print_t_stats(results):
t_results = []
print("For each bin:")
for idx in range(len(results))[1:]:
t_stat = stats.ttest_ind(results[idx], results[idx-1], axis=0, equal_var=True)
t_results.append(t_stat)
print("%d %s " % (idx, str(t_stat))
print("Comparing final and first bins:")
t_stat = stats.ttest_ind(results[-1], results[0], axis=0, equal_var=True)
t_results.append(t_stat)
print(t_stat)
return t_results
Here is the output for Eurodollar
>> plot_results_for_bin_size(2, pd_result)
For each bin:
Ttest_indResult(statistic=4.225710114631642, pvalue=2.44857998636189e-05)
Ttest_indResult(statistic=1.814973164207728, pvalue=0.06959073262053131)
Ttest_indResult(statistic=1.9782202453688769, pvalue=0.04795295675153716)
Comparing final and first bins:
Ttest_indResult(statistic=7.36610843915252, pvalue=2.1225843317794611e-13)
The key numbers are in bold: we can see that with a p-value of 0.0479 the third line just passes the test. But the first line and the overall slope tests are passed easily.
Pooling data across instruments
Looking at one trading rule for one instrument is sort of pointless. We have quite a lot of price history for Eurodollar and we only just get statistical significance, for plenty of other instruments we wouldn't.
Earlier I openly admitted that I cherry picked Eurodollar; readers of Leveraged Trading will know that there are 8 futures markets in my dataset for which the test would definitely fail as this particular trading rule doesn't work (so we will be on one of the 'red line' plots).
I should probably have cherry picked a market with a clearer linear relationship, but I wanted to show you the funky reversion effect.
Checking each market is also going to result in an awful lot of plots! Instead I'm going to pool the results across instruments. Because the returns and forecasts are all risk adjusted to be in the same scale we can do this by simply stacking up dataframes. Note this will give a higher weight to instruments with more data.
instrument_list = system.data.get_instrument_list()
all_results = []
for instrument_code in instrument_list:
pd_result = get_forecast_and_normalised_return(instrument_code, rule)
all_results.append(pd_result)
all_results = pd.concat(all_results, axis=0)
plot_results_for_bin_size(6, all_results)
We didn't need to do this plot for the formal analysis, but I thought it would be instructive to show you that once the noise for individual instruments is taken away we basically have a linear relationship, with some flattening in the extremes for forecasts out of the range [-12,+12].
For the formal test we want to focus on the bin=2 case, with 4 points:
plot_results_for_bin_size(2, all_results)
1 Ttest_indResult(statistic=10.359086377726523, pvalue=3.909e-25)
2 Ttest_indResult(statistic=13.502334211993352, pvalue=1.617e-41)
3 Ttest_indResult(statistic=15.974961084038702, pvalue=2.156e-57)
Comparing final and first bins:
Ttest_indResult(statistic=35.73832257341082, pvalue=3.421-e278)
Remember: we want a significantly positive slope for the first and third lines: yes without question. We also want a significantly positive slope between the first and final bins, again no problems here.
For the overall slope, I didn't even know python could represent a p-value that small in floating point. Apparently we can get down to 1.79e-308!
Note that if the first and third T-tests statistics were zero, that would indicate a binary rule would make sense. If they were negative, it would indicate reversion. Finally, if the final comparision between the last and first bins was negative, then the trading rule wouldn't work
I think we can all agree that for this specific trading rule, a non binary forecast makes sense.
Testing all momentum rules
We can extend this to the other momentum rules in our armoury. For all of these I'm going to plot the bins =6 case with and without capping (because they're usually more fun to look at, and because <spolier alert> they show an interesting pattern in the tails which is more obvious without capping), and then analyse the bins=2 results with capping using the methodology above. Let's start at the faster end with ewmac2_8.
Notice that for this very fast trading rule (too expensive indeed to trade even for many futures), the behaviour in the tails is quite different: the slope definitely does not revert. We can see how people might be tempted to start fitting these response functions, but let's move on to the figures. We want all the T-statistics in bold to be positive and well above 2:
Ttest_indResult(statistic=3.62040542155758, pvalue=0.00029426)
Ttest_indResult(statistic=7.166027593239416, pvalue=7.761585-13)
Ttest_indResult(statistic=2.735993316153726, pvalue=0.006220)
Comparing final and first bins:
Ttest_indResult(statistic=12.883660014469108, pvalue=5.9049-38)
A resounding pass again. Here's ewmac4_8:
We have a pretty smooth linear picture again. I won't bore you with the T-tests, which are all above 6.0 and positive.
The t-statistics are now above 9. To keep things in order, and so you can see the pattern, here is the plot for ewmac16_64 (without capping, and with capping which we've already seen):
Can you see the pattern? Look at the tails. In the very fastest crossover we saw a linear relationship all the way out. Then for the next two plots as the rule slowed down it became more linear. Now we're seeing the tails start to flatten, with strong reversion at the extreme bullish end (although this goes away with capping).
We already know this rule passes easily, so let's move on.
Now there is a clear flat spot in both tails, so the pattern continues. Oh and the t-statistics are all well above 12.
One more to go:
It's a pass in case you haven't noticed. And there is some evidence that the flattening/reversion is continuing to become more pronounced on the negative end.
Anyway to summarise, all EWMAC rules have non binary responses.
What about carry?
Now let's turn to the carry trading rule. Again I will plot the bin=6 case, and then analyse the statistics based on bin=2.
That is pretty funky to say the least, and exploring it could easily occupy another post, but let's be consistent and stick to the methodology of analysing the bins=2 results:
Ttest_indResult(statistic=5.3244949302972255, pvalue=1.0147-07)
Ttest_indResult(statistic=36.3351610955016, pvalue=1.4856-287)
Ttest_indResult(statistic=14.78654199081023, pvalue=2.004e-49)
Comparing final and first bins:
Ttest_indResult(statistic=40.85442806158974, pvalue=0.0)
Another clear pass. The carry rule also has a non binary response.
Summary
I hope I've managed to convince you all that non binary is better: the stronger your forecast, the larger your position should be. Along the way we've uncovered some curious behaviour particularly for slower momentum rules where it looks like the forecast response is dampened or even reverts at more extreme levals. This suggests some opportunties for gratuitous overfitting of a non linear response function, or at the very least a selective reduction in the forecast cap from 20 to 12, but we'll return to that subject in the future.
Non binary means that we should change our expected risk according to the strength of our forecasts. In the next post I'll test whether this means that fixing our ex-ante risk is a bad thing.
A disadvantage of non binary trading is it needs more capital (as discussed here and in Leveraged Trading). At some point I'll explore how we can exploit the non binary effect to make best use of limited capital. | https://qoppac.blogspot.com/2020/07/ | CC-MAIN-2021-43 | refinedweb | 3,246 | 54.63 |
I would really like to add a form field "invite_code" to the user sign up form, but I don't know how to add the invite_code to the controller so that the application knows how to look for it?
The form in the sign up on the template would read:
<% form_for User.new do |f| %>
<span>Email:</span> <% f.email %><br>
<span>Name:</span> <% f.name %><br>
<span>Invite Code:</span> <% f.invite_code %><br>
<% end %>
before_save :invite_promo
def invite_promo
if @invite_code.present? && @invite_code == "special_person"
self.special_key = true
end
end
You need to define a virtual attribute
invite_code in
User model:
attr_accessor :invite_code
Your form should look as follows:
<%= form_for User.new do |f| %> <span>Email:</span> <%= f.email_field :email %><br> <span>Name:</span> <%= f.text_field :name %><br> <span>Invite Code:</span> <%= f.text_field :invite_code %><br> <% end %> | https://codedump.io/share/7uXMkALwKZLw/1/rails-use-a-form-field-to-set-something-on-the-user-registration-devise | CC-MAIN-2016-44 | refinedweb | 136 | 61.93 |
Talvola wrote:
>.
finally it seems i've traced something interesting, the folling
is the output of nohup.out file:
*** Starting request on thread Thread-9
341 2004-09-07 14:59:18 /products/
341 0.07 secs /products/
*** Done with request on thread Thread-9
*** Starting request on thread Thread-11
342 2004-09-07 15:00:41 /dealerarea/
342 0.02 secs /dealerarea/
*** Done with request on thread Thread-11 <--- ok until here
*** Starting request on thread Thread-10
343 2004-09-07 15:00:48 /news/
*** Starting request on thread Thread-12
344 2004-09-07 15:04:16 /
*** Starting request on thread Thread-13
345 2004-09-07 15:05:15 /news/
*** Starting request on thread Thread-9
346 2004-09-07 15:05:37 /it/index.py
346 0.04 secs /it/index.py
*** Done with requ./AppServer: line 9: 31074 Killed
note how Thread-10, 12 and 13 got stuck.
i'm running SUSE linux. i'm wondering if this can be
in some way related to my use of a NOT threadsafe mysqldb
module. i plan to move soon the app to a new linux server
(it's SUSE too) with mysqldb compiled againt threadsafe
mysqlclient library. to my understanding to check if
mysqldb is using a threadsafe client lib at the python
prompt one has to type:
import _mysql
print _mysql.thread_safe()
a zero value stands for no, otherwise yes.
also, i'm not experiencing any lock-up on my win2k box,
where i develop most of the code (threadsafe mysqldb module )..
cheers,
deelan.
View entire thread
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/webware/mailman/message/13907410/ | CC-MAIN-2016-44 | refinedweb | 307 | 73.88 |
Measuring performance of Java UUID.fromString() (or lack thereof)
aka “Why is UUID.fromString() so slow?”
Background
Similar to my recent adventure into evaluating performance of String.format() for simple String concatenation, I found another potentially meaningful case of widely used (and useful) JDK-provided functionality that seems to significantly under-perform: decoding of
java.util.UUID from a String:
UUID uuid = UUID.fromString(request.getParameter("uuid"));
This was found to be a hot spot on profiling done for a web service. Given that decoding should not really be that complicated compared to, say, generating UUIDs, this seemed odd.
(note: I am not the first developer to have noticed this, see f.ex this blog post from 2015)
Given that I once wrote (and still maintain) the popular java-uuid-generator library — which actually predates addition of
java.util.UUID in JDK 1.4 by a year or two :) — I thought I could see what is happening and whether I could find and evaluate more efficient alternatives.
And as usual, I’ll reproducible test(s) on microbenchmark suite.
#include <std-disclaimers.h>
Before proceeding further I think I need to add the usual standard disclaimers about microbenchmarking, results and interpretations: microbenchmarking itself is hard to get right and results (absolute and relative) are never absolute, and beyond being relative are highly contextual: something being 10x or 100x or 1000x slower may or may not be a problem in a given situation.
So I’ll get and show some numbers, talk about them; you may consider using that information if it makes sense for your particular usage.
Does JUG have it? How about Jackson?
Measuring the actual performance of
UUID.fromString() can be useful in estimating the relevance of measurements, but the other important part is to establish potential upper bound on faster implementation.
At first I thought that java-uuid-generator probably has equivalent code I could use. With a bit of digging I found it indeed has this method:
UUID uid = UUIDUtil.uuid(uuidString);
and we can see how its performance ranks compared to JDK implementation.
In addition, I know that Jackson (jackson-databind) also has a rather heavily optimized
UUIDDeserializer which could be useful — not exactly as-is, but we can easily copy-paste the logic. So let’s check out that too: Jackson codebase tends to be heavily optimized in many places and I recall having spent some time with UUID handling in particular.
I suspect there are many other implementations out there too that I could have benchmarked (there are 2 other widely used Java UUID generator libraries, both of which may well have a method for decoding) — if anyone wants to contribute an addition, feel free to submit a PR against and I can update the results!
But for now let’s see how these initial 3 choices perform.
Test Case & Results, initial
In this case our test set up is quite simple: we pre-construct a set of
java.util.UUIDs (32) using random-number based generation method, then convert them to
Strings: the test consists of rounds of constructing UUIDs back from the 32-element String array.
The test class is
ValidUUIDFromString (in package
com.cowtowncoder.microb.uuid) if you want to have a peek.
Running this test on my set up (Mac Mini (2018) 3.2Ghz 6-core Intel Core i7, JDK 1.8.0_272) gives results like this (note: I trimmed names of test cases to fit results better):
Benchmark Mode Cnt Score Error Units
UUIDFromString.m1_JDK thrpt 15 89175.229 ± 1899.754 ops/s
UUIDFromString.m2_JUG thrpt 15 490052.366 ± 35351.600 ops/s
UUIDFromString.m3_manual thrpt 15 1129569.239 ± 6054.405 ops/s
This gives us rough ratios of performance: using JDK implementation as the baseline, we see that:
- JDK approach can decode almost 3 million UUIDs per second (per core)
- java-uuid-generator can decode UUIDs from Strings about 5 times as fast (15 million / sec / core)
- copy-pasted code from Jackson can decode UUIDs from Strings over 10 times as fast (33 million / sec / core)
So: there is indeed a significant performance overhead with JDK (8) way of doing things. Yet even with it you need to call this method awful lot for it to necessarily matter.
Results with JDK 14
Given that JDK 8 is getting old by now, I decided to try the current stable LTS JDK, JDK 14. To my surprise there was quite a big positive difference — JDK 14 implementation is almost 4x as fast as in Java 8! While not quite as fast as alternatives, performance is rather close to
java-uuid-generator. Jackson’s optimized version is still faster but it’s only by a factor of 3 now.
Benchmark Mode Cnt Score Error Units
UUIDFromString.m1_JDK thrpt 15 358738.222 ± 7188.453 ops/s
UUIDFromString.m2_JUG thrpt 15 529761.948 ± 3866.240 ops/s
UUIDFromString.m3_manual thrpt 15 1181016.727 ± 4541.903 ops/s
Reasons for slowness of Java 8 / UUID.fromString()
One thing that interests me, as usual, is the reason for slowness of Java 8 implementation. I was thinking of profiling it a bit until realizing that someone else had already checked into it: “Micro-optimization for UUID.fromString()” has a good overview of where time is spent, so I won’t repeat it here.
And as to JDK 14, I assume it uses approach similar to what java-uuid-generator does. That approach is probably bit less code than Jackson’s, using simple looping: Jackson, on the other hand, gains more speed but removing looping after first sanity-checking validity of input format.
Next Steps
Given the difference between
java-uuid-generator, Jackson’s decoder, I am tempted to use code from latter to speed up
UUIDUtil.uuid() implementation in former — leading to the fascinating idea of releasing a new version of almost 20-years old library (although the oldest version at Maven Central is marked as being from 2005, the first version was actually made available in 2003 or so).
We’ll see — it seems like a nice idea if I find time to do that. | https://cowtowncoder.medium.com/measuring-performance-of-java-uuid-fromstring-or-lack-thereof-d16a910fa32a?responsesOpen=true&source=user_profile---------5------------------------------- | CC-MAIN-2022-05 | refinedweb | 1,020 | 55.44 |
Convert a Boxed Array to Stream in Java
In this tutorial, we will learn the logic behind converting boxed array to a stream in Java. We will also implement a Java program that demonstration the conversion.
What is Array?
An array is a container object that can store a fixed number of elements of a single datatype. The length of an array is declared when the array is created. After creation of an array, its length remains fixed. Each item in an array is called as element and each element is accessed by its index position ex. array[i]. There are multiple ways of creating an array, one way to create an array is with the new operator.
What is stream?
Java streams represent a data-flow medium through which the data flows. In Stream there are different functions that operate on the data in the stream. Streams they can be used in various programs that involve data-transition functions.
A stream is not a data structure that stores elements; instead, it facilitates elements from a source such as a data structure, an array, a data creator function, or an input/output channel, through a stream of computational operations. Various operations can be performed on the data that is present in stream.
Following is the Java code to convert a Boxed Array to Stream
In this program, we are going to convert the array of strings to a stream using the Arrays.stream() method in Java.
import java.util.*; import java.util.stream.*; public class array_to_stream { public static void main(String[] args) { String[] array = { "Code", "Speedy", "Technologies" }; Stream<String> output = Arrays.stream(array); output.forEach(str -> System.out.print(str + " ")); } }
Output:
Code Speedy Technologies
Explanation: In the above Java program, I have declared an array of string type that stores Code Speedy Technologies as three different elements. Then I have declared a Stream named output that will store the converted array elements. The ‘Arrays.stream(array)’ converts the array into stream where array is passed as an argument to the method. Then at the end, using a loop all the elements from the stream are displayed. | https://www.codespeedy.com/convert-a-boxed-array-to-stream-in-java/ | CC-MAIN-2020-45 | refinedweb | 356 | 63.7 |
Tim Peters wrote: > > I think you need a better example than that. Only smart-alec brown belts go around treating modules and functions like variables! Don't we usually cater to the beginning user, not the brown belt? It is easy to work around by renaming the module. <aside> The fact that Python late-binds function names can be annoying and dangerous outside of default arguments. Just last week I did this: import random def shuffle(seq): random.random( ) del random # so "import *" doesn't pollute the caller's namespace Shows how much I know about Python! I only think about functions "like that" when it is convenient. :) There may be an argument from reliability (and certainly from performance) in resolving certain names statically as part of the language specification. The REPL might have to be a special case... </aside> -- Paul Prescod - ISOGEN Consulting Engineer speaking for himself If all you want is sleep, go to bed. But if you want to dream, go to Barbados. - Timothy Findley, "Barbados: The Very Pineapple of Perfection" | https://mail.python.org/pipermail/python-list/2000-March/053324.html | CC-MAIN-2016-40 | refinedweb | 174 | 66.94 |
12 minute read
Notice a tyop typo? Please submit an issue or open a PR.
A common vulnerability that we are going to discuss is a buffer overflow.
A buffer overflow occurs when the amount of memory allocated for a piece of expected data is insufficient (too small) to hold the actual received data. As a result, the received data "runs over" into adjacent memory, often corrupting the values present there.
Specifically, stack buffer overflows are buffer overflows that exploit data in the call stack.
During program execution, a stack data structure, known as the call stack, is maintained. The call stack is made up of stack frames.
When a function is called, a stack frame is pushed onto the stack. When the function returns, the stack frame is popped off of the stack.
The stack frame contains the allocation of memory for the local variables defined by the function and the parameters passed into the function.
A function call involves a transfer of control from the calling function to the called function. Once the called function has completed its work, it needs to pass control back to the calling function. It does this by holding a reference to the return address, also present in the stack frame.
Stack buffer overflows can be exploited through normal system entry points that are called legitimately by non-malicious users of the system. By passing in carefully crafted data, however, an attacker can trigger a stack buffer overflow, and potentially gain control over the system's execution.
The following program - which roughly resembles a standard password checking program - is vulnerable.
#include <stdio.h> #include <strings.h> int main(int argc, char *argv[]) { int allow_login = 0; char pwdstr[12]; char targetpwd[12] = "MyPwd123"; gets(pwdstr); if(strncmp(pwdstr, targtpwd, 12) == 0) allow_login = 1; if(allow_login == 0) printf("Login request rejected"); else printf("Login request allowed"); }
We have allocated space for
int named
allow_login that is initially set to
0.
In addition, we have allocated space for a user-submitted password (
pwdstr) and a target password (
targetpwd).
We then ask the user for their password (
gets). Their response gets read into
pwdstr and if
pwdstr matches
targetpwd (via
strncmp), we set
allow_login to
1.
Finally, if
allow_login is
0, we print "Login request rejected". Otherwise, we print "Login request allowed"..
There are two things you can do with a stack: push and pop.
The stack grows when something is pushed onto it, and shrinks when something is popped off of it.
The current "top" of the stack is maintained by a stack pointer, which points to different memory locations as the stack grows and shrinks.
We can assume that the stack grows from high (numerically larger) addresses to low (numerically smaller) addresses.
This means that the stack pointer points to the highest memory address at the beginning of program execution, and decreases as frames are pushed onto the stack..
If the attacker guesses the correct password and types that as input to the program, login will be allowed.
If the attacker guesses the wrong password - which fits into the allocated buffer - there will be no overflow and login will be rejected.
These are the two basic outcomes for a naive attack: either the attacker guesses correctly and access is granted or the attacker guesses incorrectly and access is denied.
In order to understand how an attacker can use buffer overflow to gain control of this program, we first need to look at how the data associated with this program is laid out on the stack.
We know that the stack grows from higher memory addresses to lower memory address.
When we make the function call to
main, we push the arguments
argc (4 bytes) and
argv (4 bytes) onto the stack.
Assuming the top of the stack is located at memory address
addr, the stack pointer points to
addr - 8 after pushing these argument onto the stack.
Next, we have to push the return address (4 bytes) onto the stack. Every time we make a function call, we have to push the return address onto the stack so the program knows where to continue execution within the calling function once the called function completes.
After pushing the return address, the stack pointer points to
addr - 12.
Finally, we allocate space for
allowLogin (4 bytes),
pwdstr (12 bytes) and
targetpwd (12 bytes).
If
pwdstr is within 12 bytes, it will occupy only the memory allocated to it. If
pwdstr is longer than 12 bytes, it will exhaust the 12 bytes allocated to it, and will overflow into the space allocated for
allowLogin.
The reason
pwdstr overflows into
allowLogin and not
targetPwd is because occupation of memory occurs sequentially, from lower memory addresses to higher memory address. Note: this is the opposite of the direction in which the stack grows.
If the supplied value for
pwdstr is greater than 16 bytes,
pwdstr will also overwrite the return address.
As an attacker, we want to direct program control to some location where the attacker can craft some code.
If the attacker writes more than 16 bytes to
pwdstr, the buffer allocated to
pwdstr will overflow and will overwrite the return address.
If we know the address of the code that we want to execute, we can craft our input carefully, such that the existing return address gets overwritten with the address we want.
If we do this, what will happen?
Remember, the point of the return address is to give the function a location to transfer control to when it is done executing. If we overwrite that address, the function will "return" to the address we supply and begin executing instructions from that address..
The code that the attacker typically wants to craft is code that is going to launch a command shell. This type of code is called shellcode.
The execution of the shellcode creates a shell which allows the attacker to execute arbitrary commands.
You can write the shellcode in C, like this:
int main (int argc, char *argv[]) { char *sh; char *args[2]; sh = "/bin/sh"; args[0] = sh; args[1] = NULL; execve(sh, args, NULL); }
The "magic" here is execve, which replaces the currently running program with the invoked program - in this case, the shell at
/bin/sh.
While the code can be written in C, it must be supplied to the vulnerable program as compiled machine code, because it is going to be stored in memory as actual machine instructions that will be executed once control is transferred.
The vulnerable program is running with some set of privileges before transfer is controlled to the shellcode.
When control is transferred, what privileges will be used?
The shellcode will have the same privileges as the host program.
This can be a set of privileges associated with a certain user and/or group. Alternatively, if the host program is a system service, the shellcode may end up with root privileges, essentially being handed the "keys to the the kingdom".
This is the best case scenario for the attacker, and the worst case scenario for the host.
So far we have talked about stack buffer overflows. There are other variations of buffer overflows.
The first variation is called return-to-libc.
When we talked about shellcode, the goal was to overflow the return address to point to the location of our shellcode, but we don't need to return to code that we have explicitly written.
In return-to-libc, the return address will be modified to point to a standard library function. Of course, this assumes that you will be able to figure out the address of the library function.
If you return to the right kind of library function and you are able to set up the arguments for it on the stack, then you can execute any library function any parameters.
For example, if you point to the address of the
system library function, and pass something like
/bin/sh, you should be able to open a command shell.
The main idea with return-to-libc is that we have driven our exploit through instructions already present on the system, as opposed to supplying our own.
An overflow doesn't have to occur to memory associated with the stack. A heap overflow describes buffer overflows that occur in the heap.
One crucial difference between the heap and the stack is that the heap does not have a return address, so the traditional stack overflow / return-to-libc mechanism won't work.
What we have in the heap are function pointers, which can be overwritten to point to functions that we want to execute.
Heap overflows require more sophistication and more work than stack overflows.
So far, when we have talked about buffer overflow, we have talked about writing data; specially, inputing data into some part of memory and overflowing the memory that was allocated to us.
Overflows don't just have to be associated with writing data. For example, if a variable has 12 bytes, but we ask to read 100 bytes, the read will continue past the original 12 bytes and return data in subsequent memory locations.
The OpenSSL Heartbleed vulernability did just this. It read past an assumed boundary (due to insufficient bounds checking) and was exploited to steal some important information - like encryption keys - that resided in adjacent memory.
Naturally, we shouldn't write code with buffer overflow vulnerabilities, but if such code is out there deployed on systems, we need to find ways to defend against attacks that exploit these vulnerabilities.
For instance, choice of programming language is crucial. There are languages where buffer overflows are not possible.
These languages:
Languages that have these features are referred to as "safe" languages and include languages like Java and C++.
If we choose a "safe" language, buffer overflows become impossible due to the checks the language performs at runtime.
For example, instead of having to perform bounds checking explicitly, programmers can rest assured knowing that the language runtime will perform the check for them.
So, why don't we use these languages for everything?
One drawback for these languages is performance degradation. The extra runtime checks slow down the execution of your program.
When using "unsafe" languages, the programmer takes on the responsibility of preventing potential buffer overflow scenarios.
One way to do that is by checking all input to ensure that it conforms to expectations. Assume that all input is evil.
Another strategy to reduce the possibility of exploitation is to use safer functions that perform bounds checking for you. One such list of safe replacements for common library functions in C can be found here.
A third strategy is to use automated tools that analyze a program and flag any code that looks vulnerable.
These tools look for code patterns or unsafe functions and warn you which code fragments may be vulnerable for exploitation.
One issue with automated analysis tools is that they may have many false positives (flagging something that is not an issue), and may even have false negatives (not flagging something that is an issue). No tool should replace thoughtful programming.
There is no excuse for writing code that is insecure!
A number of source code analysis tools are available. These tools analyze the source code of your application, and can flag potentially unsafe constructs and/or function usage.
Companies will often incorporate the use of these tools into their software development lifecycle to ensure that all code headed for production is audited before being released.
If you are attempting to analyze code that you didn't write, you may not have the source code available, at which point source code analysis tools obviously won't be helpful.
One of the tricks that hackers use is to override the return address on the stack to point to some other code they want to execute.
During the execution of a function, however, there is no reason for the return address to be modified; that is, there is no reason a function should change where it returns during the middle of its execution.
As a result, if we can detect that the return address has been modified, we can show that a buffer overflow is being exploited and handle execution appropriately, likely with process termination.
How can we detect if the return address has been modified? We can use a stack canary, or a value that we write to an address just before the return address in a stack frame. If an overflow is exploited to overwrite the return address, the canary value will be overwritten with it.
All the runtime has to do, then, is to check if the canary value has changed when a function completes execution. If so, it can be sure that there is a problem.
What is nice about this approach is that the programmer doesn't have to do anything: the compiler inserts these checks. Of course, this means that the code may have to be recompiled with a compiler that has these features, a step which may come with its own issues.
There are also OS-/hardware-based solutions which can help to thwart the exploitation of buffer overflow vulnerabilities.
The first technique that many operating systems use is address space layout randomization (ASLR).
Remember that one key job of the attacker is to be able to understand/approximate how memory is laid out within the stack or, in the case of return-to-libc, within a process's address space.
ASLR randomizes how memory is laid out within a process to make it very hard for an attacker to predict, even roughly, where certain key data structures and/or libraries reside.
Many modern operating systems provide ASLR support.
In the classic stack buffer overflow attack, the attacker writes shellcode to the stack and then overwrites the return address to point to that shellcode, which is then executed.
There is no legitimate reason for programs to execute instructions that are stored on the stack. One way to block executing shellcode off the stack is to make the stack non-executable.
Many modern operating systems implement such executable-space protection..
OMSCS Notes is made with in NYC by Matt Schlenker. | https://www.omscs.io/information-security/software-security/ | CC-MAIN-2022-33 | refinedweb | 2,367 | 60.95 |
Java Array is like a container that can hold a fixed number of the same type of items, it can be primitive types as well as Objects.
Array Sorting in Java
Sometimes we need to sort array in java, we can use Arrays class to sort the array. Arrays is a utility class that provides a lot of useful methods to work with arrays in java.
Let’s look at an example to sort an array in Java.
Copypackage com.journaldev.sort; import java.util.Arrays; public class JavaArraySort { /** * This class shows how to sort an array in Java * @param args */ public static void main(String[] args) { int[] intArr = {1, 4, 2, 6, 3}; String[] strArr = {"E", "A", "U","O","I"}; //sort int array Arrays.sort(intArr); Arrays.sort(strArr); System.out.println(Arrays.toString(intArr)); System.out.println(Arrays.toString(strArr)); } }
Output of the above program is:
Copy[1, 2, 3, 4, 6] [A, E, I, O, U]
Array Sorting In Java
Important Points
- We can use
Arrays.sort(T[] tArr)only if the array type implements Comparable interface.
- There is another variant of
Arrays.sort(T[] tArr, Comparator c)that we can use to sort custom object array based on different fields.
- You can head over to java comparable and comparator to learn about sorting an array using Comparator.
Arrays.sort(T[] t)uses Dual-Pivot Quicksort algorithm with performance of O(n log(n)). The sorting is done in natural ascending order.
What are different ways to sort an array in Java?
There are many algorithms to sort an array. Some of the popular ones are:
- Bubble Sort
- Insertion Sort
- Heap Sort
- Merge Sort
- Quick Sort
We can write code to implement any of these algorithms to sort an array. However, it’s always recommended to use built-in Arrays.sort() function for error-free sorting and fast. | https://www.journaldev.com/784/sort-array-java | CC-MAIN-2019-13 | refinedweb | 311 | 64.61 |
Welcome to my Flask REST API tutorial, so the goal of this tutorial is to introduce you to writing APIs with Flask.
We would be building a simple personal diary API with these basic features.
- Add notes with a date and text
- Show more recent note first
- Attach images to your diary
WHAT YOU WILL LEARN FROM THIS TUTORIAL.
- Structuring a Flask Restful project for production.
- Basic CRUD operations(GET, POST, UPDATE, and DELETE).
- Authentication with JWT
- Object serialization with Marshmallow
- Working with file upload
- Adding Custom Error messages and handlers
- Logging
- Running Tests
- Deployment
This new post would be in series and we would begin with structuring our Flask Rest project for production.
Structuring a Flask Restful project for production.
Unlike most frameworks, Flask does not impose a specific organization. For this tutorial, we would structure our app like the image below so it scales pretty well.
So we are going to install the following dependencies for our diary API.
1. Flask: web microframework for Python
2. Flask-restful: extension for Flask that adds support for building APIs.
3. Flask-CORS: is a flask extension for handling Cross-Origin Resource Sharing (CORS) making cross-origin AJAX possible.
4. Flasgger: an extension that creates Swagger 2.0 API documentation for all your Flask views.
Let’s Build our Project
It’s a good practice for python projects to run on their own specified independent virtual environments.
1. Create our virtual environment and install our app dependencies.
From the terminal do the following (Mac and Linux Users)
mkdir recipe-api & cd diary_api python 3 -m venv env source env/bin/activate pip install -r requirements.txt
Window Users
py -m venv env .\env\Scripts\activate pip install -r requirements.txt
ALTERNATIVELY, if you use Pyenv like I do(a simple Python management tool that allows you to easily switch between multiple versions of Python. )
pyenv update //update pyenv pyenv install --list //To see available versions of python pyenv install -v 3.8.3 //install latest version of python pyenv virtualenv 3.8.3 env //select our python version and create // virtual environment pyenv local env //activate our environment pip install -r requirements.txt pyenv deactivate // remember to deactivate
2. Setting Up Configuration
Create a new folder, called api , create an __init__.py , app.py, and config.py file. Add the following code below to the config.py file
#api/config.py import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get("SECRET_KEY") SQLALCHEMY_TRACK_MODIFICATIONS = False , }
The Config is our base class that contains settings that are common to all configurations and it implements an empty init_app() method.
The SQLALCHEMY_DATABASE_URI variable is assigned different values under each of the three configurations. This enables the application to use a different database in each configuration. This is very important, as you don’t want a run of the unit tests to the database that you use for day-to-day development.
At the bottom of the config.py, you notice a dictionary (env_config), contains config for the various environment (development, testing, or development).
3. Define the application factory
Add the code below to the app.py file
#api/app.py from flask import Flask from flask_cors import CORS from flask_restful import Api from flasgger import Swagger from api.config import env_config api = Api() def create_app(config_name): #import our resource folder to avoid circular #dependency error import resources app = Flask(__name__) app.config.from_object(env_config[config_name]) api.init_app(app) CORS(app) Swagger(app) return app
The create_app() function is the application factory, which takes as an argument the name of a configuration to use for the application. The configuration settings stored in one of the classes defined in config.py can be imported directly into the application using the from_object()
method.
4. Define the application instance (the flask app)
Create a new file in the root folder called main.py
#main.py import os from api.app import create_app app = create_app(os.getenv("FLASK_ENV"))
5. Test and create our default resource
Create a new folder called resources, create the following files (__init__.py and default.py).
Now add the following to default.py file
from flask_restful import Resource from api.app import api class DefaultResource(Resource): """Handle default route.""" def get(self): """Get request for home page or response.""" return { "status": "success", "data": { "msg": "Welcome to our diary API" } } api.add_resource(DefaultResource, "/", endpoint="home")
Import the default module into resources/__init__.py to avoid circular dependency error.
#resources/__init__.py from . import default
Now run the following on the terminal to start our app.
export FLASK_APP=main.py export FLASK_DEBUG=1 export FLASK_ENV=development flask run
For Window users, run the following
set FLASK_APP=main.py set FLASK_DEBUG=1 set FLASK_ENV=development flask run
This following below will be displayed on your terminal, press your Ctrl key, and the to go to your browser.
:~/Desktop/blog_Notes/diary_app$ flask run * Serving Flask app "main.py" (lazy loading) * Environment: development * Debug mode: on * Running on (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 326-455-266 127.0.0.1 - - [09/Jul/2020 19:30:32] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [09/Jul/2020 19:31:12] "GET /apidocs/ HTTP/1.1" 200 -
Viola!
Our API is up and running.
Open a new tab on your browser and type our Swagger is up and running.
In my next post, we would create custom error handlers and handle exceptions in our Flask app.
Thanks for visiting my blog, here is a Github repo for the post, click here | https://oluchiorji.com/structuring-a-flask-restful-api-for-production/ | CC-MAIN-2022-21 | refinedweb | 934 | 51.04 |
This is a discussion on urgent help required. within the C++ Programming forums, part of the General Programming Boards category; We have been given a project where we have to make a c++ code generator through a give text file. ...
This is what i've come up with yet, and I know it is incorrect because if you change the parameters in the sample input, the output goes all wrong.
Code:#include <fstream.h> void main () { char CLASS[50]; ifstream fin; fin.open("sample_input.txt"); fin.getline(CLASS, 20, '\n'); ofstream fout; fout.open("code.txt"); fout<<"#include <iostream>"<<"\n"; fout<<"using namespace std;"<<"\n"; fout<<CLASS<<endl; fout<<"{"<<endl; fin.seekg(27); fin.getline(CLASS, 50, ')'); fout<<CLASS<<":"<<endl; fin.seekg(51); fin.getline(CLASS, 10, ')'); fout<<CLASS; fin.seekg(40); fin.getline(CLASS, 20, '('); fout<<CLASS<<";"<<endl; fin.seekg(51); fin.getline(CLASS, 20, ')'); fout<<CLASS; fin.seekg(60); fin.getline(CLASS, 10, '('); fout<<CLASS<<";"<<endl; fin.seekg(83); fin.getline(CLASS, 10, ')'); fout<<CLASS; fin.seekg(78); fin.getline(CLASS, 10, '('); fout<<CLASS<<";"<<endl; cout<<fin.tellg(); fin.close(); fout.close(); }
I love it! No longer are teachers simply teaching bad design techniques from the start; they are teaching people how to automatically produce code with bad design techniques.
GENIUS!
To the original poster, first write the program yourself from the template, then figure out the steps you took to get there, and finally, you need to automate those steps.
Out of curiosity, are you supposed to use memory allocation, or just ........ away all semblance of good design?
Soma
This project is much like an Code Generator for a UML Diagram; C++ is possible but not really the best Language to process text files.
Tim S. | http://cboard.cprogramming.com/cplusplus-programming/137373-urgent-help-required.html | CC-MAIN-2014-23 | refinedweb | 289 | 67.86 |
Iterator to iterate over all static lights in the engine. More...
#include <iengine/light.h>
Inheritance diagram for iLightIterator:
Detailed Description
Iterator to iterate over all static lights in the engine.
This iterator assumes there are no fundamental changes in the engine while it is being used. If changes to the engine happen the results are unpredictable.
Main creators of instances implementing this interface:
Main users of this interface:
- Application.
Definition at line 535 of file light.h.
Member Function Documentation
Get the sector for the last fetched light.
Return true if there are more elements.
Get light from iterator. Return 0 at end.
Restart iterator.
The documentation for this struct was generated from the following file:
Generated for Crystal Space 1.4.1 by doxygen 1.7.1 | http://www.crystalspace3d.org/docs/online/api-1.4/structiLightIterator.html | CC-MAIN-2013-48 | refinedweb | 129 | 52.66 |
RationalWiki:Saloon bar/Archive273
Contents
- 1 Talkpage editnotice: "please have specific criticisms"
- 2 Holocaust denial to cover?
- 3 Y'all gotta see this
- 4 My girlfriend just texted me
- 5 Blog: American Kabuki
- 6 Proposal: Re-purpose the Elections WIGO to Politics
- 7 Trump preemptive strike
- 8 Zero hour...
- 9 Brittany Pettibone & Lauren Southern
- 10 Trump: Should I laugh or be scared he is the President?
- 11 Appeal to identity
- 12 It's alive! IT'S ALIIIIVE!!!!! (Kind of.)
- 13 Nibiru redux
- 14 Thread for crazy stuff you come across
- 15 RationalWiki edits, graphed
- 16 Who else is joining the March for science?
- 17 Interesting study
- 18 Wikipedia featured article
- 19 Interesting thought about recycled paper
- 20 'Recent Changes'
- 21 black invention myth debunked says right winger
- 22 "Right side of history"
- 23 Results from the Limerick Contest
- 24 Stupid question
- 25 Everythings flipped
- 26 Attention Span Article?
- 27 Bright Ideas
- 28 Express.co.uk
- 29 Issuepedia
- 30 Is Godwin's Law ever invoked in a positive way?
- 31 Appeals to motive on Wikipedia
- 32 Calling Old-Timers
- 33 Thoughts on cooperatives ?
- 34 God's good ideas
- 35 Damn, who is this guy?
- 36 Jon Rappoport
- 37 "Please have specific criticisms"
- 38 Anyone else feel like this tweet?
- 39 Question about IQ
- 40 Crap, I agree with the Republicans on tax policy...
- 41 Revisiting Tragedies
- 42 Sam Harris had Charles Murray on his podcast and uh...
- 43 Here's to being part of the 2%
- 44 Have you seen so much hatred to Einstein in this generation?
- 45 This comment chain was funny.
- 46 Thoughts on Religious Companies?
- 47 I thought I would let you know
- 48 Racial Self-interest is not racism
- 49 Andy has a new weekly column at WND
- 50 What's the difference between the Saloon bar...
- 51 Why
- 52 How do I change my name?
- 53 Weird bug.
- 54 Check out this new Funspace/Parody article I created
- 55 You'll never win
- 56 Why are people still so judgemental in the 21st century?
- 57 R.I.P., feminists
Talkpage editnotice: "please have specific criticisms"[edit]
Many "critical" talkpage comments just say RationalWiki is biased/cucked/etc. Then a brave, noble RatWik must ask the critic "why, what's wrong with the article". Let's have the page itself ask the critic. This is what it would look like:
It's very easy to do. Does the community want it? Fuzzy "Cat" Potato, Jr. (talk/stalk) 19:54, 9 April 2017 (UTC)
- I think it's a good idea. On another note, I'm "a brave, noble RatWik now"? Christopher (talk) 20:04, 9 April 2017 (UTC)
Have it[edit]
- I think it'll be a good idea, not sure how many people will pay attention to it though. Christopher (talk) 20:12, 9 April 2017 (UTC)
- Yeah, ragers gonna rage. But what's most important is showing in good faith that we can actually be reasoned with. With the proposed edit box notice, we're just putting it out there that for anyone who wishes to see changes to some article, letting Cuck-O-Tron 3000 phrase their complaints for them is likely not going to be their most constructive route forward. Reverend Black Percy (talk) 20:49, 9 April 2017 (UTC)
- The overwhelming majority of criticism seems to be "you're all SJWs/cucks etc though, I've never come across an example of genuinely constructive criticism beyond typo correction. Can you think of any off the top of your head? Christopher (talk) 20:56, 9 April 2017 (UTC)
- I'm by no means suggesting we're perfect though, just that genuine constructive criticism is drowned out by trolls. Christopher (talk) 20:58, 9 April 2017 (UTC)
- Take a look at Talk:HIV/AIDS_denialism if you want to see a recent detailed criticism of one of our pages. Bongolian (talk) 21:22, 9 April 2017 (UTC)
- I don't see trolls drowning anything out. In fact, they're typically swept off the platform pretty quickly in the vast majority of cases. And sure, I've come across many instances of "genuinely constructive criticism beyond typo correction" — certainly several tens of times, perhaps even a hundred times or more (in my two highly active years at the site)? Besides, you seem to perhaps be confusing FCP's above proposed template with some kind of "troll/shitpost protection measure"? I assure you it's not. If nothing else, this edit notice is just another chance for us to earnestly offer people the chance to simply play by the rules (which seems to me a win-win). Reverend Black Percy (talk) 00:44, 10 April 2017 (UTC)
- I was sure it must have happened somewhere, what I really meant by "trolls drowning people out" is more things like someone having a detailed criticism of one of our articles and then in their last sentence daring to question our rationality. Then all they'd likely get is "But I thought this was supposed to be RATIONALWiki!" Drink! and have none of their actual criticisms addressed. I should've phrased it better. Christopher (talk) 07:45, 10 April 2017 (UTC)
- Seems like an excellent idea, as far as I understand it. IMO, you should also make the text link clearly to "What is a rationalwiki article?", considering how many BoNs cry foul about things covered in plain English on that page (bias, snark, confusing us for an encyclopedia, etc). Reverend Black Percy (talk) 20:31, 9 April 2017 (UTC)
- And by the way, could it also say something like: "(3) Don't just say "I hate it, blank it all". Provide a constructive suggestion for alternate article text. (4) Remember to include credible sources!"? Reverend Black Percy (talk) 20:36, 9 April 2017 (UTC)
- Yes, good idea. I agree with Percy: encourage them to give sources. Bongolian (talk) 21:22, 9 April 2017 (UTC)
- cool idea, it can be surprising how things like this can actually give people pause Vorarchivist (talk) 00:42, 10 April 2017 (UTC)
- Most people on RW are reasonably cooperative (even if having quirky sense of humour/going off at a tangent/needing some help to operate in the wikiverse etc); some people have particular bees in their bonnets/get into 'who blinks last' exchanges and similar; some people enjoy 'stirring' because they think it is the spirit of RW (including the "daring" - is this another version of "just asking questions"?) - and then there are those whose 'views at a significant angle to reality' are being challenged, those who just wish to complain; the 'look at me being a nuisance (till I am blocked)' and the real trolls and other nasties. ('Just summarising') 82.44.143.26 (talk) 16:05, 10 April 2017 (UTC)
- Yes! Yes! Yes! Spud (talk) 16:12, 10 April 2017 (UTC)
- Assuming we can limit to pages that are likely to breed such non-specific whines. ikanreed You probably didn't deserve that 16:37, 10 April 2017 (UTC)
- Good idea. I was going to suggest making the text link to "What is a rationalwiki article?" but that hyperactive Swede beat me to it. Leuders (talk) 17:59, 10 April 2017 (UTC)
- MFW Reverend Black Percy (talk) 18:14, 10 April 2017 (UTC)
- I asked the spirit of the dead horse: "Yay". But then the table started trembling, seized by a voiceless cynical giggling which could only be interpreted as the prophecy of more flogging because of people who don't even bother reading the first lines of the articles they criticize. --Cmonk (talk) 20:01, 10 April 2017 (UTC)
- And Percy hits another one from left field. Good idea! Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 17:33, 11 April 2017 (UTC)
- I think it was Fuzzy who thought of it actually. Christopher (talk) 17:35, 11 April 2017 (UTC)
- Oops. My bad, I woke up extra early today so I'm still feeling somewhat tired. Great idea, though, FCP! Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 18:04, 11 April 2017 (UTC)
- Hey, the only reason I can see so far is because I'm standing on the shoulders of Fuzzy. Reverend Black Percy (talk) 16:42, 12 April 2017 (UTC)
- Yeah. Won't work of course, but at least it's another reason to rapidly collapse the inane - David Gerard (talk) 12:31, 12 April 2017 (UTC)
Don't have it[edit]
Goat[edit]
- To cheer people up [1]. 82.44.143.26 (talk) 16:05, 10 April 2017 (UTC)
- So that's where argan oil comes from! It's expensive shit; ahem 😉. And wouldn't you know it, Dr. Axe is touting it.[2] Bongolian (talk) 16:57, 10 April 2017 (UTC)
- (edit conflict) Whilst there aren't really any rules on it, the "goat" section is generally about discussing the proposed change. Not discussion of goats. Doesn't particularly matter and it's a common mistake to make, just thought I'd let you know. Christopher (talk) 17:04, 10 April 2017 (UTC)
- "Needs more Goat" is on the official agenda, however. Reverend Black Percy (talk) 18:10, 10 April 2017 (UTC)
- And discussion of goats is always preferred over discussion of things that are not goats. Christopher (talk) 11:01, 11 April 2017 (UTC)
- One thing to have, another thing to enforce it. So, if there are comments that violate it, what would be the proper course of action? I'm iffy on outright deleting it, not because the troll will cry out "censorship" (that's not my concern), but because people might not use their judgement wisely and delete things they disagree with it. I do guess that engagement and pointing out the template works, but it only goes so far sometimes in testing patience... --It's-a me, LeftyGreenMario!(Mod) 18:32, 10 April 2017 (UTC)
- As the IP is overtly out to amuse, and has informed, are they off-message, or abiding to the spirit of Rationalwiki? 86.191.125.209 (talk) 21:43, 10 April 2017 (UTC)
- Going to agree with GreenMario. Seems like alot of work. Also I like to have arguments whit crazy people. 2d4chanfag (talk) 03:49, 11 April 2017 (UTC)
- Which of the above persons are you referring to in particular (and do you mean 'with' or 'wit', or do you not give a whit?) 86.146.99.26 (talk) 09:51, 11 April 2017 (UTC)
- I don't think 2d4chanfag is referring to anyone in particular, could be any of the many cranks who, instead of providing any constructive criticism, just say "YOUR[sic]ALL CUCKS LOL FAG I THOUGHT THIS WAS CALLED RATIONALWIKI!!!!!!111!!!SHIFT1!!SHIFToneeleventyone11!!!1! Or a variation thereof. Christopher (talk) 10:01, 11 April 2017 (UTC)
- @86.146.99.26 Yes. 2d4chanfag (talk) 11:28, 11 April 2017 (UTC)
- @LGM: If a talkpage critic is shitty and boring and vague, then nothing needs to happen. As the maxim goes: If it's shit, don't touch it. Sir ℱ℧ℤℤϒℂᗩℑᑭƠℑᗩℑƠ (talk/stalk) 18:40, 11 April 2017 (UTC)
- Easier said than done, given that it can be difficult to identify someone who is genuinely critical, but uses abrasive language, a concern troll, and an outright troll. It's more often than not that someone will come and respond. Anyhow, from my experience, a lot of people don't pay attention to talk page notices (when they should grumble grumble) so I will question its effectiveness in the future. --It's-a me, LeftyGreenMario!(Mod) 19:50, 11 April 2017 (UTC)
- Does argan oil deserve a RW article (and not just to have a picture of the goats in question) - or a section somewhere? 86.146.99.26 (talk) 22:30, 11 April 2017 (UTC)
- @LGM You must become more zen, grasshopper. Indeed, the day all drive-by whine ceases completely is the day we're no longer being read by anyone. Besides, if we devolve into a perfectly insular community, group polarization becomes a serious risk to our rationality — an effect which is "increased by settings in which people repeat and validate each other's statements", as TOW puts it. As such, there's basically no type of talkpage criticism that I personally mind a priori. Best case, criticisms are brought to the fore which actually adress something that ought to change in the article (leaving us with improved content). "Worst" case, the rants serve to provide essential insight into the heart and mind of ye olde crank — in rare cases, even adding to our esteemed crack-Potédex. Reverend Black Percy (talk) 08:29, 13 April 2017 (UTC)
Holocaust denial to cover?[edit]
Talk:Holocaust_denial#2017.2C_CAN_WE_COVER_STORY_THIS - the cover nom got mistakenly archived. I've pulled it out. Discuss over at the talk page - David Gerard (talk) 13:06, 12 April 2017 (UTC)
- Hm. I wonder what could have prompted a push to cover story it. Narky Sawtooth (Nyar?~) 14:36, 12 April 2017 (UTC)
- Why? You think it was a holohoax? Reverend Black Percy (talk) 16:54, 12 April 2017 (UTC)
- Huh? I'm saying that this sounds related to Spicey. Narky Sawtooth (Nyar?~) 20:28, 12 April 2017 (UTC)
- A Twitter exchange I saw actually. I looked up our article and went "huh, why isn't this cover" and saw the nominee template on talk and tracked through the archives for the nom - David Gerard (talk) 22:18, 12 April 2017 (UTC)
- @Narky Just pulling your leg Who is Spicey? Reverend Black Percy (talk) 08:03, 13 April 2017 (UTC)
- It's pretty fucking obvious Spicer was saying Hitler did not use chemical weapons on the battlefield (Hitler himself was wounded in a chemical weapons attack in WWI). Trying to make something of it other than what it is will only backfire, and discredit RW's Holocaust denial article. No different than calling everybody who scratched their ass or sneezed during Obama's lectures on morality and Obamacare rather than undivided devotion labeled as a racist. When will you guys ever learn? nobs 19:33, 13 April 2017 (UTC)
- ...What in sweet baby Jesus' name are you even talking about, nobs? You're doing that thing you do again Reverend Black Percy (talk) 00:24, 14 April 2017 (UTC)
Y'all gotta see this[edit]
Don't know why I didn't think of showing this earlier, but check this out. They say they're a "self taught[sic] law student." You know what that means! They've even got this nice little post. And, after you're done laughing at that weirdness, this should provide context. Narky Sawtooth (Nyar?~) 14:35, 12 April 2017 (UTC)
- Oh lovely, I can already see the RW page being typed up. In all seriousness, if this isn't going to mar the reputation of the furry fandom, I don't know what will. The living oxymoron (talk) 14:58, 12 April 2017 (UTC)
- Seems it's having a positive effect? Like, it's a nice conversation starter that can lead into other furriness. Narky Sawtooth (Nyar?~) 16:52, 12 April 2017 (UTC)
- Why, it's as if they were bat signaling Encyclopedia Dramatica on purpose. Reverend Black Percy (talk) 17:00, 12 April 2017 (UTC)
- Heh. Bat signalling... Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 20:15, 12 April 2017 (UTC)
- Abraham Lincoln was a self taught law student, wasn't he? nobs
- ...Could someone please reboot nobs? I think his cerebrum is spazzing out again. Reverend Black Percy (talk) 00:39, 14 April 2017 (UTC)
My girlfriend just texted me[edit]
She sent me pictures of the ear pain medicines at the pharmacy to ask which one I thought was best.
Every single one was useless homeopathic garbage after googling them. Every. Single. One.
How can you go to a pharmacy looking for over-the-counter medication for a specific problem(ear pain) and literally see nothing but water? What the fuck Walgreens? ikanreed 🐐Bleat at me 21:36, 11 April 2017 (UTC)
- (I recommended oral acetaminophen(i.e. Tylenol) if she thought it wasn't going to be bad enough to warrant a doctor). ikanreed 🐐Bleat at me 21:41, 11 April 2017 (UTC)
- Painkillers block the pain receptors in the brain, rather than shutting off the perticular nerves sending the pain signal (in the ear in your case). If you want to relieve the pain, then use general everyday painkillers. If you want to cure the pain's cause, you need something more specific. What does your doctor say? Bicyclewheel 11:17, 12 April 2017 (UTC)
- Ibuprofen, it's anti-inflammatory - David Gerard (talk) 12:32, 12 April 2017 (UTC)
- Ear trouble is a bitch, since it's one of the most insufferable places to have problems in, while at the same time being one of the most fragile systems in the body (and trying to "treat" it yourself risks causing serious damage!). Be careful NOT to use any shitty OTC ear washing products, Ikan! They do more harm than good. Whatever the issue is, it's rarely caused by wax — and even when it is, you NEED a qualified ENT doctor to perform any such procedure on you if said specialist finds need for it, etc... Ear pain/hearing loss is a bitch, but don't squirt a bunch of shit in your ear or dig around in your ear canal, ESPECIALLY not with cotton swabs (they are meant ONLY for surface cleaning, and you WILL push the wax deeper if you go in deep with them). Instead, take oral meds, use nasal spray (it reduces ear swelling slightly), see an ENT if need be and — most importantly — let things take its time. Reverend Black Percy (talk) 12:43, 12 April 2017 (UTC)
- I will also note that it's paracetamol alone which works the way Bicycle Wheel describes (which makes it excellent for ear pain). Ibuprofen, as brought up by David, might help as well by virtue of being an NSAID. Reverend Black Percy (talk) 12:48, 12 April 2017 (UTC)
- You guys are missing the point. The problem is a major American pharmacy chain has a section devoted to treating a specific problem where none of the medicines are real. ikanreed 🐐Bleat at me 15:24, 12 April 2017 (UTC)
- Oh, it's not that I missed that. It pisses me off to hear, truly (and I'm relieved that all Swedish pharmacies keep that hokum out). It's just that I recall having read something about that happening before. But I will agree that it seems uniquely derp to hear that ALL the options were homeopathic. I mean, what kinda godforsaken hippie pharmacy did you send her to? Cause I worry for you and your countrymen if ALL-homeopathy treatment is becoming the new OTC standard. Reverend Black Percy (talk) 16:47, 12 April 2017 (UTC)
- Walgreens is one of the three big pharmacy chain stores(CVS and rite-aid are the other two) in the US, with no particular focus on alt-med compared to its competitors. You cannot go into a pharamacy in the US, grab an arbitrary OTC treatment, and count on it being actual medicine. ikanreed 🐐Bleat at me 17:26, 12 April 2017 (UTC)
- Jesus Shit like this is what makes RW worthwhile, IMO. Also, note that not only is it not medicine — it even poses a health risk of its own! Reverend Black Percy (talk) 17:32, 12 April 2017 (UTC)
Depending on what's causing the earache, you might try the Bronk-Aid asthma pills. These contain both ephedrine as a decongestant, and guaifenesin to loosen up phlegm and snot. A lot of earaches are caused by fluid and pressure due to inflammation from upper respiratory tract infections or allergies. Decongestants and expectorants will help. I also recommend chewing a large wad of bubble gum. - Smerdis of Tlön, LOAD "*", 8, 1. 18:04, 12 April 2017 (UTC)
- She should see a doctor since it could be an infection requiring antibiotics. Bongolian (talk) 20:10, 12 April 2017 (UTC)
- @Ikanreed Man — you're gonna have to be much clearer next time. The compulsive helpfulness of us RationalWikians came to overshadow your point Haha. Reverend Black Percy (talk) 08:08, 13 April 2017 (UTC)
Blog: American Kabuki[edit]
Found this blogger yesterday. And explaining it doesn't do justice, have a look:
I think the blog post about Antarctica should sum up what this blog is like:
—チーズバーガー • めん (talk • stalk) 21:58, 12 April 2017 (UTC)
- Error 404: Logic not found-D1@m0ndD15c1 (talk) 03:18, 13 April 2017 (UTC)
- Best part, IMO:
- In other words:
- I'm aware that contactees tend to unwittingly base their own descriptions of the aliens on popular culture, but this is just ridiculous. Reverend Black Percy (talk) 07:48, 13 April 2017 (UTC)
- The sov cit I linked earlier engages in Antarctica trutherism. Is it making a comeback or something? Speaking of, the woo surrounding Terra Australis is interesting (they got bored of looking for it and named a different continent "Australia," and it is only by coincidence that Terra Australis existed) Narky Sawtooth (Nyar?~) 07:51, 13 April 2017 (UTC)
- There's more to the blogger than just that. The blogger retweeted this:
- McCain: "The New World Order Is Under Enormous Strain"
- The blogger also posted this on their blog:
- is smart and good at making deals. And he knows how to handle very large bankruptcy which is perhaps his most important skill for this moment as CEO of the USA Corp.
- And this:
- Terran: Nabrac the energies feel particularly intense tonight. Almost on the level of when the trio are working.Do you know what is transpiring?
- Nabrac: TERRAN. ALL IS FLOWING. INTENSITY WILL ACCELERATE AND EXPAND EVEN MORE. NABRAC.
- Terran: Duration?
- Nabrac: TERRAN. DURATION HAS A HIGH PROBABILITY OF ONE FULL DAY AND NIGHT. NABRAC.
- "Benjamin Fulford: Now.”
- Pyramids in Antartica, lol
- —チーズバーガー • めん (talk • stalk) 18:59, 13 April 2017 (UTC)
- Now I heard the Planet Nibiru really is the cause of the rise in the ocean's temperature and nothing anthropomorphic. Any truth to this? I read it in the CIA blog, the Washington Post. nobs 19:52, 13 April 2017 (UTC)
- this one is interesting. Individually, the beginnings of their thoughts always catch my interest and make me think "huh, there may be something to this." Then they launch into the explanation and completely lose me. From there I look at their message as a whole and realize it's a jumbled mess. 71.188.73.196 (talk) 20:03, 13 April 2017 (UTC)
- @nobs I don't know how the heck you managed to read that WaPo article as somehow suggesting (or even implying) that "AGW is being caused by Niburu". I mean, it clearly says "No" right there in the headline. Did you get as far as reading the headline, I wonder? Reverend Black Percy (talk) 01:14, 14 April 2017 (UTC)
- People read nobs's posts? Whenever you see a post of his, skip it.—チーズバーガー • めん (talk • stalk) 03:09, 14 April 2017 (UTC)
- I was just calling attention that ZetaTalk#Current_status needs updating. It's back in the news. And what would you expect WaPo, the CIA's mouthpiece to do anyway, admit to their crimes? nobs 04:48, 14 April 2017 (UTC)
- What drugs are you on, nobs? I want to make some RW pages for them if they don't already exist. 07:24, 14 April 2017 (UTC)Bongolian (talk)
Proposal: Re-purpose the Elections WIGO to Politics[edit]
For better or for worse, the Bar has a good share of political discussion. The Elections WIGO is rather moribund since the culmination of last year's Clown car. I propose renaming the Elections WIGO to the Politics WIGO. This will, for example, let us keep the Trump drama out of WIGO World, and make the existing WIGO page more useful and entertaining. What do you think? Regards, Cosmikdebris (talk) 00:10, 7 April 2017 (UTC)
- I think it makes sense because not all countries have elections, although it won't always be obvious where to put an entry (controversial law, major change in leadership). --Cmonk (talk) 01:38, 7 April 2017 (UTC)
- Yeah, occasionally there has been a Blogs versus Clogs versus World debate, but i trust the mobacracy to sort it out. It should be relatively easy for anyone to judge if a politics-related event is relevant to the world, or if it's of topical interest. People outside the US may not be particularly interested in what some alt-right asshat on Trump's staff is up to, for example. Regards, Cosmikdebris (talk) 01:56, 7 April 2017 (UTC)
- I'm from outside the US and I can't get enough of what the alt-right asshats in the White House are up to. 85.234.65.51 (talk) (Sophie) 08:58, 7 April 2017 (UTC)
- Also our current format misses out on all the wierd white house news these days and make it more useful in the day to day instead of taking it out every once and while Vorarchivist (talk) 03:04, 9 April 2017 (UTC)
The main problem is...[edit]
The main problem is that WIGO is getting filled these days with tedious rubbish and isn't much worth reading - David Gerard (talk) 12:30, 12 April 2017 (UTC)
- The voting system only provides limited feedback. Do you have any suggestions to help improve the entries? --Cmonk (talk) 16:49, 12 April 2017 (UTC)
- Tell people who put in humdrum everyday news articles to stop putting in humdrum everyday news articles. What are we, Fark or something? 85.234.65.51 (talk) 11:15, 14 April 2017 (UTC)
- +1 - David Gerard (talk) 19:11, 15 April 2017 (UTC)
Trump preemptive strike[edit]
The US is planning a preemptive strike if N.Korea does a nuclear test. This is getting more terrifying. I think we might be going to war with China and North Korea perhaps. I know I might be overreacting to this,but I am genuinely afraid of what is going to happen. S.H. DeLong (talk) 02:09, 14 April 2017 (UTC)
- This is just stap one to bring the world under one government. The Terran Republic will raise up to be a great power in this galaxy.2d4chanfag (talk) 03:04, 14 April 2017 (UTC)
- @S.H. DeLong. I'd be concerned, but I wouldn't worry too much. N. Korea has done many nuclear tests. [3]. Reports that the US will strike if they do another test may be overstated (it happens, even with normally reliable news media). I think what you're seeing is the US preparing for a worst-case scenario: i.e. N. Korea launches a nuke that's aimed dangerously close to, or directly at Japan, China, or S. Korea. There are various methods [4], [5] for knocking such a missile out, although the most effective ones are probably classified. Leuders (talk) 03:16, 14 April 2017 (UTC)
- ^Phew.-D1@m0ndD15c1 (talk) 04:03, 14 April 2017 (UTC)
- This is scheduled to be an underground test, sort of like Fourth of July fireworks for a national holiday. We can knock down a NK missile test with all sorts of electronic gadgetry to make it veer off coarse, as has been done to the last few. We got all sorts of other shit to disrupt their power grid, radiowave, and electronic communications. If they really want to set it off, it could be done manually with a suicide bomber.
- And if you wanna be pissed off at a Westerner for rising tensions and nuclear proliferation, be pissed off at the God damn Clintons; they are the mutherfuckin' pieces of shit that paid NK to build the goddam bomb, so long as they wouldn't give Bill any trouble while he was in office. nobs 04:33, 14 April 2017 (UTC)
- All this sabre rattling and displays of even bigger bombs and the stated intention of regime change just make the likes of north korea and iran more likely to develop and more convinced of the need for nuclear weapons. Bombs alone will not achieve the stated end, nor is there any thought of dealing with the aftermath as per iraq. History repeats itself. Are you still convinced Trump has any kind of plan? As for suicide bombers with nukes, its not nk or iran you need you should be worried about, its existing nuclear states failing that should be the worry - Pakistan should be more of a concern. That being said, i find it difficult to begrudge even awful regimes such as NK and iran a nuclear deterrent in face of our own hypocrisy is maintaining and updating our own and our own increased increased belligerence towards these states. AMassiveGay (talk) 10:50, 14 April 2017 (UTC)
- Here's my theory: the Pentagon is running the country. The Commander-in-Chief is on auto pilot giving the reins over to the generals-as he said as much he'd do on the campaign trail. For eights years the international situation deteriorated as the Pentagon was shut out and ignored (Obama went thru 4 Defense Secretaries in 8 years). But these military planners watch moment by moment, always ready with a next step strategic response. Now we are going thru a "catch up" phase to rectify balance. Witness: Syria, MOAB, NK, etc etc. War is diplomacy carried on by other means. nobs 14:51, 14 April 2017 (UTC)
- According to Wikipedia, the actual quote is "War is a mere continuation of politics by other means" (source). Setting aside the questionable wisdom of having a country run by the military, war is not diplomacy, unless we really want to give up on words and meaning (I don't). --Cmonk (talk) 15:37, 14 April 2017 (UTC)
- The context in which Clausewitz is speaking is, relations between peoples and nations do not stop simply because diplomatic notes are no longer exchanged. And to understand this context you need familiarity with a few chapters leading up to the famous dictum:
- 3.B. On the Magnitude of the Object of the War and the Efforts to be Made
- 4. Ends in War More Precisely Defined—Overthrow of the Enemy
- 5. Ends in War More Precisely Defined (continuation)—Limited Object
- 6.A. Influence of the Political Object on the Military Object
- 6.B. War as an Instrument of Policy
- This is the 1873 translation, probably best available online. nobs 00:55, 15 April 2017 (UTC)
From an analysis given on the same website: "One of the main sources of confusion about Clausewitz's approach lies in his dialectical method of presentation. For example, Clausewitz's famous line that "War is merely a continuation of Politik," while accurate as far as it goes, was not intended as a statement of fact. It is the antithesis in a dialectical argument whose thesis is the point—made earlier in the analysis—that "war is nothing but a duel ... on a larger scale."." I read the chapters that you recommended, but not being a Clausewitz expert, I can only defer to others as to what he did or didn't mean.
Clausewitz's book is titled "On War", not "On Diplomacy", so it is not surprising that he relates everything to war. The online translation seems to have a slightly different text than yours: "Does the cessation of diplomatic notes stop the political relations between different nations and Governments?" I can't be certain of the meaning the words "diplomacy", "policy" and "politics" in the translation compared to the original. But there is no point in torturing the language to try to make Clausewitz say something that he may or may not have meant. The start of a war is a failure of diplomacy. Diplomacy can (optionally) still go on in parallel (not replaced) and bring an end to the war, but it is not about "the overthrow of the enemy". While I do not have a solid grasp of military tactics and strategies, I do understand that people suffer and die while the political game of war is going on.
Finally Clausewitz claims: ." I do not subscribe to this point of view, because this is how we fail to recognize our own biases. There are other minor points on which I disagree (maybe it is the translation, or the thesis/antithesis confuses me). In the end, I would still prefer to avoid another war, but the big decisions are out of my hands. Anyway, thanks for the reference. --Cmonk (talk) 04:56, 15 April 2017 (UTC)
- I'm speeking from memory of the 1976 translation, which isn't online. The 1943 version is abridged, and doesn't carry these final chapters. Chapters 4 discusses Total War, such as WWII; chapt. 5 a War of Limited Aims, such as the Gulf War of 1991-merely expel Saddam from Kuwait and not regime change. As you get into chapter 6, you realize Clausewitz was ignored by Hindenburg & Ludendorf in WWI. Clausewitz emphasizes that despite war's violent and emotional nature tending toward the extreme, The political object comes to the fore (1976 trans). That when diplomatic notes no longer are exchanged, the military men take over (Bay of Pigs, for example, after diplomatic relations with Cuba were cut off). But in a Total War of Attrition, such as WWI was, the political object was subordinated to the military object. This is what this chapter forwarns against. The political object - even though diplomats are no longer speaking - must remain the focus. By 1917-18, the whole Imperial German civil government melted away, and the whole nation, economy, and government were serving the military which was fighting a lost cause.
- Let me just lift out two paragraphs that serve our purposes well in this translation. (Sorry for the repetion) The first from a merely personal, moral point of view;
- .'
- And secondly, to emphasize the military objective serving the political objective (the Anglo-American tradition of military serving civilian leadership we take for granted; fortunately the German & Russian traditions now also see and accept this principal. In China, the Communist party basically is the military, supported by a massive, growing, private sector with no democratic rights).
- "That the political point of view should end completely when war begins, is only conceivable in contests which are wars of life and death, from pure hatred: as wars are in reality, they are as we before said, only the expressions."
- So in all cases, the first question is, What are we trying to achieve? in too many cases, the original political object becomes obscured, or forgotten. Syria (from the internal parties perspectives) now, Vietnam, and WWII are some of the best examples. Whereas the 1991 Gulf War or Civil War are good examples of wars being fought through to their finish with the desired policy aim intact.
- American policy in all its foreign wars can best be described in the following nonsensical anecdote (I tell it better live, but I'll try it here in writing):
- The Americans soldiers beats down the enemy, disarms him, has him laying flat on his back, standing over him with his rifle and extended bayonet at the enemies throat. Than, with his blood pumping, shouts, "God damn it! You better accept human rights and freedom of speech". The poor, broken, helpless, defeated enemy then raises his head and screams, "FUCK YOU!". Then the dutiful American soldier lays down his weapon, extends his hand and says, "Now you got it, brother.
- I'm just not so sure this time-tested policy works against jihadis. nobs 06:43, 15 April 2017 (UTC)
Political aims and civilian leadership[edit]
This is a very interesting video relevent to now.
- Sec. Gates focus's on the Clausewitzian aspect of the political aim not being subordinated to military necessity (the mistrust among Obama's NSC of the Pentagon. "box you in" aspect).
- Sec. Penatta's comments about "proximity is everything in the White House", the speculation on Bannon's future right now.
- Sec. Hagel's comments about "35 year old PhDs", -- Jake Sullivan presumably, the author of last weeks Wikileaks dump about "Al Qaeda is on our side." And comments on Susan Rice's approach.
Trump has essentially given the Pentagon "blanket check" authority to do what they deem necessary to pacify the regions of Syria, Afghanistan, and North Korea until the "political object comes to the fore". The most important thing is that we have a political object in these regions once they are pacified. Here the chapt, Attack on a Theatre of War without the View to a Great Decision comes into play. nobs 19:29, 15 April 2017 (UTC)
- Here for example, a prime example of a violation of Clausewitz dictum: using military force with no political object, stated in plain terms:
- "We are currently doing everything we can to bomb, strafe and use missiles to carry the rebels into power in Libya. We want them to win. We just don’t know who they are.” -Hillary Clinton, June 23, 2013. Cite: Preston, Bryan (June 23, 2011). "Hillary Clinton to Libya skeptics: 'Whose side are you on?'". PJMedia website/PJTatler. nobs 22:12, 15 April 2017 (UTC)
And sport is a continuation of war by other means (see Trobriand Island Cricket). Things would be much safer if the leaders of countries had to do a bout of hand to hand combat before they declared war. 86.191.125.172 (talk) 21:42, 14 April 2017 (UTC)
- That's what the game of polo is. It was training for knights (fighter pilots would be the modern equivalent) to swing a sword on horseback and lop off a footsoldiers head. nobs 01:19, 15 April 2017 (UTC)
Zero hour...[edit].[6] [7] to anyone who has the opportunity to see it. 86.145.120.178 (talk) 21:43, 15 April 2017 (UTC)
Brittany Pettibone & Lauren Southern[edit]
"Our own" Brittany Pettibone User:BrittanyPBone as well as Lauren Southern were scheduled to appear[8] at this riot in Berkeley today.[9] The park where the riot was scheduled was once informally known as "Provo Park", after the Dutch Provos.[10]?[edit]!!(Mod) 03:22, 20 April 2017 (UTC)
--Rbaja (talk) 21:10, 20 April 2017 (UTC)
Appeal to identity[edit]? FU22YC47P07470 (talk/stalk) 21:36, 19 April 2017 (UTC)
- Sounds a little similar to the friend argument but not quite.—チーズバーガー • めん (talk • stalk)!)
- This seems like suitable content for a page, but what should we call it? Samstr (talk) 01:27, 21 April 2017 (UTC)
It's alive! IT'S ALIIIIVE!!!!! (Kind of.)[edit]
[edit]
Is Nibiru an excuse to increase funding for FEMA camps? [11])
- Ignore this thread folks.-D1@m0ndD15c1 (talk) 06:43, 22 April 2017 (UTC)
Thread for crazy stuff you come across[edit] also)
RationalWiki edits, graphed[edit]
I figured out how to use the MediaWiki API, which made grabbing all the edits 100x easier. It also made it possible to graph the actual characters added over time -- which might be a more useful barometer of activity than edits themselves. Graphs available at:
The data doesn't include page deletions, so the "characters added" graphs might be larger than what's real.
αδελφός ΓυζζγςατΡοτατο (talk/stalk) 16:30, 22 April 2017 (UTC)
- Found a typo. Guess what it is.—チーズバーガー • めん (talk • stalk) 16:37, 22 April 2017 (UTC)
- Fixed. Herr FuzzyKatzenPotato (talk/stalk) 17:12, 22 April 2017 (UTC)
I thought the proportion of characters by namespace and proportion of edits by namespace were interesting. You can see the downfall of Conservapedia-space and the rise of mainspace pretty damn clear. αδελφός ΓυζζγςατΡοτατο (talk/stalk) 17:15, 22 April 2017 (UTC)
Who else is joining the March for science?[edit]
It's tomorrow! I'm going! Go science!QuantumDudeI am beyond your understanding 16:50, 21 April 2017 (UTC)
- I would, but I'm going to a trigonometry contest tomorrow. RoninMacbeth (talk) 17:04, 21 April 2017 (UTC)
- I'll be marching in Sweden! Reverend Black Percy (talk) 18:08, 21 April 2017 (UTC)
- ...have a trout slap, for making the same stupid joke as my older brother. Reverend Black Percy (talk) 14:17, 23 April 2017 (UTC)
Interesting study[edit]
Too special to be duped: Need for uniqueness motivates conspiracy beliefs.
Conclusion:
Across three studies, the desire to see oneself as unique was weakly but reliably associated with the general mindset behind conspirational thinking, conspiracy mentality, as well as the endorsement of specific conspiracy beliefs. These results thus point to a hitherto. The current findings add to this emerging image by pointing to a highly functional aspect of endorsing largely unpopular conspiracy beliefs. All humans share not only the need to belong and affiliate with others (Baumeister & Leary, 1995), but also to be different and stick out from them, to be an identifiably unique individual (Snyder & Fromkin, 1980). In navigating both these goals, individuals engage in social identification processes with groups that serve both needs to a comparable degree (Brewer, 1991) and make consumer choices that can either signify belonging to a certain group of consumers or signify differentness. The same logic is also applicable to attitudes; Agreeing with overly consensual opinions is aversive for people with a heightened need for uniqueness (Imhoff & Erb, 2009) and they may thus turn to less common opinions. Conspiracy theories seem to hold the promise of being a set of political attitudes that guarantees that one will be seen as having an independent, if not necessarily accurate, mind.
Damn interesting. Mʀ. Wʜɪsᴋᴇʀs, Esϙᴜɪʀᴇ (talk/stalk) 19:37, 22 April 2017 (UTC)
- Wow. America has become a nation of Californians - 300 million eccentrics. Between the anti-globalists and Russia-Trumpers, beating each other up in the streets, looking for a sense of community. nobs 19:55, 22 April 2017 (UTC)
- I resent that comment!...and grudgingly recognize its veracity. RoninMacbeth (talk) 21:17, 22 April 2017 (UTC)
- So, the alt-righters (and other extremists) are basically political hipsters then. Having some experience with alt-righters, I always thought this in a way, and I'm glad studies came to this conclusion. I recall JonTron being against identity politics, so there's that.—チーズバーガー • めん (talk • stalk) 00:23, 23 April 2017 (UTC)
- This study also further extends the idea of human conflict being integral to human interaction, as can be read in this article.—チーズバーガー • めん (talk • stalk) 00:28, 23 April 2017 (UTC)
@nobs Hey! Not all Californians are like that, only about 98% are.'Legionwhat do you want from me 02:00, 23 April 2017 (UTC)
- The other 2% are conformists. nobs 03:33, 23 April 2017 (UTC)
- Hah, is funny because when rejection is most common, acceptance is conformism! CorruptUser (talk) 04:45, 23 April 2017 (UTC)
Wikipedia featured article[edit]
Coincidentally, Wikipedia's featured article today (Shakespeare authorship question) is the same one as on RW (Shakespeare authorship). Bongolian (talk) 06:31, 23 April 2017 (UTC)
- Obligatory WAKE UP!!! Reverend Black Percy (talk) 14:15, 23 April 2017 (UTC)
- Coincidence, hell! It's Shakespeare's birthday! Spud (talk)
- Wait, isn't that a coincidence too? 😉 Bongolian (talk) 16:48, 23 April 2017 (UTC)
- It's actually the anniversary of his death, his birthday is in 3 days.'Legionwhat do you want from me 21:25, 23 April 2017 (UTC)
- Well, the truth is the date of his birth is unknown. It's known that he was baptized on 26 April 1564, so he was probably born soon before then. And yes it is known that he died on 23 April 1616. Anyway, like all good Stratfordians (and Stratfordodians) I always celebrate Shakespeare's birthday on 23 April. Spud (talk)
Interesting thought about recycled paper[edit]
Have you ever had something made of recycled paper and wondered where it came from? Have you ever considered that new certificate or license may have at one point been a political flyer for Donald Trump, a church bulleton from a right wing church, a Jehovah's Witness flyer, a school assignment from Bob Jones University, or an advertisement for some kind of homeopathic quackery? 172.58.11.195 (talk) 03:03, 24 April 2017 (UTC)
- So, basically the old "did you consider that the water you're drinking was once dinosaur pee" idea but with paper? Incidentally, no, I didn't. RoninMacbeth (talk) 03:35, 24 April 2017 (UTC)
'Recent Changes'[edit]
Can the St George's tag be removed - as the day has been and gone?
(St George and the Dragon were running a 'leave your local village without relatives hauling you back' set up but then George fell in love with one of the intending leavers.) 31.51.114.96 (talk) 10:39, 24 April 2017 (UTC)
- Not everyone lives in the same time zone as you, 31.51.114.96. The Holydaze template appears on the recent changes page 12 hours before the special day starts in UTC and stays there until 12 hours after the day's finished in UTC. That's why, for a few hours yesterday the Earth Day and St. George's Day templates were both up at the same time (it was 23 April in some time zones but still 22 April in others). For the same reason, you'll see the Christmas day and Boxing Day templates appear together for a few hours. Spud (talk) 15:24, 24 April 2017 (UTC)
black invention myth debunked says right winger[edit]
-)
- Erdogan, Kim Jong-Un, and Xi Jinping. RoninMacbeth (talk) 21:10, 25 April 2017 (UTC)
"Right side of history"[edit]?—チーズバーガー • めん (talk • stalk):[12])
- Le Pen has her secret army of women standing up for wom3n's rights. It's about time. We need more Rosa Parks standing up against shariah. What's next? Terror attacks on polling places? nobs 00:10, 22 April 2017 (UTC)
- Same problem with Pascal's wager It doesn't matter the cause if your justification is bullshit. But if I wanted to tear feminism down I'd have a harder time because God is hard to prove and seems to have no real effect. At least feminism stands for something that could work. Gaul Dernitt (talk) 06:56, 22 April 2017 (UTC)
- Feminism is like Islam; (a) nobody knows what it is, and (b) you got moderate believers and hardcore assholes. nobs 07:05, 22 April 2017 (UTC)
- Not a great job. But Feminism is not like Islam, because one is a radical response to societal injustice and the other justifies itself with a magic wizard. Gaul Dernitt (talk) 07:15, 22 April 2017 (UTC)
- Islam was founded as a response to social injustice (Jahiliyyah. Infanticide, for example, was rampant. Islam was meant to civilize the ignorant who practiced social injustice, same as it does today). What, you think this generation is something special? that the human race had to wait twenty centuries after Christ to invent or discover social injustice? nobs 08:10, 22 April 2017 (UTC)
- I guess not, but you're hardly defending anything. Yes, social justice is a consistently current thing, co-opted by groups. That doesn't make it wrong, especially shows it ain't right, and it categorically cannot make current social morality movements a religion, except they should be and they should respect each other because people. Wait, I meant to say is nobs a liberal? Gaul Dernitt (talk) 08:46, 22 April 2017 (UTC)
- At somepoint in recent years - I don't know when it was (probably before Obama, maybe) we crossed the Rubicon. Old notions, still taught in text books and widely held as liberal and conservative have fallen away. And what's emerging bares scant resemblance to either. Yes, there are deep down basic precepts in each, but they are easily forgotten or compromised in a world that's changing too fast for people to keep up with.
- Take User:Conservative, for instance. He's stuck on a 1970s sermon by Jerry Falwell that secularization is the big enemy, hence 'desecularization' means Christian revival. The hell it does. Preaching the gospel means Christian revival, which he conveniently ignores, while he races down the road to praying to Mecca five times a day and worshipping a rock. And it's not like the bible he touts dorsn't warn him of this.
- Or look at the anti-nationalists who accuse Trump of Treason. Only a person who believes in national borders would call somebody else a traitor. Hypocricy? No. This is the only criticism leveled at Trump with chance to stick. And they are committed and really believe it.
- We're going thru a mass confusion stage, but what emerges at the other end won't bare any resemblance to the things we've known. nobs 10:05, 22 April 2017 (UTC)
- Welcome to every other point in the history of anything. I think that was your point?
- My points are somehow now 1) Feminism bares no resemblance to Islam, 2) Trump is a national disgrace who is breaking the law and ignoring the terms and conditions of holding the highest executive office in the US, both implied and explicit (tax returns to running international business).
- It's not an age of confusion about the facts, because we have them. And we can verify them even if some people choose not to. If it's an age of confusion, it's because we're confused what to do with people like Trump. I like you but how far off the rails are we and to what end? Gaul Dernitt (talk) 17:50, 22 April 2017 (UTC)
- Feminism is a cult phase that can't possibly survive two decades of Islamic dominance.
- There is no compulsion to share one's tax information. That violates all the sacred privacy rights Americans hold dear. nobs 19:46, 22 April 2017 (UTC)
- Nobs, your first point was feminism is similar to Islam, then you went on saying that apparently social justice was not a thing of this generation. But somehow recently they succeeded more. The point is that Islam was meant to address a supposed injustice tracing back to Abraham and a disowned son, feminism about concrete inequality. I also have qualms about the extremist sjw degeneration, of course, because of their rigidity and the embarrassing strawman they serve to reactionaries. I'm curious about your other point, about what's coming on, as you say it bears little resemblance to liberal and conservative cathegories. I'd say though there is a quite strong reactionary component though, somehow revalued, because they think the Islam radicalization is an effect of the liberal society, but Islam is also feared because of being a sexist, non secularized political religion, which also Christianity used to be. Islam immigrants though used to be more light in their faith and more secularized. Imho the sjw degeneration is an effect of the path chosen by the political left, when it has been coopted by the establishment, which always was at its vertices to an extend. Such degeneration has watered down the economical and exploitative aspect of society, focusing on welfare and the (rightly due, though) civil rights. They also romanticized the immigration, doing little to address the exploitative component of using the to devalue the workforce. Because yes melting pot is a nice concept but not without a project, a sense of unity for a resistance against exploitation. Then the geopolitical aspects of aggression, war, destablization of middle east, further fed the anti western sentiment.--78.15.232.220 ([User talk:78.15.232.220|talk]]) 16:20, 23 April 2017 (UTC)
- Look at Macron, for example, from "a fringe left" party in France, where the center supposedly has collapsed. He's running on cutting the corporate tax rate and reducing public sector jobs. That sounds like Trump or Reagan that French socialists are voting for. Then in the US, you have extreme Tea Partiers voting to protect Obamacare and rejecting Trumpism.
- Politically speaking, these are not a reversal of roles, these are new crossover coalitions being formed. But underneath it all, there are ideological shifts, 'cause frankly, nobody believes or adheres to the old ideologies anymore. The brlief systems have either been discredited or proven ineffective.
- I spent much of today listening to a Jewish lawyer defending the Daily Stormer on free speech grounds in a lawsuit brought by the SPLC. To sum it up, Daily Stormer did exactly what others groups have done to Milo Yankovich, Ann Coulter, David Horowitz, Bill O'Reiily and a host of others.
- As these ideological shifts are crystallizing (which can happen overnight or over decades), some people may want to define themselves by their percieved enemies. IMO, this not only is a weak basis for a new ideology, it can overlook the fact everyone's belief system is in flux. These are the people and groups most prone to violence out of anger cause their world is turned upside down.
- So how do you soothe the anxieties of people who feel left behind economically or as the result of an election? By stoking their fears and prejudices? nobs 00:05, 24 April 2017 (UTC)
- You don't. Or rather, nobody does. Or we elect a demagogue. Gaul Dernitt (talk) 07:52, 24 April 2017 (UTC)
- Macron fringe left? He is considered a "center" independent, secular and liberal, he has some area of public spending if I got it right. Melenchon is considered like this, probably being just social democrat :). For your examples I think about confusion and disorientation, but it's true. As the traditional parties "betray". The recurring appeal to free speech is some times paradoxical, from people not granting the right to exist of some people ^_^. Especially if it comes in the form of complaint, I mean, I suppose people can advocate killing blacks, etc. but it's not paradoxical, they would grant them free speech when they are killing them. It's an example. Yeah, also Yiannopoulos advocating the worst homophobes against the threat of Islam, I suppose. But I call it confusion if one person criticizes, rightly, Islam for being regressive and reactionary, holding to old prescriptive gender roles and the votes regressive and reactionaries, because liberalism is somehow at fault. But same goes I learned, for the left, I'm Italian and the same people, who, like me, adversed Berlusconi and his power abuses, cutting the art.18 of workers statute (on firing without just cause), demonstration all around. The Renzi came, nominally "left", he approved the Jobs act, no nig national demonstration or strikes. So I guess most of them were just "faction driven".--78.15.232.220 (talk) 20:41, 24 April 2017 (UTC)
- Thankn you for your outside insight (that's a little oxymoronic phrase that I thought I'd lodge in place of an emojii) It's always a tough sell when tasked with a counterargument. Even tougher when your practical representatives live on couunterarguments. Yiannopolous had to make enemies. That was his character's point. He was also sad scum, never gave a thought to the counterargument itself, but faction drive deserves consideration because of its potential power. Because factions sometimes want a shift more than they want centrism, but rarely have comprehensive plans. Still, I think we should progress, and I can't blame progressive Trump voters for voting, but I can blame them for not using Google to even it's least extent. Being said, I'm right there with everybody on the wrong side, because history means all of us, so if anybody has any bright ideas...Gaul Dernitt (talk) 07:28, 25 April 2017 (UTC)
- A problem today is too many groups like Antifa, the Salafis, and few right-wing groups hold as a basic premise that unless you think like me or agree with me, you must be an infidel fascist commie worthy of death. This sort of thinking is the cornerstone of totalitarianism. nobs 02:34, 26 April 2017 (UTC)
- Well, yeah. But I thought you were the totalianist? Is that a word, why isn't anybody fighting my fights for me? Jokes aside, the left is almost as dumb as the right anymore, sure, but Gamergate died because it made no sense. The point that anybody cared about a video game developer's fidelity and then gaming 'journalism' accounting for more than pointless hype, the people who criticize that live outside of it, man. You mean to say Nintendo Power was honest, and I'm responsible for disliking any game that got a good review? Gamergate was defeated because it was an overreaction to nothing. Antifa is fun for angry kids. I'd have done it. Salafis, okay, I'm lost on that. I'll try and figure it out, but that's because of you, nobs, not the argument itself.
Never considered it, don't even know what you mean, really. But the problem of groupthink won't get solved very quickly, it will only get solved thoroughly. Which is an oxymoronic plan. Crap. Gaul Dernitt (talk) 06:14, 26 April 2017 (UTC)
Results from the Limerick Contest[edit])
- I didn't get first place? This contest is rigged!-Donald Trump 06:46, 22 April 2017 (UTC)
I think a link to the Limerick Generator should be added somewhere on mainspace.--Кřěĵ (ṫåɬк) 03:09, 26 April 2017 (UTC)
Stupid question[edit][edit])
Fuck 'em. Theresa May (talk) 20:59, 21 April 2017 (UTC)
- Isle of Man (famous for three-legged logo and tail-less cats), Berwick upon Tweed - supposedly persisted in the Crimean War until some 'municipal jolly settling the matter' in the 1960s, Rockall - occasionally visited, Gruinard Island (better known by another name), and 'subjects of the Duke of Normandy' (including the Minquiers and occasionally invaded Ecrehous Islands). 86.146.100.38 (talk) 22:02, 22 April 2017 (UTC)
- lets not forget Pimlico is Independent Nation AMassiveGay (talk) 08:55, 26 April 2017 (UTC)
Everythings flipped[edit]
Donald Trump is cause of the collapse of Western civilization and the anti-Trump crowd is being called upon to defend and preserve traditional values. nobs 05:13, 22 April 2017 (UTC)
- Do you believe your premise? Gaul Dernitt (talk) 08:25, 22 April 2017 (UTC)
- I'm more inclined to the conclusion. Trump, Le Pen, Putin (and Hillary, too} is symptomatic of the problem, not the cause. But what comes next is something to worry about. What's equally or more worrying, is young people, whose world this is seem unconcerned about it.
- I'm not a big fan of Stephen Molyneux, but today he spoke along the same lines after the Paris attacks, and I shocked myself at being rivetted to every word. Two of these alarm bells the same day, one before one after Paris, is too more than coinicidence. nobs
- The only thing that is being "squandered" is the rather recent achievements of 20th century western liberals. For most of those thousands of years of European history, your average person (along with many noble people) lived short, brutish lives under cruel autocracies. In the US, our liberty was bought with the blood of our own mixed with the blood of these very same autocrats. But we were only marginally better, enslaving an entire other race for economic gain. Trying to look to the past to find liberalism and enlightenment is like looking to a wolf den for philosophy.
- Economic strife mixed with civil strife is putting a strain on democracy, due to democracy's natural inability to respond to these kind of crises quickly and decisively. So just as in the 1930s, we are given a choice- so we want to be perfectly safe and economically secure, or do we want to be free? We were told the same thing by illiberals back then. "Give power to [Insert Fascist Here] and you won't have to choose, they will ensure your freedom while taking care of the 'problem'." It is a cruel deception, and one that ignores the very essence of classical liberalism, because if only some privileged classes have freedom, no one really does. If we give them the avenue to revoke freedom, it will always be revoked. Europe realized this cruel deception too late last time.
- And we're quickly seeing this same issue play out now, aren't we? Luckily we have a fair number of controls in the US to keep Trump's tyrannical ambitions in check, for now. But him complaining about the judges and an entire branch of government is quite telling. He doesn't understand what a President is for, because he doesn't remember under one that was truly great and was restrained by the actual duties of the office (really, we haven't had a true President since Andrew cocklord Jackson). Le Pen is talking about stripping citizenship away from people who born in the country. So much for liberty and fraternity, eh? Sure, you may be free now, until we decide that certain people born in the country are no longer citizens. Scroll down to the comments of that Molyneux video and you get a heavy dose of where this train of thought naturally leads to- not being protected "bloodlessly and without suffering", but ultimately to people openly clamoring for autocracy and genocide because of scary brown people. This is what you REALLY get with Le Pen, Trump, et al, not some kind of bloodless rebuilding of "civilization" and peace, security, and freedom all at the same time. You may get peace and security, but only at the very high cost of your personal liberties.
- What is truly disturbing to me is that people seem blind to the obvious machinations of it all. There's no reason to construct some elaborate theory about what happened here. A radical Muslim shot a police officer in the most famous part of Paris three days for an election. Is that because they loved Macron or Fillon? Maybe they want people to vote for Melenchon! No, obviously they are doing it to try and get people to vote for Le Pen, because that's exactly what they want. They want more war, more conflict, and to force the Muslims who were born and Europe to make a choice between them on Little Miss Petain. Just as "striking back" for "justice" against the terrorists after 9/11 did not change anything or make anyone more safe. As for the younger people, I guess I may fall in that category... I grew up with 9/11 burned into my psyche. I only have vague memories of a time before we started fighting terrorists, using the same tactics against the same enemies with the same results. The executives under Bush and Obama trying to consolidate more power and overstep in order to keep us "safe". Trump and Le Pen and whatever nouveau-fasciste coming down the pipeline will not reverse this trend, they will not keep me safe because the last 3 Presidents I remember were unable to keep me fully safe from harm. Because it turns out the government can't actually really do that. Is it necessary to live in a democracy? I'll let you know when I actually live in one.
- That turned into an essay but it's good to get it out sometimes. Hentropy (talk) 16:39, 22 April 2017 (UTC)
- Well thought out response, but I have to differ on some points regarding the 1930s. No, the defeat of fascism in Europe, which France was incapable of, did not make people free. Yes, America'a war effort was billed as such, but it failed in its objectives. 350 million people found themselves enslaved after 1945 - that's what a half century Cold War was all about. So I don't see where the parallels hold up other than a rallying call to oppose Trump - albeit on flawed premises.
- My arguement is the situation would not be much different with Hillary Clinton right now. Probably worse - because we'd have to endure another 8 years of an ignorant lovefest between media, Hollywood, and the White House while the whole the world and everything we treasure burns - which isn't the prime cause of our problems, but certainly made things more difficult.
- Hiding from problems doesn't fix them - Reagan was accused of that. I'm grateful people are being forced to confront reality, it's an imperfect world, and there are real dangerous threats in it. And Donald Trump is not the cause of these problems. Trump, populism, nativism - love it or hate any of them - forces people to get out of their "unaware and compliant" mode and get engaged. Information and education are key. And barking after Trump serves no purpose whatsoever to confront these real problems that Trump has taken off the back burner. nobs 19:22, 22 April 2017 (UTC)
- Strangely enough, I would actually agree on pretty much all of these points. I would never suggest that simply winning WWII made everyone free. It was mostly just the prosperity gained in the US that led to a steady expansion of liberalism, and then us using that as a geopolitical strategy to oppose to Soviets. I would also agree that things wouldn't be much different under Hillary... in fact they could be worse. It's become clear to me that the only way people will sour on this form of populism or nationalism is if they jump headfirst into it, or if they're lucky, see another country dive headfirst into and see how it goes. Delaying it longer with another relic like Hillary was only going to make people more hungry.
- And I don't even think Trump is that bad, I don't think he's stupid but I think it's clear he has no clear or coherent political ideology. It's rather easy to abandon principles you never really had in the first place. No deep state brainwashing or blackmailing needed. Le Pen and AfD and all these other opportunists in Europe are more troubling, these are not incoherent populists with no principles or ideologies, they are actively looking to erode the foundations of peace and cooperation in Europe that has prevented them from slipping back into their neverending, bloody pissing contests all because the last 10 years or so has kinda been shit for the economy and politics. Hentropy (talk) 06:33, 23 April 2017 (UTC)
- Don't forget Putin, tho. Even relations between Merkel & Putin (Iran, too) are not as strained as the US IC & Putin. The EU is a creation of US hegemony. We may be looking at an Right-wing Euro-slavic alliance, less all the racism it's been known for in the past, making Russia an equal partner, rather than a dominant bogeyman that was feared under the Soviet system. nobs 07:49, 23 April 2017 (UTC)
- Economic powerhouses matter. Moreso than military powers, or so India would think. So the problem has always been Globalism and the fallout of imperialism, but imperial military is not as valuable as it used to be. Hence the US, Russia, North Korea panic. North Korea shouldn't even be in the game. Hell, at this point I gotta give ISIS some credit, throwing bodies at the problem objectively doesn't work anymore, but I guess they are willing to play it to the hilt? Not a morality assessment here. Gaul Dernitt (talk) 06:59, 26 April 2017 (UTC)
Attention Span Article?[edit]
Not sure if this has crossed anyone's mind...i like fish...I mean, I was just presented with the 12 second attention span argument and I did some brief googling but the whole thing seems crazy subjective. Anyone else like fish? Err...I mean, anyone given this one any thought? Gadzooks (talk) 23:22, 24 April 2017 (UTC).
- See my source here. I don't think our attention spans shortening is necessarily a bad thing, nor do I think that we really need an article on it (it isn't exactly missional). However, if you or others think it's a good idea, write away my friend. Meh (You) 23:40, 24 April 2017 (UTC)
- This sounds like Nazi science. Dehumanizes us comparing us to fish bait. nobs 04:20, 26 April 2017 (UTC)
- Is it 'attention span' or 'how long it takes us to decide something is neither a threat nor interesting enough to pursue' (so part of a more complex process)? 86.146.100.79 (talk) 12:58, 26 April 2017 (UTC)
- Nobs, I don't think it's dehumanising to compare our attention spans to that of a goldfish. I make no claims, the article makes no claims, and the researchers make no claims that we are less human because we have a half-second less of an attention span than a goldfish. To claim that it is dehumanising is, at best, a claim that has little to no basis in reality. #Can'tComeUpWithACleverSignature 01:48, 27 April 2017 (UTC)
- C'mon now. You ever see a goldfish build the Eifel Tower? or the International Space Station? or a cure for polio? nobs 08:09, 27 April 2017 (UTC)
- Nobs that's a nonsense answer haha. No one's making the claim that goldfish could build the Eiffel Tower, the ISS, or create a polio vaccine. Furthermore, the only thing that was compared was the attention spans of goldfish and mankind, not their respective capacities for rational thought, their abilities to do science, or even their capacity for thought in general. To compare goldfish and humanity in terms of achievement is to compare a fishbowl to the world. #Can'tComeUpWithACleverSignature 13:04, 27 April 2017 (UTC)
- chill the fuck out nobs. Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 17:42, 27 April 2017 (UTC)
Bright Ideas[edit]
Let's bleach enema everybody until autism ducks it's ugly head into whatever wormy corner it came out from.
Being American is a right, defined by ladder building or rope knitting. Knotting, by dammit cost or spell check be fuddled, ha! build some kinda wall! Gaul Dernitt (talk) 08:28, 25 April 2017 (UTC)
- So, basically come up with the most insane, frothing idea possible and present it here? RoninMacbeth (talk) 15:11, 25 April 2017 (UTC)
- Been tried. Sometimes it catches on. Sometimes it flops. nobs 04:08, 26 April 2017 (UTC)
- Still not convinced. Defeat weight gain via gluten with rice and potatoes and corn. Okay, fine, I give up. Gaul Dernitt (talk) 05:42, 26 April 2017 (UTC)
- Uh shit...Hit yourself in any random body part with something that has sharp edges. Fuck it. Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 15:16, 26 April 2017 (UTC)
- Sacrifice sheep to the Goat good, and then use the juices to put in school lunches in order to make children infinitely smarter. Genius! RoninMacbeth (talk) 15:19, 26 April 2017 (UTC)
- Get the government to fund your live-streamed sheep sacrifices to immerse the masses. Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 15:39, 26 April 2017 (UTC)
- Just the government? How about the government, the Illuminati, and the secret reptoid overlords fund the sacrifices. Stop discriminating against our shadow rulers, Zexcoiler! RoninMacbeth (talk) 15:48, 26 April 2017 (UTC)
- I don't need no steenkin' Illuminati! Fuck, let's revive the Mayans and Aztecs so they can do it. Host the event in stadiums and get Barack HUSSEIN Obama to host the spectacle! Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 16:28, 26 April 2017 (UTC)
- Oh, we left out the Templars and Freemasons! Silly us! Yes, the Aztecs, Maya, Templars, Masons, and the (truly insidious) RW admins will sacrifice the
unsuspecting sheeplesheep to the Great Goat! As a side note, the best way to make people American is to destroy every state that isn't New England or the Pacific coast. That way, only the good parts of America are left! RoninMacbeth (talk) 23:50, 26 April 2017 (UTC)
- Oh no! Not again! nobs 04:14, 27 April 2017 (UTC)
Express.co.uk[edit]
Can we get an article written about this woo-laden 'website'? I've been reading right, and I came across an article there called 'REVEALED: This Large Hadron Collider discovery could REWRITE the laws of physics'. Like. Seriously? They didn't find that. The article doesn't even mention what the title does. All the scientists found (I'm making my inner physics lover cringe by saying all they found was..) was that they could create quark-gluon plasma by colliding protons. Hardly the 'REWRITE THE LAWS OF PHYSICS!!?!?!11?!?!!!1?!1' title that I was expecting. After that, we see articles for the LHC proving ghosts exist and 'super orgasms[sic]' for women. See what I see now? We desperately need an article ripping that publication apart. Meh (You) 18:20, 24 April 2017 (UTC)
- Ooohhhh my bad my bad it's the website of the Daily Express Meh (You) 18:23, 24 April 2017 (UTC)
- Is this site for real?
- Have heard the DE called 'the Daily Fascist.' 31.51.114.96 (talk) 21:49, 24 April 2017 (UTC)
- It competes with the Daily Mail for that "honor." RoninMacbeth (talk) 15:27, 28 April 2017 (UTC)
Issuepedia[edit]
Anybody come across these guys before? From their 'About' section: "Issuepedia is the encyclopedia of issues, analysis, thought, and opinion. As with Wikipedia, anyone can edit; unlike Wikipedia, we encourage opinions and rants as well as carefully considered analysis and purely factual writing." Seems to be active; is it on-mission for us? 197.89.55.35 (talk) 13:54, 27 April 2017 (UTC)
- It isn't active at all: there's only one active editor. Does it deserve an article? Ehh, it's not super missional so I would vote no. #Can'tComeUpWithACleverSignature 15:17, 27 April 2017 (UTC)
- Not active, but has linked from RationalWiki in the Ferguson effect article. Wheeee! I still wouldn't link it though, not unless it's more active than this. --It's-a me, LeftyGreenMario!(Mod) 18:29, 27 April 2017 (UTC)
- I wouldn't link it since it isn't very active.-D1@m0ndD15c1 (talk) 05:41, 28 April 2017 (UTC)
Is Godwin's Law ever invoked in a positive way?[edit]
Suppose there are some white nationalists discussing politics and one of them says, "That sounds just like something Hitler would say!" and the other says, "Yeah, you're right! So I guess that means I'm on the right track, huh?"
Or suppose they're chatting about Donald Trump's proposed Muslim ban, and one of them says, "It sounds like something Hitler would propose!" and the other says, "Yeah, I guess we should vote for Trump again in 2020, huh?"
Would that count as Godwin's Law in action? Men's Rights EXTREMIST (talk) 20:30, 27 April 2017 (UTC)
- it isnt godwins if the hitler comparison is justified. im not convinced its entirely justified with trump. AMassiveGay (talk) 20:37, 27 April 2017 (UTC)
- @MRE, I suppose? Who cares what some random neo Nazi might've once said though? Christopher (talk) 20:41, 27 April 2017 (UTC)
- @AMassiveGay, I always thought Godwin's law only referred to the likelihood of a comparison to Hitler not whether it was valid or not. Christopher (talk) 20:41, 27 April 2017 (UTC)
- Godwin's law applies because it involves the bringing up of Hitler. Also, comparing Hitler to X is a terrible argument because the comparison is most likely made for the shock value. I say just analyze the person at face value and analyze what exactly is wrong with X instead of doing a shallow comparison.—チーズバーガー • めん (talk • stalk) 20:44, 27 April 2017 (UTC)
- I agree that Argumentum ad Hitlerum is almost never valid, I still don't think Godwin's law itself (As an online discussion grows longer, the probability of a comparison involving Nazis or Hitler approaches 1.) Makes any claims as to the validity of a Hitler comparison. Christopher (talk) 20:52, 27 April 2017 (UTC)
- its entirely pointless if the the comparison is valid. Such memes are pointless anyway, but that make it more so. i dont shout 'godwins' at the telly when world at war is on. AMassiveGay (talk) 21:07, 27 April 2017 (UTC)
- Keep in mind that "Godwin's Law" is NOT a value judgement on the validity of Nazi comparisons. Sometimes bringing up Nazis is perfectly relevant. The law, like the "law of gravity" simply describes the inevitability that many political discussions (though even the original coiner was just talking about Heinlein discussions) will eventually careen towards bringing up Nazis, for valid or (often) unvalid reasons. Pointing out Godwin's Law whenever someone brings up Nazis is like pointing out gravity whenever you drop your pen. In this sense, it cannot be "invoked" positively or negatively, it just is. Hentropy (talk) 22:25, 27 April 2017 (UTC)
- Isn't there a version of it that says, "The first person to bring up Hitler loses the argument"? Men's Rights EXTREMIST (talk) 22:57, 27 April 2017 (UTC)
- The whole Antifa movement is based on Godwin's law. It started in California with some masked "antifascists" macing a Trump rally organizer, all predicated on the notion Trump=Hitler and Trumpsters=fascists, coupled with the idea "I'm gonna hit 'em first before they start killing people." Then the Trumpsters get organised ready to respond to violence, and soon the streets of Berkley look like the streets of Berlin in 1919 or Munich in 1923.
- Who's right and who's wrong? It doesn't matter when you're dead (especially if you're an atheist). As my father used to say, "If you go looking for a fight, don't be surprised if you find one." nobs 23:15, 27 April 2017 (UTC)
- @Men's Rights EXTREMIST No, and even if there were, it doesn't change the fact it's a shitty argument.—チーズバーガー • めん (talk • stalk) 23:17, 27 April 2017 (UTC)
- That's how people chose to interpret it over time. Godwin's Law became a way for people to point out how often people jump to Nazis in the most irrelevant contexts, so people started to "invoke" it as a way to encourage people not to talk about Nazis when talking about stuff that has nothing to do with them. But in reality the Nazis (and some might say Stalin's USSR) were examples of the worst regimes in the modern history, the epitome of what not to do, which is actually quite useful when talking about politics. Cautionary tales and showing "what not to do" are very useful things whether you're talking about politics, life, chess, etc. Hentropy (talk) 23:20, 27 April 2017 (UTC)
- It needs to be used carefully and well sourced (I would suggest not using it at all to make comparisons). A young person, who never heard of Hitler & the Nazi's, could come away believing "well, Hitler must not have been that bad" once the fallacious basis of the argument is exposed. "What else did they say about Hitler and Donald Trump that was not true?" That's the impression young minds can pick up. nobs 23:33, 27 April 2017 (UTC)
- I think that's a good point actually, talking about issues like Nazism, slavery, colonialism, etc. in only the most simplest terms often gives people a false impression, and when they get older and find out that Hitler wasn't some cartoon character, they lose trust. Talking more broadly about the politics of dehumanization and how it has played a role in history, both far back to the present, is more important to properly connect the lesson. Hentropy (talk) 23:51, 27 April 2017 (UTC)
- Yes, Godwin's law has obvious applications: if you make a serious argument centering around the word "feminazi" or seriously have disdain for a discussion of grammar calling people "Grammar Nazis", you've probably fallen into the easy trap of viewing people who are just slightly meaner than you like as Nazis. People advocating for an authoritarian ethnostate are the one exception. ikanreed 🐐Bleat at me 14:53, 28 April 2017 (UTC)
Appeals to motive on Wikipedia[edit]
I might as well post here, because if you post any kind of criticism of Wikipedia, on Wikipedia, they'll say, "Oh, what's this criticism based off of? What kind of petty dispute, in which you were probably the one in the wrong, are you passively-aggressively trying to make a point about? If you don't like how we run things on Wikipedia, the door's that way," etc., etc. You pretty much have to post outside of Wikipedia, to have any kind of reasonable discussion about it, because the regulars tend to want to circle the wagons and present a united front against any critic in their midst.
As the New Agers would say, they can't get outside of their egos. They'll greet any criticism with, "Oh, so you think you can come here and give us some brilliant insight we never thought of before? You got a lot to learn, buddy. Please read these 500 pages of policies, guidelines, and essays, so you can better understand the wisdom that we've developed since 2001, making minor tweaks once in awhile, to the point where now it's so close to perfection that it's inconceivable that any major overhaul would ever be warranted."
Any successful organization, whose founding represented a revolutionary step forward, will tend to view its policies as holy Scripture, and its culture as the best that could possibly exist. Look at America. They say, "Our Constitution is already perfect; don't fuck with it!" and "We have this great culture of guns, baseball, and apple pie that is very wholesome, nurturing, and good. If you don't like our culture, then leave."
Or it's like if you approach a creationist with some of Dawkins' arguments. They'll say, "Read The Evolution Handbook and then we'll discuss further. You'll find that a lot of your arguments have already been addressed. What, you think you're the first person to point out the genetic similarities between humans and apes? The creationist community consists of serious scholars who have studied the evidence and devoted their lives to developing a comprehensive body of work refuting all counterclaims. This is a religion that has stood the test of time and been embraced by very intelligent people around the world. You have a lot to learn."
One thing I think is a flaw in Wikipedia culture is their constant use of appeals to motive. It's even implicit in the "assume good faith" guideline that you should be thinking about other users' motives. It says, "Avoid accusing other editors of bad faith without clear evidence in the form of diffs along with the deformed, resultant edit." Why not just say, "Avoid accusing other editors of bad faith," period?
It's not always necessary in life to judge what people's motives are. In criminal court, the intent is what matters; even if you do no harm, you can be sent to jail for making an attempt, while on the other hand, if you do harm, you can escape punishment by showing your behavior was inadvertent and not negligent. In civil court, intent doesn't matter at all; if you caused harm, then you pay damages, but if you didn't cause harm, then you don't pay damages, even if your intent was bad. Whenever possible, it's good to get away from principles inspired by the highly politicized criminal justice system, and instead use principles inspired by the common law.
It very often happens on Wikipedia that someone will write an article that isn't up to standards, and they'll start attacking the contributor's motives. "You're a spammer," "You're trying to disparage the subject of the article," "You're trying to shoehorn in stuff that will further your agenda," etc. Usually the editor will respond, "No, that's not what I'm trying to do; that's not what my motive is," when really, maybe he should be saying, "Neither of us can prove beyond a shadow of a doubt what my motives are or aren't, but they're irrelevant anyway; let's just discuss what the rules have to say about this kind of content."
The accuser will often try to put himself in a superior position to comment on the matter by saying, "I'm not affiliated with the article's subject, although who knows about YOU. I'm only commenting because I want to keep the encyclopedia neutral. I have a long standing in this community, which I could not have achieved if I were biased; what about YOU?"
That's like if a senior executive at Fox News were to say to an intern, "I've worked for 20 years at this company, which provides fair and balanced coverage. I could not have achieved that without actually being fair and balanced. What about YOU, newcomer? If you're going to criticize me, it means that either you have some underhanded agenda of wanting to introduce bias into the news, or you have a lot to learn."
We're at a point now where the paid editors feel they have to operate in the shadows, and where anyone with credentials feels like they have to hide those credentials, lest people accuse them of having a conflict of interest. Paid editors these days usually hire a bunch of meatpuppets in order the help them fly under the radar. Everyone prefers it this way, because it would be bad for Wikipedia's reputation to admit that a lot of articles are written by paid editors, yet those editors are responsible for quite a lot of content, so they're a necessary evil, given the declining rates of volunteer edits, and the fact that volunteers often have their own undisclosed axes to grind.
There are a lot of users with "bad" intent who nonetheless add good content, and a lot of users with "good" intent who nonetheless add bad content, so intent is kinda irrelevant. It just becomes relevant because people will shriek, "You let this person, who admits their bias, edit articles pertaining to the area that they're biased in? How is that compatible with neutrality?" So instead we have people who don't admit their bias, but still have a bias, edit those articles under the cloak of anonymity.
Yet I can't say any of this on Wikipedia, because they'll say, "Oh, you must be one of these biased users who's trying to corrupt our encyclopedia, or you wouldn't be saying this" which is yet another appeal to motive. They just can never stop with the appeals to motive, even in meta-conversations about appeals to motive. Men's Rights EXTREMIST (talk) 20:01, 28 April 2017 (UTC)
- Your username is the perfect punchline there - David Gerard (talk) 22:21, 28 April 2017 (UTC)
Calling Old-Timers[edit]
When did I/P start? I'm planning on adding a chronicle of it on the timeline page. RoninMacbeth (talk) 21:53, 24 April 2017 (UTC)
- That's an old timer thing? It seems like it started after I got here. ikanreed 🐐Bleat at me 15:43, 27 April 2017 (UTC)
- By my standards, yes. I got here in November, and IIRC, it was only dying out when I got here. And even now, people try to preemptively stop its revival. RoninMacbeth (talk) 15:47, 27 April 2017 (UTC)
- I'd say "mona's regdate"(August '15), not because Mona is the only "combatant" who was obstinate and obtuse, but because they managed to take the opposite position of the other obstinate and obtuse people involved who were already here. The irony of it quickly breaking down into a "No, they started it" endless chicken coop was probably not lost on most other editors. ikanreed 🐐Bleat at me 15:52, 27 April 2017 (UTC)
- Ikanreed's right. The I/P crap started back in August. I don't know when it actually started precisely, but I do distinctly recall it having started after Mona's August 15 registration. I think it started with a source of her's called Electronic Intifada or something along those lines. Maybe that's how it started. Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 21:30, 27 April 2017 (UTC)
- I never once took part in the I/P shitstorm on any side, nor would I qualify as an "old timer" by any metric... Regardless, I'd wager that one of the conveniences of using Mona's regdate, rise, fall and LANCB as one of your reference points for said timeline is that unlike some users — said without fingerwagging, of course — she atleast did not register herself an army of sockpuppets, AFAIK. In other words, Mona the person and Mona the account appears to have had something like a 1:1 ratio of activity at RW — which might prove useful to any supposed chronicler, I suppose. Reverend Black Percy (talk) 09:47, 29 April 2017 (UTC)
Thoughts on cooperatives ?[edit]
Bernie and Corbyn (and Mélenchon also, but I'm going to pretend he never existed, as I'm starting to believe it's impossible for the left to win any election) both want to support cooperatives (for exemple, Bernie tried to pass à Bill to create an employee ownership Bank to give loans to people who want to create worker's cooperatives or workers who want to but their company). What do you guys think about it ? Diacelium (talk) 15:28, 25 April 2017 (UTC)
- My version of democratic socialism is based not on government control of the economy, but on the belief that employees should have the ultimate decision making power in the company, as the current corporate structure is fundamentally authoritarian. In a cooperative, the main goal is not the enrichment of a small elite of shareholders and executives, but instead rewarding the fruits of the labor of the employees back to the employees. I also feel like it will prevent humans from becoming obsolete due to automation, as workers will not vote to replace a significant amount of themselves with robots. Therefore, I wholeheartedly support cooperatives and their expansion. 184.88.254.182 (talk) 23:35, 25 April 2017 (UTC)
- Co-ops are commie crap. When will u gīz ever learn? nobs 04:15, 26 April 2017 (UTC)
- Hate to say it but, *gulps* I kind of support nobs on this. There, I said it. RoninMacbeth (talk) 04:21, 26 April 2017 (UTC)
- So, in the end, Bernie is actually a commie ? After all this time spent explaining he isn't ? Diacelium (talk) 07:42, 26 April 2017 (UTC)
- I eat bait. Does that make me worse than some dumb fish? Don't know, don't care, I will fight that fish. Of course support of communes or co opts doesn't make you a communist, it makes you a pluralist. Unless you only support communes and don't need votes. But communes aren't inherently bad, even if impractical, and in the US they're generally populated by democratic self-actualizing adults. Pretty useless voting bloc, if you run the numbers Gaul Dernitt (talk) 08:44, 26 April 2017 (UTC)
- Im not sure what the OPs question is. Co-ops have existed for years and they are all other the place. they are neither new nor particularly radical and by all accounts rather successful. AMassiveGay (talk) 09:21, 26 April 2017 (UTC)
- Supporting cooperatives means supporting employee ownership of business, which is the cornerstone of many kinds of socialism. Bernie Sanders said, when he was younger, that he believes that in the long term all big companies should be owned by their workers (not the exact quote but he said something very close). If he supports cooperatives, and if he wants the state to support cooperatives it's probable that he still believes that. Diacelium (talk) 23:06, 26 April 2017 (UTC)
- To make a co-op work, even just for the lifetime of its employees, requires a basic understanding of the capitalist system, which is probably the cause of most co-op failures. First and foremost, it takes money to make money. This it called capitalization. To capitalize a single job in the United States takes about, on the average, $150,000. This can come from only one of two sources: (1) borrowing or debt (what happens when one or more coop members crap out? since they have nothing invested? who is willing to step in and assume another's debt burden as well as their own? it places an added burden on everyone else) or (2) unpaid, or grossly underpaid wages until the co-op hits the break even point.
- And by the nature of its very structure, in all fairness and justice, should a co-op ever survive to be profitable, a member who joined after the start up phase would owe a debt to the surviving members. So it has with it a class system or structure from its very inception. nobs
- That is probably true, but don't most startup businesses fail already regardless of whether they are co-ops or not? That does not address your second point, but it is hard to accept that encouraging the creation of more co-ops would have a greater negative impact on borrowing than the encouragement of more traditional small businesses.
- This does not address your second point, which I consider the more important criticism. The question then is how much stratification in power does a successful cooperative entail, and whether this is more significant than the current system. I believe as a moral axiom that power should be distributed across a society as equally as possible. This is a question of ethics more than economics or political science. That is the goal that I believe we should strive for, and in my opinion, the most important criteria for evaluating possible systems. Do cooperatives best further this goal? I honestly can't say that I know. Samstr (talk) 04:13, 29 April 2017 (UTC)
Sidenote: Melenchon convinced a little less than 1 in 5 to vote "socialist"; Le Pen convinced a little more than 1 in 5 to vote "nationalist". Why do left-wingers always get so nihilistic when they almost succeed? FuzzyCatPotato!™ (talk/stalk) 12:02, 26 April 2017 (UTC)
- He arrived fourth, and I think he won't be a candidate in the next election (his party will probably have a new candidate but I don't think that it'll work). We still have the legislative elections but it doesn't look good either. We'll maybe have a big number of deputies if the Front National wins and implement integral proportional, but that's it (and I don't really want Le Pen to win). Diacelium (talk) 15:03, 26 April 2017 (UTC)
God's good ideas[edit]
As there is a list of errors made by God (I forget the exact title offhand) - perhaps an article on God's good ideas/accidental Good Things/examples of (deity pronoun)'s sense of humour. 86.146.100.79 (talk) 22:03, 26 April 2017 (UTC)
- If we can get enough good examples, then perhaps we can create an article. Maybe like the existence of the North America nebula or God's face appearing in a bird dropping to show its sense of humor. --It's-a me, LeftyGreenMario!(Mod) 00:31, 27 April 2017 (UTC)
- Well I mean, there's tons of good ideas multiple deities have tried to spread, although they aren't exactly unique ones. For example, Jesus tried to promote charity and forgiveness, although I wouldn't dare to venture far enough to claim either of those were "his" ideas... megalodon (talk) 01:16, 27 April 2017 (UTC)
- When you get an article set up, count me in. Just give me a minute or three to think of his good ideas. #Can'tComeUpWithACleverSignature 01:52, 27 April 2017 (UTC)
- If we go with irony we can include slavery or the weird stuff in the "other" ten commandments.--Bob"Life is short and (insert adjective)" 06:34, 27 April 2017 (UTC)
- God created food, dope, and sex. Shouldn't that be enough? nobs 08:03, 27 April 2017 (UTC)
- Pi being exactly 3 would make math class a lot easier. ikanreed 🐐Bleat at me 15:41, 27 April 2017 (UTC)
- For a list of mistakes made by God, flip open a phone book for starters. Trust me, I'm a Reverend. These things happen. Reverend Black Percy (talk) 10:03, 29 April 2017 (UTC)
Damn, who is this guy?[edit]
Did I just piss off a cheerleader's boyfriend, or did I stumble upon one of Andy's homeschoolers? If it's the former, I'm sure she's a lovely lady, no malice was intended. All I did was add some content to an aricle, with some snark, and I got hardblocked by JorisEnter. No warning or anything, just BOOM. Retired Old Guard (talk) 15:19, 29 April 2017 (UTC)
- I agree the block wasn't warranted. Christopher (talk) 15:26, 29 April 2017 (UTC)
- Regardless of if the block was warranted or not, allow me to provide you with the following protip: don't blow a gasket. These things happen. And as such — any supposed assumption of intentional malice on the part of Joris would be fallacious in and of itself. Reverend Black Percy (talk) 23:54, 29 April 2017 (UTC)
Jon Rappoport[edit].
—チーズバーガー • めん (talk • stalk):
- —チーズバーガー • めん (talk • stalk).—チーズバーガー • めん (talk • stalk) 02:17, 21 April 2017 (UTC)
- I read his three branches of logic post and it was ... strange. From what I recall of my formal logic class, there are two main branches, inductive and deductive reasoning. (Which produce probable and certain conclusions based on premises respectively.) Samstr (talk) 15:50, 21 April 2017 (UTC)
- Just when you thought he was a lunatic, he comes out with a piece of unqualified genius like today. nobs 02:38, 26 April 2017 (UTC)
Rappoport trashes the homeschoolers. FYO. nobs 22:37, 30 April 2017 (UTC)
Reference[edit]
"Please have specific criticisms"[edit]
The consensus was to keep, with 11 votes for it and none against. Yet it doesn't appear to have been implemented, why not? I can't do it because it's a MediaWiki thing. Christopher (talk) 17:10, 25 April 2017 (UTC)
- I didn't forget about it. That would be absurd. FuzzyCatPotato of the Posh Steak dinners (talk/stalk) 11:57, 26 April 2017 (UTC)
However, openly bigoted comments will probably be removed or {{tl|collapse}}'d.
- If people don't want it, I can nix it. Fuzzy "Cat" Potato, Jr. (talk/stalk) 11:59, 26 April 2017 (UTC)
- I think that as this is mostly aimed at new users it'll just get confusing. I'd remove that line. Christopher (talk) 08:13, 30 April 2017 (UTC)
Anyone else feel like this tweet?[edit]
This one. This one here. I've seriously had this reaction lately. And it bothers me a lot. ikanreed 🐐Bleat at me 15:59, 27 April 2017 (UTC)
- no, but i am in the uk. no one gives a shit here. no one talks about religion - its considered odd if you do. its curious. Stateside, there seems so much scrutiny on the religious credentials of presidential candidate and what church they may attend. Over here, religious belief in an mp is consider not just a liability but an actual threat, thus we get tim farron being asked about the gays on a daily basis. Can you tell from this which country has a separation of state and religion, and which has an established church? AMassiveGay (talk) 16:34, 27 April 2017 (UTC)
- Ever since Romney got nominated and Trump got elected I think one can safely say the people no longer really care that much about churches... all the people who do care are Republican now and won't vote for Democrats no matter what, and even if you had a Satanist or pagan revivalist run for office, so long as they are pro-life evangelical conservatives will vote for them. Even Bernie's religion or lack thereof was never really brought up, but then again he was a COMMIE RED so that takes priority. As for the original point, it certainly does seem to be getting that way, where if I see a "proud" white-dude atheist I start thinking whether or not he's some kind of Sargon-sucking "left libertarian" who loves Trump and hates SJews. Of course, atheists have kinda always had an image problem, with quieter, reasonable atheists always trying to avoid the issue in public. I wasn't sure what you did with that issue in 2007 and I'm not sure what you do with it in 2017. Hentropy (talk) 17:10, 27 April 2017 (UTC)
- Atheists have the same PR problem as anarachists, that they're unprincipled, lawless, rable-rousers spitting in the eye of history, society, and everything that's good and decent. nobs 18:44, 27 April 2017 (UTC)
- Same deal with ex-conservapedia editors, really. ikanreed 🐐Bleat at me 18:54, 27 April 2017 (UTC)
- @hentropy - if someone is going to make their atheism a major part of their identity, it doesnt matter what their politics are they are going to be a prick. atheism is a facile thing to hang an identity on. AMassiveGay (talk) 20:21, 27 April 2017 (UTC)
- Um, not to go #NotAllAtheists. I see where you're coming from, because there's a lot of high-profile atheists in the public eye who are complete assholes (especially the stereotypical fedora atheist), but there are also people like David Silverman of the FFRF who aren't prickish like, say, Dawkins or Hitchens. Maybe the non-asshole atheists base themselves upon humanism or some other trait, so I'm just going out on a limb here. Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 21:23, 27 April 2017 (UTC)
- That's true for any religious or political affiliation really. But it's not just a matter of people who shout it from the rooftops and obnoxiously inject it into everything, but someone's religion is occasionally relevant and you can bring it up in good faith. It used to be that admitting you were an atheist (in the US) was something only certain "enlightened" liberals did, in some ways it's a good thing that it's spreading farther from that narrow group, but unfortunately that means that there's a large contingent of "cultural conservative" atheists who are obsessed with Islam, excuse anything bad a Christian has ever done and waving the Republican/Trump flag. Hentropy (talk) 21:38, 27 April 2017 (UTC)
- In the case of Richard Dawkins, do you think he has become worse over time? Perhaps I'm mistaken, but I recall a time when he was more respectable and seemed to be more even handed in his criticism of religion. Recently he seems to have become more overtly Islamophobic. Perhaps many of these atheists have always had these beliefs, but they feel more comfortable openly sharing them in the current political climate. Samstr (talk) 02:56, 29 April 2017 (UTC)
- In Sweden, atheism is the norm (read: representative of our mainstream values and completely uncontroversial). So, no.
- But we do differentiate between "atheist" and "new atheist" even here. Still, the worst association that new atheism seems to have here is that "Dawkins can be quite shrill" (which I wouldn't really agree he is).
- As for me, steeped in the American context of internet culture... No, still — but I do get the tweet.
- Which atheists have you been reading, Ikan? I highly recommend Aron Ra, Michael Shermer and Richard Carrier (aside from the Hitch, of course) if you don't want to go down the increasingly suspect "Harris/Dawkins"-path. Reverend Black Percy (talk) 10:13, 29 April 2017 (UTC)
- There are many intelligent and thoughtful atheists as well as people like Sam Harris and Richard Dawkins, just like virtually every other category of people. That being said, there are some atheists (especially some of the more vocal ones on the internet such as the amazing atheist) that do make me feel more like identifying with that tweet. The best solution is probably not to recoil from the term, but to actively identify as an atheist while trying to be the most kind and considerate person possible. If enough people do that, then perhaps some negative connotations surrounding the term will start to disappear. Samstr (talk) 02:24, 30 April 2017 (UTC)
- That is, in part, what I try to do for feminism by calling myself a feminist with some consistency. I dunno if it'll work in the long run, but seems to me it's worth a try to not surrender as politically diverse, historically important and fundamentally egalitarian a rallying term as that to any shrill subset of illiberal anti-science cranks — just as one likewise should not fall away from said term and please the reactionary manospherians who wish daily for the entire feminist project (anti-sexism, women's rights, and all) to be declared defunct. It's a complicated issue, to be sure... And the fact is, the term "feminism" without qualifiers is almost meaningless at this point. For anyone to have a clue which feminism I mean for myself, for example, I seriously have to reference like five separate concepts for it to even make basic sense (something, something, sex-positive, analytical, empirical, liberal, etc...). Anyway, speaking of worthwhile non-abrasive atheists, let's not forget A.C. Grayling or Dan Barker as well. Reverend Black Percy (talk) 09:41, 30 April 2017 (UTC)
- I think it's dumb that people are still intolerant of others in the 21st century. My school embraces diversity and people actually want to make it a sanctuary campus even. People shouldn't have to hide who they really are. DanielleD
Question about IQ[edit]
Off the back off Sam Harris's recent conversation with Charles Murray, I have to ask: people with IQ below 70 are considered intellectually disabled, right? Therefore, wouldn't that mean that the average sub-Saharan African is intellectually disabled, seeing as studies have consistently shown the mean IQ of sub-Saharan Africans to be below 70.Levi Ackerman (talk) 16:50, 29 April 2017 (UTC)
- 1) It looks like you're race baiting. 2) You didn't give any evidence to back up your claims other than an interview with a coauthor of the highly dubious book The Bell Curve. 3) IQ does not equal "intelligence"; it's a measure of some types of intelligence and it's biased by the culture that creates it. WP has a better article on this than we do and it discusses some of the culturally-bounded aspects of IQ. Bongolian (talk) 17:05, 29 April 2017 (UTC)
- 1) I am not race bating. 2) The fact that the mean IQ for sub-Saharan African Blacks is 70 did not come up in that interview (between Harris and Murray), which is why, contrary to your insinuation, I didn't use it to back up my claim. 3) Evidence to back up my claim is as follows: The results of the IQ tests are not disputed. It is the arguments and the conclusions to be drawn from them that are. Are they a true marker of intelligence? Are they, as you've said culturally biased? Are they predictive of educational and professional achievements? Are they result of genes, environment, education, culture etc? These are all questions worth asking. But none of them is the question I am asking. I am asking if sub-Saharan Africans are intellectual disabled based on the result of those studies? 4) Try not to assume the very worst about people in future. For all you know, I myself am Black. Levi Ackerman (talk) 17:36, 29 April 2017 (UTC)
- I don't know if your figures are correct or not - but my understanding of IQ tests is that they measure the ability of of people to do IQ tests. So what? Well, that, to an extent makes them a test of education. For example if you are illiterate, or have poor reading skills, you are going to have some problems taking the test. If you have not been educated in some abstract concepts you are going to have problems etc. --Bob"Life is short and (insert adjective)" 17:45, 29 April 2017 (UTC)
- If you give more information about your premises, it's more likely to make people not assume the worst about what you're asking. Framing your proposed conclusion as "the average sub-Saharan African is intellectually disabled", is an oversimplification at best since it ignores what IQ measures, differences in malnutrition rates and education opportunities, and possible measurement biases. The Rushton & Jensen paper you cited is a good one and it does go into these issues in some detail. Bongolian (talk) 20:10, 29 April 2017 (UTC)
- As others have mentioned, IQ tests are not a good way to gauge intelligence. Lord Aeonian (talk) 20:32, 29 April 2017 (UTC)
- Guys, guys, guys... Correct me if I'm wrong, but I'm about 98% certain that Levi's original point here was something along the lines of: it's the IQ test — especially when interpreted in the typical HBD sense — that's (proverbially) retarded; not huge swaths of mankind. Reverend Black Percy (talk) 00:00, 30 April 2017 (UTC)
- It's also entirely possible that the tests prescribed just weren't things that the sample population were good at, like thinking abstractly. For instance, in 1900s America, the mean IQ was around 70. Does this mean that we've gotten smarter? Not necessarily. We've just added factors that increased our ability to score highly on IQ tests. The ability to think critically, the ability to think abstractly, formal education - these are all contributing factors in the mean 30 point rise in sample populations since 1900..
- Finally, a high or low IQ does not measure how well an individual or sample population can do in certain contexts.
#Can'tComeUpWithACleverSignature 01:54, 30 April 2017 (UTC)
- My purely unscientific take is that IQ tests appear to measure numerical, geometrical, and analogical reasoning; and to some extent, test taking skills. But the basic purpose of human intelligence is networking in human societies. Part of it has to do with an arms race between deceivers and those who don't want to be deceived. There are all sorts of intelligence that IQ tests don't test for. Moreover, I find it hard to imagine that these arms races are absent anywhere. - Smerdis of Tlön, LOAD "*", 8, 1. 02:23, 30 April 2017 (UTC)
- One more thing, you don't have an IQ. It's literally a score you received on a particular test, not a personal trait you have like gender or hair color. It's more accurate to say that they scored X. --It's-a me, LeftyGreenMario!(Mod) 02:37, 30 April 2017 (UTC)
- On a previous computer I had a version of Encarta (an encyclopedia program) with a quiz game on it. As a Brit I found a number of the 'easy' questions on history difficult (as they were US orientated) - but the 'difficult' (rest of the world) questions were much easier.
- IQ tests that are calibrated to a particular cultural environment (people in parts of the world will #never# encounter traffic lights or ships etc - and over the past 20 years from 'so what X cannot use a computer' to 'X is peculiar as they cannot use a computer') will reveal some material information about persons and their abilities to understand and interact with the world, and the ways in which they access and manipulate information (most of us have probably not understood one presentation of information but when it is put in another way have no problem). However there are many sorts of intelligence (and why aren't people in Mensa in top postings in business, politics, academe...?) Put 'an urban person who had a high score in an IQ test' and a local in a particular environment and the latter is likely to survive longer. 86.146.99.7 (talk) 13:20, 3 May 2017 (UTC)
Crap, I agree with the Republicans on tax policy...[edit]
...though not the reduction in taxes.
The piece that I've been advocating for a decade now is apparently a central part of Republican proposed tax policy; Destination-based cash flow tax. In it, basically, the taxes are levied on where the revenue is made, not where the company declares its headquarters. So, for example, a car manufacturer has a steel mill in Poland, an auto plant in Germany, and a sales team in France, at each point the company pays the workers 10k, and the car is sold for 40k euros. Which set of workers made the 10k profit? The answer is the part time accountant in Lichtenstein. Under DBCFT, no, the car was sold in France, they have to pay French taxes on their profits.
Interestingly, the Koch brothers are vehemently opposed to it in spite of the Republicans being for it. So it has that stamp of approval, I guess. CorruptUser (talk) 15:43, 30 April 2017 (UTC)
- The Kochs are not mainline Republicans, if such exists anymore, but closer to ideological libertarian Freedom Caucus Republicans. It makes sense that the Kochs would be oppposed to the DBCFT since, a criticism of is that it would be protectionist. Bongolian (talk) 17:43, 30 April 2017 (UTC)
- It isn't really protectionist, even though it does have the result of "subsidizing" exports and taxing imports. The goal is to stop tax evasion. Really, if the company is selling to Your markets, the company made its profit in Your country. CorruptUser (talk) 18:39, 30 April 2017 (UTC)
- Yes, it's not directly protectionist, but it encourages companies to become export-dominated by way of a tax break. Those companies that are import-dependent risk retaliation by way of tariffs from the exporting countries who see the tax break for the other companies as unfair competition. Bongolian (talk) 19:00, 30 April 2017 (UTC)
- And those countries don't add VAT to exports, giving an "unfair" advantage already. CorruptUser (talk) 19:21, 30 April 2017 (UTC)
Revisiting Tragedies[edit]
President Trump raised an interesting point with his Andrew Jackson/Civil War discussion. Which is why I bring up other, similar topics below:
- Why didn't we stop the War of 1812, when Oliver Cromwell and George Washington were clearly angry at it?
- Why didn't President Trump's great friend Frederick Douglass try and stop Jim Crow?
- Why didn't Frederick I Barbarossa try and stop Hitler from seizing power?
- And why didn't Qin Shi Huangdi try and stop Mao from destroying all books in China written prior to his reign?
And last but not least, we need to ask, 'why?' Why did the Holocaust, Holodomor, Cultural Revolution, and Trail of Tears have to happen? Oh, if only Andrew Jackson could tell us. All the best, RoninMacbeth (talk) 15:20, 2 May 2017 (UTC)
- Andrew Jackson would have "stopped" the civil war the same way James Buchanan did, by ignoring the underlying problems and giving the slave-owning states even more undue power in national affairs, all the while perpetuating one of the most grievous crimes in the history of the country in the process. ikanreed 🐐Bleat at me 16:10, 2 May 2017 (UTC)
- That sounds too restrained for Jackson. I assume he'd just burn Boston to the ground. RoninMacbeth (talk) 17:22, 2 May 2017 (UTC)
- Barbarossa failed to stop Hitler because Hitler was being backed by Charlemagne and Wagner. I thought everybody knew... - Smerdis of Tlön, LOAD "*", 8, 1. 18:39, 2 May 2017 (UTC)
- Clearly, Jackson was not that great. He never rose to the level of omnipotent "didit" capability. Bongolian (talk) 02:00, 3 May 2017 (UTC)
- Burn Boston to the ground? He could've burned down all of South Carolina while he was at it. Remember the antebellum nullification crisis? Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 05:10, 3 May 2017 (UTC)
- I think the point Trump is trying to make is Jackson took on the Bourbon Democrats, the monied intersts, the slave holders and establishment. Bourbon Democrats, if it's not too far a stretch, would be like Limousine liberals today. They don't represent the typical redneck backwoods working class hillybilly white trash forgotten common man. nobs 09:08, 3 May 2017 (UTC)
- there you going again assuming trump knows what he is doing, despite all evidence to the contrary. do you spend the day rocking in a corner chanting 'its all part of the plan' over and over? i am unsure if you are delusional or dishonest. it must take so much effort to have to constantly spin self evidently imbecilic statements from that clown everytime he opens his mouth. but hey, at least hes the anti-politicianTM AMassiveGay (talk) 14:25, 3 May 2017 (UTC)
- also, why does every picture of trump i see look like he is about to suck a cock? AMassiveGay (talk) 14:29, 3 May 2017 (UTC)
- Nobs, did you take an American History course? Jackson never took on the Southern slaveholders. In fact, Southerners were about reaching the peak of their influence. The fucker also drove countless Native Americans out of their native homelands, even though the Supreme Court itself told him not to. "John Marshall has made his decision; now let him enforce it." Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 15:03, 3 May 2017 (UTC)
Sam Harris had Charles Murray on his podcast and uh...[edit]
Well they seem to be enjoying each other's company, Sam Harris doesn't actually do much debating or calling out the problems in Murray's work. Here's the link to the podcast, in case anyone's interested. As a bonus, look at our ol' pals at reddit's reaction to it. Hollow (talk) 00:39, 25 April 2017 (UTC)
- Sam Harris has always had sympathy for some nastier libertarian ideas. He has previously admitted that he believes in human biodiversity, wants to repeal the Civil Rights Act, and has recently been a victim of alt-right rhetoric about "free speech." No wonder so many "classical liberals" like Dave Rubin worship at his altar. This is additionally concerning because these ideas are at the foundation of neoreaction (Mencius Moldbug himself said that Murray's work was central to some neoreactionary beliefs), and by supporting these ideas, Sam Harris is making his fanbase sympathetic to neoreaction. Gutza1 (talk) 12:09, 25 April 2017 (UTC)
- The human biodiversity thing should probably go in our article on him if it's true, have you got sources? Christopher (talk) 16:45, 25 April 2017 (UTC)
- Yeah, so this is the type of shit that concerns me about Sam Harris. The typical kneejerking against Harris is unfounded, but here's the twist — kneejerking aside, he's got a growing resumé of legit BS moves. And this is one of those things, it seems to me.
- Harris is at his most reasonable when conversing strictly on topics of philosophy, AFAIK — on metaphysics, theory of mind, theology and free will. His best quotes on those topics are, I think, excellent.
- But the further he strays from those topics, the shakier it all gets, it seems to me. And shit like having Murray on — allegedly without calling the guy on his bull — just comes off as a huge red flag to me. Reverend Black Percy (talk) 09:59, 29 April 2017 (UTC)
- If I got a Bachelors in Philosophy too I hope you'll be my first fan. Although really, it's funny how Sam Harris fans have now flocked to Murray arguing he's misunderstood and maligned by the 'regressive leftists'. If only they just read The Bell Curve and listened to Sam they'd understand!!! It's not really racist! They're Just Asking Questions! Why do you hate science??? Hollow (talk) 23:25, 1 May 2017 (UTC)
- I consider Harris a crank and more of just an entertainer than a legitimate scientist or philosopher, he's always associated himself with extreme and dubious ideas such as Ray Kurzweil and transhumanism as well, his philosophy is basically just vanilla scientific utilitarianism / social Darwinism which has fascist undertones.--BrittanyPBone (talk) 03:23, 4 May 2017 (UTC)
Here's to being part of the 2%[edit]
Who ."
Cheers! Parrrley 13:30, 3 May 2017 (UTC)
- I'm sure they used very rigorous methods to determine that 2% figure. (For those without access to Google, here's a link to what Koidevelopment is referring to). Christopher (talk) 15:11, 3 May 2017 (UTC)
- My favourite Scientology thing is that I got caught by one when I was out and they gave me a pamphlet that had a questionnaire in it for me to fill out and send back so they could tell me how much money I need to pay them to be free of Thetans. But the pamphlet wasn't freepost or anything, I had to supply the envelope and a stamp. That made me chuckle. X Stickman (talk) 19:42, 3 May 2017 (UTC)
In a nutshell[edit]
This is what Scientologists actually believe. Reverend Black Percy (talk) 10:12, 4 May 2017 (UTC)
Have you seen so much hatred to Einstein in this generation?[edit]
That amount of hatred towards Einstein really disgusts me as as far as I know, and I'm not a physicist, Einstein's theories are well grounded in physics and considered so reinforced, so that it is very much "closed". Theoretically, even if Einstein mainly just confirmed or synthesized existing ideas, still his contribution in confirming and unifying these ideas in such complex fields of study would be most valuable and honorable (I would not be surprised, as a non-physicist, to discover that these people lie and he had some major original contributions of his own and I really don't want to talk on a subject I am not enough knowledgeable in). Comostas (talk) 23:14, 3 May 2017 (UTC)
- Video description calls Einstein a plagiarist, communist, Zionist and a fraud. He is a constructed myth." I suspect the video is just fringe anti-Semitic poo-slinging and for Neo-Nazi poo slingers. I also think it's disgusting such things like this even exist. --It's-a me, LeftyGreenMario!(Mod) 23:19, 3 May 2017 (UTC)
- Einstein is the reason we have the theory of relativity. By the age of 24, he had published not one, not two, but four papers that helped revolutionise physics. Parrrley 23:41, 3 May 2017 (UTC)
- I take sensationalist criticism like that as the speaker playing iconoclasm to get attention, or as Lefty pointed out, anti-semitic in intent. I'm all for taking a critical eye to influential historical figures and keeping them from being mythologized, but things like that video smack of desperation and pettiness. 71.188.73.196 (talk) 00:01, 4 May 2017 (UTC)
Einstein bashing is nothing new[edit]
Here's a brilliant talk from one of my favorite philosophy lecturers of all time, Steven Gimbel.
Truly an engaging (and funny) lecturer. I have some of his courses in audiobook format, and he's a real expert.
Topics touched upon in the above video include: the first world war, Descartes, Galileo, Newton (who was actually a bit of an intelligent falling proponent), the Nobel disease, cosmopolitanism, ethnic/religious minority, the Catholic Church, Judaism,...
Just go for it. Great talk from an awesome professor. Reverend Black Percy (talk) 10:05, 4 May 2017 (UTC)
This comment chain was funny.[edit]
--Godonaldgo1 (talk) 02:38, 5 May 2017 (UTC)
- Reminds me of a friend of mine who is well informed but decides to troll for the lulz. —Oh colors! (speak, speak) Look at what I've done 20:54, 5 May 2017 (UTC)
Thoughts on Religious Companies?[edit]
Today my mother came to visit me on campus. We went downtown and ended up stopping at a frozen yogurt place called Sweet FROG. Despite the mascot that appeared next to the name, FROG did not refer to the animal, but rather an acronym, "Fully Rely on God". This was accompanied by Christian rock and a number of prominently displayed posters with Bible verses. My mother seemed more bothered by it than I was, expressing concern that it could alienate or offend people of other religions who enter the establishment not knowing of its religious message. I can understand this perspective, but I don't feel particularly bothered by such messaging unless I know that money I spend at the establishment will be used to further political causes I disagree with or find morally abhorrent, such as Chick-fil-A's association with anti-LGBT organizations. Am I wrong in expressing this sentiment? Should I be opposed to private businesses including blatant religious branding? Samstr (talk) 02:45, 30 April 2017 (UTC)
- I don't see the issue. They can do what they want. You don't have to spend there if you don't want. The "shut down speech that offends us" can easily be used against atheists, and usually is. Lord Aeonian (talk) 06:16, 30 April 2017 (UTC)
- It can get problematic if they hide who's behind it (like Hare Krishna restaurants) or if they're behind negative social impacts like attempting to defund innocent bystanders' healthcare (like Hobby Lobby). In the US, it's kind of awful since everybody gives religions a total tax break for not real social benefit (no property taxes no clergy salary taxes), we're more-or-less subsidizing them and they're business wings even though the businesses (are supposed to) pay taxes. On the plus side, some of these outfits dilute their own religion by putting Bible verses on napkins and such (formerly Alaska Airlines, and still
In-N-Out UrgeIn-N-Out Burger). Bongolian (talk) 07:07, 30 April 2017 (UTC)
- If their treatment of their employees is in accord with the Sermon on the Mount, I wouldn't care about their politics or theology. Somehow I suspect that hamburger and fried chicken chains do not. - Smerdis of Tlön, LOAD "*", 8, 1. 18:27, 30 April 2017 (UTC)
- My two cents: aside from the obvious givens, like the sanctity of freedom of religion, freedom of speech, the right to assemble and the right to peacefully conduct business... Here's the plain facts:
- Businesses all vary across a spectrum, ranging between more- and less communicative about any supposed ideals.
- Consumers also vary across a similar spectrum, ranging instead from "more informed" to less so.
- It's the moral obligation of the business to be up front with its customers, and likewise, it's the moral obligation of the consumers to stay informed.
- That being said, neither of these obligations are functions of each other. The moral reasons why businesses should communicate with its customers have nothing to do with how informed any given consumer may already be.
- Likewise, the moral reasons why consumers ought to remain constantly vigilant and inquisitive have nothing to do with how well or poorly any given business might have chosen to conduct itself ethically.
- In fact, the reasons both for being informative as a business, and for making sure you find things out as a consumer, is that businesses may not be perfectly up front, nor consumers fully informed.
- It's a question of ethics and rational business sense, no matter if you're the business or the consumer. As such, make sure you conduct all your business rationally and with morals — be you consumer or vendor — and the problem "solves itself", as it were. Reverend Black Percy (talk) 10:07, 30 April 2017 (UTC)
- And if you refuse to eat there becsuse of religion, your guilty of discriminiation, bigotry, snd possibly a hate crime. So you have to find another excuse to pass them up. nobs 22:44, 30 April 2017 (UTC)
- Nobs, you're being loony again. People in the US have the freedom of association: they can choose whom they talk to and whom they patronize; this is why boycotts are generally legal. Businesses that are open to the public on-the-other-hand have not been entirely humanized by the Supreme Court — yet. They are required to serve the public without discrimination as per the Civil Rights Act. I am not a bigot if I don't eat at Chick-fil-A because I think they're a bunch of assclowns. BTW, I do patronize a particular Christian business because, well — convenience, and they haven't made public asses of themselves yet. Bongolian (talk) 05:06, 1 May 2017 (UTC)
- You're right. I forgot. Discrimination and hate crimes only happens to Muslims and Jews, not Christians. Excuse me. nobs 07:38, 1 May 2017 (UTC)
- You can try to hide your real thoughts from nobs by saying something else entirely but he always sees through it. 94.1.140.243 (talk) 14:39, 1 May 2017 (UTC)
- Eh? Christopher (talk) 14:42, 1 May 2017 (UTC)
- If one can't tolerate differing opinions themselves, one shouldn't be telling other people to be more tolerant. I frequently go to Chinese restaurants with Buddha statues, and I don't complain about them being offensive despite being a Christian. I also enjoy an occasional cup of Starbucks coffee, despite the CEO's idiotic comments. If someone can't handle a business owner's culture, he or she should choose to patronize other businesses. 67.238.67.250 (talk) 15:29, 1 May 2017 (UTC)
- I don't think that anyone is saying that the owner of a business being Christian is a problem. There's a problem when the owner discriminates against people because of their religion (because as we all know all Christians are homophobic transphobic racist sexist bigots). Christopher (talk) 15:36, 1 May 2017 (UTC)
- It's no different in hiring and firing. You can never say you refused to hire someone cause they're a woman, you to say cause she un1ualified from lack of experience because she soent too many years rwising children. Or that you fired someone cause they're black; you have to say you fired them cause they were stealing. Then you only have to defend yourself against the claim that the rules against stealing are enforced differently between black and white. nobs 02:59, 2 May 2017 (UTC)
- There's nothing wrong with companys being religious. In fact, I love ChickFilA and Hobby Lobby! But refusing to hire women is just outright being a dick. — Unsigned, by: DanielleD /) 09:13, 6 May 2017 (UTC)
I thought I would let you know[edit]
This site, RationalWiki, has to be the most freaking stupid bunch of nonsense I have seen in a long time. To think you people supposedly align with science... 67.238.67.250 (talk) 15:23, 1 May 2017 (UTC)
- Drink!'Legionwhat do you want from me 15:29, 1 May 2017 (UTC)
- Go ahead and drink, it's your liver. 67.238.67.250 (talk) 15:33, 1 May 2017 (UTC)
- I love idiots who go "My bigoted instincts tell me A, so A must be science, and anyone contradicting me must be anti-science" because you scratch the surface even a little, and you instantly hit a bedrock of ignorance. ikanreed 🐐Bleat at me 15:37, 1 May 2017 (UTC)
- Are we anti science because we promote evilution? How are we anti science? Christopher (talk) 15:42, 1 May 2017 (UTC)
- Supporting evolution or even creationism does not make one anti-science, but creating a website where almost all of the articles take cheap shots at opponents like adolescent siblings engaged in an argument does. The flame wars people here appear to engage in on a regular basis over trivial issues seem to support my theory that this website is operate by middle school students. 67.238.67.250 (talk) 15:54, 1 May 2017 (UTC)
- 1) Example please 2) Even if we did do all that, how does that make us anti science? 3) I would argue that supporting a pseudoscientific idea such as creationism makes you anti science. Christopher (talk) 15:56, 1 May 2017 (UTC)
- 1) Most of the articles, some of the threads on this very page, and anything in the history of the "Chicken Coop" 2) It is anti-science because this website claims to support science, therefore tarnishing the reputation of science. 3) I challenge you to explain how creationism, in itself, attacks science or scientific method. For that matter, I challenge you to define scientific method, in your own words. Narrow minds respecting only the mainstream ideas of the day are the root of the so-called "anti-science movement". 4 [extra credit]) I'm a nurse (as you can see from my IP address and took plenty of science courses in college. Can you say the same? 67.238.67.250 (talk) 16:09, 1 May 2017 (UTC)
- 1) Specific mainspace example please. 2) anti science is defined as rejecting the scientific method and attempting to discredit it, not "tarnishing it's reputation" (which you haven't proved we do) 3 a.) Creationism is a belief that contradicts the conclusions arrived at by using the scientific method, it therefore has to reject the scientific method. That's anti science. 3 b.) Use a bloody dictionary, or Wikipedia 4) One of the most blatant arguments from authority I've ever come across. Christopher (talk) 16:19, 1 May 2017 (UTC)
- There is neither need not space to repeat all the arguments here, but you need to look at Evidence against a recent creation where you will find the scientific evidence you are after.--Bob"Life is short and (insert adjective)" 16:50, 1 May 2017 (UTC)
- I reckon the BoN is gone. No one would take that long to reply to something. Christopher (talk) 16:53, 1 May 2017 (UTC)
- Maybe it's just anti-God (Satan) masquerading as science? nobs 17:13, 1 May 2017 (UTC)
- Any evidence that whatever it is you're talking about (I presume evolution) is the work of Satan? Christopher (talk) 17:25, 1 May 2017 (UTC)
- Ew, looks like the Bon didn't keep their 5th grade notes on the Scientific Method. Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 17:37, 1 May 2017 (UTC)
- Being anti-God (Satan) is cool, and if you joined us cool athiests, you'd know that nobs. Lucifer means "light bringer" because Satan is lit af. ikanreed 🐐Bleat at me 18:54, 1 May 2017 (UTC)
- Compare this and this for example. Christopher (talk) 19:00, 1 May 2017 (UTC)
- I haven't seen Satan around Science HQ since the "butter vs. margarine" debate. Hentropy (talk) 20:47, 1 May 2017 (UTC)
I have absolutely no idea what you're trying to say, could you clarify? Christopher (talk) 21:28, 1 May 2017 (UTC)
- That the Christian Right views much of the science movement as anti-God and Satanic. I believe this can be scientificaly proven. But the minute you laugh or show any bias you destroy the science behind the conclusion.
- Frankly speaking, the cult-like devotion to science we see today is a spinoff of two TV characters from the 1960s, the Professor from Gilligans Island and Spock from Star Trek. Prior to these two characters who alwayd had all the answers to all the hard problems, American culture didn't have such blind devotion to science. nobs 02:42, 2 May 2017 (UTC)
- Good Lord Rob, you really are such a fucking idiot that you're even too dumb for Conservapedia. (This isn't a response to an argument, but it remains true and apposite.) - David Gerard (talk) 07:49, 2 May 2017 (UTC)
- To them it might destroy the science, but overall, this is a problem of attitude and presentation, not a problem of the argument itself. On the other hand, your characterization of atheists is akin to a stereotype, a hasty generalization and it's also an attitude problem from the Christian Right which some are condescending and even spiteful to atheists and cry persecution when they're still the majority (albeit a shrinking one) and some from the Christian Right even take offense to the mere existence of atheists (think of pro-atheist billboards which make no statement further than "if you're atheist, you're not alone" or "this road was built by an atheist organization" types or even have just one word "atheist" and those get vandalized or companies are reluctant to advertise those). Both these attitudes is probably why the two are so callous to each other and while I do understand that atheists may have a stubborn attitude problem, the Christian Right is also guilty of characterizing their fellow atheist opponents as less-than-flattering people as you just did, which may have led to the very attitude you yourself don't like.--It's-a me, LeftyGreenMario!(Mod) 02:55, 2 May 2017 (UTC)
- What I'm saying is an adversarial relationship doesn't have to exist. Each side can co-exist with mutual respect. As such, they become models of tolerance to the Islamic world. Each side could allow the other to prosylitze for 5 minutes, then politely slam the door in their face.
- This tolerance begins by looking at each sides underlying doctrime. Christians might say, "I believe Jesus died for my sins." Athiests might say, "I believe Christians are full of shit." That's a weak doctrine. Or tweaking Christians by suing in court to remove a nativity scene from the courthouse lawn doesn't help to build good faith or mutual respect. Athiests need to build something positive, like human liberation. But attacking people, organizations, or beliefs, hasn't i proved the cause or movement or allowed it fulfill its potential. nobs 03:17, 2 May 2017 (UTC)
- Why can't we all be humanists and fight for equality and human rights for everyone and human dignity and celebrate everything that we've managed to accomplish? Parrrley 03:23, 2 May 2017 (UTC)
- nobs: Again, you're characterizing atheists as arrogant and willing to characterize their fellow Christians as "full of shit" when it's this: Christians believe Jesus died for my sins, Atheists do not believe Jesus died for their sins. That's that, please don't add further weight to atheists by characterizing them as crude and snide. And atheists remove nativity scenes not because they hate Christians but because they view the scene as an endorsement of a religion, which is argued isn't supported on the federal level on the technical terms. Now, you can argue that all state constitutions do explicitly endorse Christianity (surprising for some) and therefore perhaps it's okay to have Christian themes around state buildings, though that's an ongoing debate right now since it's clearly a legal contradiction here and that's always a mess. Overall, though, this doesn't mean atheists hate Christians, but they try to endorse neutrality and secularity while also promoting freedom of expression, which is limited by the aforementioned neutrality and secularity. As for building something positive, I do think atheists don't really have a unified group out there since atheists are a very diverse bunch of people (which is to be expected since the only thing they share is a lack of a belief and even this lack of belief varies between "whatever" to "religion is not good for our society and should be destroyed" extremist), but it's difficult to unite atheists as some people don't even like billboards that merely call for atheists and it doesn't help that they're still a distrusted minority, so they need to work on building a good image for themselves before they can attempt something big, and the religious also should play their part in softening their attitudes and help cooperate. Finally I do think atheists and theists can cooperate, not arguing otherwise, but it's really hard to look past those differences that I present, including the attitude problems, and promote love and benefit to humanity, which is something we all want. --It's-a me, LeftyGreenMario!(Mod) 03:36, 2 May 2017 (UTC)
- Right on the money, as usual. Reverend Black Percy (talk) 10:33, 6 May 2017 (UTC)
Racial Self-interest is not racism[edit]
I read a study written by Eric Kaufmann (on whom our friends over at Conservapedia have an article) and published by Policy Exchange, a British think tank which contends that racial self-interest is not the same thing as racism. Here's a link to the study: I read this study with a critical, but open, mind, thinking there may be some truth in the premise of this argument. But even then I found myself thinking, "how can racial self-interest NOT be racism. Racism isn't limited to the irrational hatred of other races or White supremacy or separatism. The latter two (separatism and supremacy) are inextricably linked to racial self-interest". Nevertheless, I proceeded to skim through the study. It's an interesting article, but ultimately, in my opinion, an unconvincing argument. To boot, I looked up "racism" in the Oxford English Dictionary and here is what I got: compared and evaluated. Hence: prejudice, discrimination, or antagonism directed against people of other racial or ethnic groups (or, more widely, of other nationalities), esp. based on such beliefs." Emphasis on the emboldened part. I'd love to know what you think, if any of you is interested. I apologise if I do not respond as I am currently in the vandal-bin. Levi Ackerman (talk) 13:27, 2 May 2017 (UTC)
- What the fuck is racial self-interest? Like... why the fuck should I care, even marginally, more about some random asshole in New Mexico whose only connection to me is skin of vaguely the same shade? A lot of people complain about the "euphemism treadmill" when it comes to not insulting people, but the euphemism treadmill for "why it's okay to hate black people" is just so much worse. ikanreed 🐐Bleat at me 13:50, 2 May 2017 (UTC)
- "I'd love to know what you think, if any of you is interesting."
- I think we've heard enough from the interesting people (e.g. Nobs.) What do the normal people think? 94.1.138.166 (talk) 14:54, 2 May 2017 (UTC)
- My bad. That ought to have read "interested". But, I share ikanreed's sentiments. I can't stand these rather transparent attempts to sanitise racism. The author, Professor Kaufmann, claims that the aim of the report is to create space for ideas around ethnic interests to be more openly aired without accusations of racism. But think about it, what he is essentially saying is that there is nothing wrong with my White neighbour thinking our society (in our instance, the UK) should have less of my kind (I'm Black), and to such an end, immigration policy should be engineered so that less of my kind is admitted into the country, because my neighbour is afraid more of my kind somehow harms his kind. How is that not racist? Just because people who hold these views don't think of these views as racist doesn't mean they aren't in fact. There's a new kind of political correctness brewing. It's the kind where people - influential people - are afraid to call out racism. It is now politically correct to bend over backwards to tell people they are not being racist and their concerns are legitimate as those very same people express openly racist opinions Levi Ackerman (talk) 16:04, 2 May 2017 (UTC) 15:03, 2 May 2017 (UTC)
It's possible for racial self-interest to not be racist, but only in two scenarios.
- Imagine a world with only one race. (Perhaps we might call it the "human race".) Since there are no other races, "promoting" one's own race wouldn't be prejudiced against other races.
- Imagine a world with unlimited resources. ("Fully Automated Luxury...") In this world, nothing is zero-sum (comes at the expense of someone else), and so "promoting" one's own race wouldn't come at the expense of other races.
Neither of those worlds exist. Instead, this article follows in the vein of atheists preaching Cultural Christianity and alt-righters promoting "Western Values": both are ways to sanitize hatred of the Other. Fuzzy. Cat. Potato! (talk/stalk) 15:26, 2 May 2017 (UTC)
- It's a case where the theory looks plausible but the reality never measures up. Anyone who claims to be looking out for the best interests of my "race" is almost certainly a racist. I'm much more interested in politically supporting people who share my values anyway. Bongolian (talk) 01:54, 3 May 2017 (UTC)
- If there were no significant differences between people they would still find ways of identifying 'them' (= less good) and us (The Best): in past centuries 'them from the next village' were regarded as untrustworthy foreigners ,and all the football chants to the effect 'We are the greatest you lot are {string of pejorative terms and activities)'. 86.146.99.7 (talk) 13:25, 3 May 2017 (UTC)
If some Koreans want an immigration policy which gives preference to people of Korean language/culture, in order to maintain a Korean cultural majority in Korea, does that make them racist? And ask the same question with "Korea" replaced by China, Japan, Thailand, Vietnam, Israel, Jordan, Egypt, Turkey, Kenya, Ethiopia, Sudan, Yemen, etc. And then also ask that question with "Korea" replaced by France, Poland, Germany, Norway, Ireland, the United Kingdom, Canada, New Zealand or Australia... Now, as to myself, I support a culturally diverse immigration policy; I think the ideal should be global freedom of movement, and while I recognise that ideal in its pure form is unlikely to be practical in today's world, I would like us to be moving towards it instead of away from it, and so given that I don't have a lot of sympathy for immigration restrictions based on cultural or ethnic or linguistic preference. All that said, even though I personally don't support such policies, I think it is unfair to label all supporters of such policies as racist, but I think that is an increasingly common smear. And, I thought the basic point of that paper was to say the same thing, although I don't think it did the best job of making that point. (((Zack Martin)))™ 04:42, 6 May 2017 (UTC)
- You're conflating language with race and with nationality. In some cases they're closely linked but not always. As an example, in pre-WWII Germany many German Jews spoke German as their first language. German is an official language in 3 countries, and is spoken as a sizeable minority language in several others. Bongolian (talk) 05:04, 6 May 2017 (UTC)
- I'm not sure I am conflating them. Or at least, not any more than many other people do–if anything, I think I am responding to a conflation made by others. I'm not sure there is such a thing as "race"–my understanding was the concept is not considered biologically valid. Imagine if Germany had an immigration policy which gives preference to native German speakers (whether they be Swiss or Belgian or from wherever) – would that be racist? Well, I'm sure some people would call it that. Now what if an English speaking country had an immigration policy which preferred native English speakers – I am certain some people would call that racist. And consider proposals like "ban Muslim immigration" or "ban Hispanic immigration" (neither of which I support) – the first is about religion and the second is about culture/language–there are Muslim people of all "races" and there are Hispanic people of all "races"–yet both proposals will frequently be given the label "racist". I think the words "racist" and "racism" are so broad and vague that I actually doubt the usefulness of those words, and wonder if we should dispense with them – no doubt they name a lot of real and awful phenomena, but they also get applied to a lot of other stuff which is either less awful, or else equally awful but not particularly connected with the questionable concept of "race" – so, maybe we should replace them with a more precise vocabulary–e.g., rather than just slapping the label "racist" on X, explain in detail why you consider X to be an imprudent or even immoral proposal. (e.g. "banning Muslim immigration is racist" vs "it is immoral to disadvantage millions of moderate and peaceful members of a religious group just because some of their coreligionists are violent extremists, and doing so makes government policy religiously non-neutral which is a precedent which is likely to be used against non-Muslims later – if you can ban Muslim immigration, you can also ban Christian immigration or atheist immigration" – the second statement is far more informative and useful than the first) (((Zack Martin)))™ 09:24, 6 May 2017 (UTC)
- Discrimination based on language has the some of the same problems as discrimination based on "race". Which German language would the Germans use for discrimination purposes? I've been told by a native-German speaker that there are some rural Bavarian dialects that are very difficult for other native German speakers to understand. Additionally, there are quite a few German dialects spoken today, both within Europe and abroad (e.g., see Geographical distribution of German speakers). Some of these dialects probably have low-comprehensibility with standard German. Why is a native speaker better than a non-native fluent speaker. Lots of nations, even if they have 1 official language, also have other indigenous languages in use. E.g., the UK has Welsh, Scots, Cornish and Irish (which have some degree of recognition). Bongolian (talk) 20:02, 6 May 2017 (UTC)
- I agree that language discrimination is problematic. Although, it can be put on a much more objective footing than "race" can. There are language tests, such as IELTS and TOEFL for English, DELF/DALF and TEF for French, the Goethe-Institut exams for German, etc. You cannot of course strictly test for being a native speaker; but, if you set a sufficiently hard exam and demand a sufficiently high cutoff, you can in practice exclude all but the most fluent of non-native speakers. If Germany sets a difficult German language exam, and demands immigrants pass it, they will obviously use German Standard German (Bundesdeutsches Hochdeutsch)–but, a native speaker of a different German dialect, could probably learn to pass an exam in that dialect (even a difficult one), with far more ease than a person with a more distantly related native tongue. Actually, I don't know about Germany specifically, but I do know some countries already use language tests in immigration, such as Australia and Canada – but, a proposal for language-based immigration restriction might propose using far more difficult tests than what Australia and Canada currently use. But, my point is – if such a very hard language test was implemented (and I don't think it should be), would some people call it "racist"? I am sure many would, even though this has no obvious connection to race at all. Which I think supports the argument that the words "racism" and "racist" are overused, and probably should be replaced with more precise vocabulary, or reserved for ideas which are explicitly and unabashedly racist (e.g. South African apartheid). (((Zack Martin)))™ 21:36, 6 May 2017 (UTC)
Andy has a new weekly column at WND[edit]
Trump sycophancy and missile defense fear-mongering, about what you'd expect from Andy and WND. Petey Plane (talk) 13:30, 6 May 2017 (UTC)
- *eagerly awaits obligatory nobs rant* Reverend Black Percy (talk) 15:19, 6 May 2017 (UTC)
What's the difference between the Saloon bar...[edit]
...and the forums? —Evo and Meta (speak, speak) | Look at what I've done! 01:11, 7 May 2017 (UTC)
- Saloon bar is much more casual, forums are usually for 'serious discussions' where you get the walls of text everywhere. Lord Aeonian (talk) 01:18, 7 May 2017 (UTC)
- Another difference is that forums are more permanent. You can sticky stuff in the bar to stop it from archiving but it's only done for important stuff like mod elections. Christopher (talk) 09:53, 7 May 2017 (UTC)
- "Important stuff like mod elections" -- heh. FuzzyCatPotato of the Melodramatic Plastics (talk/stalk) 16:43, 7 May 2017 (UTC)
- Mod elections do get a "site wide (urgent)" intercom message though, which is only ever used for the most important things. Christopher (talk) 18:19, 7 May 2017 (UTC)
Why[edit]
... is there an infestation of 'stupid user names' and can they (or their IPs) be banished to the 'look at me' playground (until they get so bored they decide to be sensible/develop proper snark abilities). 82.44.143.26 (talk) 16:02, 8 May 2017 (UTC)
- While the edgy griefers and trolls are swiftly reverted and banned (and can even be judo flipped into serving a useful purpose — see below), they are continually allowed to register in the first place. This, for the same reason that vaccines have to contain actual pathogens, albeit in weakened form, in order to work. Controlled exposure to the crap is simply a fruitful chance to develop your own immunity. Reverend Black Percy (talk) 00:03, 10 May 2017 (UTC)
How do I change my name?[edit]
In light of whatever it is that happened today, I'm thinking it'd be a good idea to change my name to a pseudonym so these weirdos don't stalk me outside this wiki. How do I do that? DanielleD (talk) 03:14, 9 May 2017 (UTC)
- one thing that you can do is make a new account, but I'll look into it to see if I can change it. Also if you don't want werdos (like me) to find you outside this wiki or the internet, use different name and emails. A proxy can help to. 2d4chanfag (talk) 03:46, 9 May 2017 (UTC)
- Just start a new account and start using it - David Gerard (talk) 10:57, 9 May 2017 (UTC)
- If you wanted to change your name you'd go to RationalWiki:Requests to change username, this wouldn't help in this case as anyone can see what your old name was. I'd just get a new account. Christopher (talk) 14:53, 9 May 2017 (UTC)
Weird bug.[edit]
So I was looking at an old change I put on Armenian Genocide denial, and the content of the ref for the Hitler quote doesn't match what the wikitext says it should be. I can't figure out what's wrong. Anyone have any guesses? ikanreed 🐐Bleat at me 15:50, 11 May 2017 (UTC)
- It looks fine for me, what exactly is the problem? Christopher (talk) 16:06, 11 May 2017 (UTC)
- Okay, if you click the little [1] at the top, it takes you to a cite that looks like this:
- <ref>
- If you look at the page source, it's supposed to be this:
- <ref>[ Adolf Hitler, Statement on the Armenian Genocide]</ref>
- Is it just me? ikanreed 🐐Bleat at me 16:17, 11 May 2017 (UTC)
- No, it's happening for me as well. Didn't notice it the first time. Christopher (talk) 16:20, 11 May 2017 (UTC)
Shouldn't this really be moved to technical support? Christopher (talk) 16:25, 11 May 2017 (UTC)
It only happens inside <ref> tags, I copied the text exactly only removing the <ref> tags around the problematic link and it worked fine. Christopher (talk) 16:33, 11 May 2017 (UTC)
- well, I figured that would be the case, but it doesn't exactly look nice that way. ikanreed 🐐Bleat at me 16:35, 11 May 2017 (UTC)
- It's fixed now, it was a manifestation of the weird problems with refs before navsidebars. Sometimes the link goes funny, sometimes the ref doesn't appear in the references list at all. Christopher (talk) 16:40, 11 May 2017 (UTC)
Institute for Asgard Research. A parody of the ICR.--Rationalzombie94 (talk) 18:41, 11 May 2017 (UTC)
You'll never win[edit]
You can try to convert Christians to atheism all you want, but faster than you can do that, Christian women will just keep pumping more Christian babies out of their vaginas. Atheists have a low fertility rate, which is why, like homosexuals, atheists have to make an effort to CONVERT their followers rather than just expecting people will be that way naturally. Men's Rights EXTREMIST (talk) 18:00, 6 May 2017 (UTC)
- I don't think atheists want to "convert Christians to atheism". I just think that any mature person who still believes in god or gods must be a little … ah; … what's the word … stupid that's it. In any case there's nothing about atheism to convert to, it's just a matter of realising that religion is bunk. Pippa (talk) 20:49, 6 May 2017 (UTC)
- You're saying Christians have more babies despite the social implications? Interesting. —Oh colors! (speak, speak) Look at what I've done 21:09, 6 May 2017 (UTC)
- What social implications? Men's Rights EXTREMIST (talk) 21:16, 6 May 2017 (UTC)
- --It's-a me, LeftyGreenMario!(Mod) 21:22, 6 May 2017 (UTC)
- Italy is a Christian nation - but has a declining population; Ken Livingstone, not known for being a Christian, has five children. Therefore MRE is 'very slightly wrong' (and on other points). 86.191.125.212 (talk) 21:24, 6 May 2017 (UTC)
- Yeah but I'm referring more to Filipino and Latino Catholics and white Mormons. Possibly Jehovah's Witnesses as well. And also probably Baptists. Them things be makin babies like they animals fightin a war of attrition cuz it's wabbit season. Men's Rights EXTREMIST (talk) 21:30, 6 May 2017 (UTC)
- You come across as rather unpleasant MRE - and do you have actual official statistics?
- Better stick to your fantasies. 86.191.125.212 (talk) 21:35, 6 May 2017 (UTC)
- Okay then, I WILL!
- fapfapfapfap Oh yeah.. Men's Rights EXTREMIST (talk) 21:48, 6 May 2017 (UTC)
- Christian women will just keep pumping more Christian babies out of their vaginas? Firstly, I didn't know babies were born religious, secondly that's a rather harsh way of saying it don't you think? I feel like you're reducing a particular faction of women to a mere baby factory with that comment. Stupid misogynist. DanielleD (talk) 22:23, 6 May 2017 (UTC)
I think there is a valid point behind what MRE is saying, although it could have been better expressed. Let's not talk about Christians for a moment, let us talk about Jews. There is a spectrum of religious liberalism/conservatism within the Jewish people. At the most liberal end, we can put secular/non-religious Jews for whom Jewishness is purely an ethnic/national/cultural identity and not a religious one. Next comes Humanistic Judaism–I would say in general about organised humanism (not just Jewish), that it keeps the form of religion but dispenses the content, so it is slightly more conservative than just plain unorganised irreligion, but not by much. Next would come Reconstructionist Judaism, then Reform/Liberal Judaism, then Conservative/Masorti Judaism, then Modern Orthodoxy, then Traditional Orthodoxy (Hasidic, Haredi, etc.) Within each of these groups, there is a subspectrum of liberal-to-conservative expression. For example, while Traditional Orthodoxy is the most religiously conservative end of Judaism, but within it Satmar (for example) is far more conservative than Chabad Lubavitch (for example). Now, if we look at birth rates, assimilation rates, intermarriage rates, along this spectrum, what do we find? At the most liberal end of Judaism, birth rates are low, people have small families and have children later, intermarriage and assimilation are high; at the most conservative end, birth rates are high, people have large families, people start families earlier (early twenties instead of late twenties or thirties), rates of intermarriage and assimilation are very low. Of course these are just communal trends and so don't always apply at the individual level – somewhere out there you will find a Jewish atheist couple with six kids, and a Satmar couple who are childless or have only one or two children (most likely due to infertility or other medical issues) – but I don't think anyone who has a half decent knowledge of Judaism could deny this trend exists – just go read up about Kiryas Joel, New York. Now, what do these trends mean for the future of the Jewish people? It means that the numbers of liberal/secular Jews are going to shrink and shrink and shrink, due to their low fertility and tendency to intermarry and assimilate away, while the ultra-conservative Jews are going to grow and grow and grow, due to their high fertility and very low rates of intermarriage/assimilation. And this phenomena isn't just true for Judaism, the same observation holds for Christianity and Islam too (and probably non-Abrahamic religions as well, but I don't know enough about them to comment.) Very conservative Christians (whether Evangelical or Catholic or Mormon or whatever) have bucketloads of kids, the liberal end of Christianity (including cultural Christians such as Richard Dawkins) have relatively few kids, and a much higher proportion of childless individuals. So, I think MRE is right in that religious conservatives will grow over time. Kiryas Joel has an annual population growth rate of 5.6% per annum – if it keeps that rate up, in 70 years its residents will number over one million people. A few centuries from now, New York State is likely to be a theocracy ruled by ultra-Orthodox Jews, because they will vastly outnumber the non-Jewish (and non-ultra-Orthodox-Jewish) residents of the state. (And this isn't just true of ultra-Orthodox Jews – what is going to happen to Utah and the surrounding states? Mormons breed like rabbits, Mormon polygamists breed like mutant rabbits from outer space.) Demography is destiny, and the destiny of atheism isn't very bright. People assume that beliefs win out in the long-run by virtue of being true, but I doubt that is correct – a false belief which encourages a high birth-rate and makes defection personally costly will in the long run win out over a true belief which encourages a lower birth rate and imposes lower switching costs on defectors from it. (((Zack Martin)))™ 22:49, 6 May 2017 (UTC)
- As a side point, any valid point MRE holds he expresses it in a masculine lens. —Evo and Meta (speak, speak) | Look at what I've done! 01:22, 7 May 2017 (UTC)
- Since when were gay people desperate to "convert" people to homosexuality? Christopher (talk) 09:57, 7 May 2017 (UTC)
- The population argument sounds convincing, but as long as the Jewish lack political power (which they do at least compared to the dominant ethnicity and whites and Protestants), it doesn't matter how big their population is, as demographic minorities certainly aren't defined by numerical minorities. Arguing that New York is likely to "transform into a theocracy ruled by ultra-Orthodox Jews" sounds a bit slippery-slopey so it made me raise an eyebrow. I really don't think that's how population growth works... --It's-a me, LeftyGreenMario!(Mod) 02:58, 8 May 2017 (UTC)
- You are right that a numerical majority doesn't necessarily result in a political majority. However, in a democracy, a numerical majority is likely to become a political majority within a few generations. Political power lags demographic change, but in a democracy they will eventually meet. This is especially true if we are talking about a group like ultra-Orthodox Jews, most of whom believe in fully participating in the political process. (A minority of them stay out of Israeli politics due to anti-Zionist purism, but even those don't have any qualms about voting in countries other than Israel.) And, you are right that we can't just extrapolate exponential growth trends indefinitely, because at some point they will run up against limits to growth and turn into logistic trends instead. The question is, will ultra-Orthodox Jews in the State of New York hit a growth limit before they become the majority population of the state? I don't know what the growth limit would be. They could stop having large families and increase their rate of defection to secularism/irreligion – that has happened before to many other groups, e.g. Catholics. However, the ultra-Orthodox Jewish leadership is very aware of this possibility, and working much harder to prevent it than the Catholic leadership ever did – ultra-Orthodox Jews are far more insular than Catholics are for example, and so much more resistant to the processes of secularisation, assimilation and intermarriage. Other eventualities could intervene – war, famine, epidemic – although, those kinds of events might not make any difference to the ultimate outcome, if they impact the non-ultra-Orthodox-Jewish population just as much as ultra-Orthodox Jews. (It is of course also concievable that ultra-Orthodox Jews might fare better or worse under these conditions than the wider population, which might assist or prevent their eventual demographic dominance.) Persecution or genocide could also intervene–I think both of them are unlikely in the North American context, but one can't rule them out entirely. So, nothing is certain in history, but I still think an eventual ultra-Orthodox-Jewish majority in New York state is more likely than not. (((Zack Martin)))™ 09:25, 8 May 2017 (UTC)
- Sooo...that means us Latino peoples are going to lord over America in the forseeable future? I'm sorry, you're using this weird logic that in the end says that ultra-Orthodox Jews might rule New York in the future, so that technically means that it is also somehow "likely" that Latino people will lord over the American Southwest or something like that? Do you have the actual proof to back it up? Ɀexcoiler Kingbolt Noooooooo! There's a roach on my Wall! 18:44, 8 May 2017 (UTC)
- I think the Latino population in the US will continue to grow, no doubt. They will form the majority in ever larger parts of the US, and I think Latino politicians will have great success to come. (Political power tends to lag demographic change, which is why Latinos are underrepresented politically today, but that will be less true in the future.) However, I don't think Latinos can really be compared to ultra-Orthodox Jews. While Latinos do have a higher birth rate than non-Hispanic whites, the Latino birth rate is trending downwards so that demographic advantage will decline over time. (Continued immigration will replenish their numbers, but the birth rate is trending downwards in the immigration source countries too.) Latinos tend to assimilate quite well, and often within a couple of generations have switched near completely from Spanish to English. (Of course, Spanish survives better in some Latino ethnicities/communities/individuals than in others.) Religiously, Latinos are mostly moderate and not particularly resistant to the processes of secularization, which leads to lower birth rates in the long run. Even though some Latino families today have lots of kids, it is unlikely their descendants will continue to have families so large. By contrast, an ultra-Orthodox Jewish couple with six kids, the great great grandchildren will probably each have around six kids too. There is a high rate of intermarriage between the Latino and non-Latino population, which contributes to Latino assimilation; by contrast, ultra-Orthodox Jews almost never marry non-Jews, and marriages with non-ultra-Orthodox Jews are almost as rare. For ultra-Orthodox Jews, intermarriage really only happens with defection or with conversion. While there are some conscious efforts among some Latinos to maintain Spanish against English, it really cannot be compared in intensity to the efforts of many ultra-Orthodox Jews to maintain Yiddish – speaking Yiddish is seen as a protection against the defilement by the immorality of English-speaking culture, whereas I don't think many Latinos see Spanish and English in quite that way. A hundred years from now, Kiryas Joel will likely still be full of Yiddish speakers, whereas the descendants of most Latino Americans will probably speak more English than Spanish. Also, Latinos politically aren't hugely different from non-Latinos, so political dominance by Latinos is unlikely to radically change politics or society. (Since on the whole Latinos tend to lean more center-left than non-Latinos do, it will probably help the center-left politically, but nothing more drastic than that.) By contrast, ultra-Orthodox Jews have values far from the mainstream, so if they become politically dominant in an area, expect much bigger changes. (((Zack Martin)))™ 16:13, 9 May 2017 (UTC)
- @Zack
- A week late, but Hasidic Judaism is not a "traditional" Orthodox sect. Amongst Ashkenazim in the pale, the important thing to have was a Jewish education. But simply put, not everyone is smart enough (or can afford) to become well versed in the laws. But almost everyone can sing along. So the Hasidic movement dispensed with most of the esoteric BS and just had constant group singing combined with the religion. It became popular among the uneducated (and poor), but the educated mostly viewed it as a cult. However, it managed to grow rapidly due to high birth rates since, well, uneducated, in addition to conversions from other uneducated/poor Jews. The other Orthodox groups did adopt some of the singing into the prayers, though.
- As for NY in particular, well, ultra-Orthodox and Hasidic groups rely very heavily on social services for income, because when you have 10 kids and your wife has to quit working after the second kid while you spend all your time studying instead of actually working, it's inevitable. This has led to a HUGE amount of animosity amongst non-Jews (check out Kiryas Joel sometime), and I really sympathize with them, though ultra-Orthodox Jews are far from the only group in NY state that abuse the system like a redheaded stepchild. What will happen is that either everyone will get fed up and eliminate the child benefits (I advocate no additional after child #2), or the system will go broke in which case the child benefits are gone entirely. CorruptUser (talk) 14:31, 13 May 2017 (UTC)
Why are people still so judgemental in the 21st century?[edit]
I'm an honor student, I am a sorority member, I an an athlete, and I am a beautiful woman, but some people seem to treat me like crap because I have a child at age 20. I'm engaged to my child's dad, so it's not like I'm a slut. Sure, I look like a high school girl, but I'm not one and it's upsetting when I go to a store or restaurant and people give me funny looks. What is RationalWiki's opinion on this? DanielleD (talk) 22:35, 6 May 2017 (UTC)
- Well, personally, I feel sorry people treat you like that. I myself didn't have kids until I was 30 (and my wife was in her mid-late thirties when we had our first, she is older than me), but I don't think there is anything wrong with having kids young, I think it is actually good for society. Unfortunately society makes it harder than it should be to do that, with the competing demands of education and career, and I wish society would try harder to help young families balance raising children with those demands. (((Zack Martin)))™ 22:53, 6 May 2017 (UTC)
- There is just a stigma associated with young age and children, and you're not conforming to society's expectations of 20-year-old women: that they should be studying hard in college and not having kids. I'm actually older than you, DanielleD, at 22 (a young woman), and I don't look down on people like you with children, but without any background knowledge on you, if I have to be honest, there is some worry and concern about you, like if you're really *ready* to have kids and wondering if you should focus on your career first. I think about the best for you and your kids. But for some, maybe it translates to "weird looks" and even nastier reactions like "you're not ready, you made a poor choice to have kids" types. I know I would get funny looks if I had to take care of my own child and my parents would certainly scold me for having poor judgement and I would also rather focus on my own life first before such a hefty investment. In the end, it's all about societal expectations and you're bound to get treatment and weird looks if you don't follow some rules. I think the poor treatment stems from pity and contempt because people might think you're making your child's life hard but the funny looks might come from friendlier people who also have pity and concern. --It's-a me, LeftyGreenMario!(Mod) 23:17, 6 May 2017 (UTC)
- That's just it. I do well in school despite having a child, but people act like I'm either destined to be a loser or a bad mom. I don't understand that. I get WIC and my parents help me with money, and that causes some people to act like I'm a snowflake, but if I worked, people would say I wasn't taking care of my baby like I should. DanielleD (talk) 01:03, 7 May 2017 (UTC)
- How are you not blocked, you sexist, racist pig? But yes, I'm white. DanielleD (talk) 00:57, 7 May 2017 (UTC)
- There was already a case in the coop discussing this where RW decided to welcome him here because of the slogan: "We welcome contributors, and encourage those who disagree with us to register and engage in constructive dialogue." —Evo and Meta (speak, speak) | Look at what I've done! 01:19, 7 May 2017 (UTC)
- If someone acted like that with me in person I would kick them in the balls. I hope he is just trolling and doesn't actually think like that. DanielleD (talk) 01:25, 7 May 2017 (UTC)
- I'd punch them too. Though given his essay, his page, and his extremely masculine style of writing, I can't tell if he's being serious or trolling. —Evo and Meta (speak, speak) | Look at what I've done! 01:30, 7 May 2017 (UTC)
- I want to know how what he is saying can be classified as "constructive" dialogue... DanielleD (talk) 01:32, 7 May 2017 (UTC)
- MRE's preceding comment is pretty condemnable, I'll tell you that. Everything else he says can be argued against. —Evo and Meta (speak, speak) | Look at what I've done! 01:35, 7 May 2017 (UTC)
From a biological perspective 20 years old is the ideal age to have children. I may be wrong but I recall reading somewhere that the chance of a fetus developing autism goes from essentially nothing when the mother is 20 to 3% by the time she is 40. In general, everything starts to degrade as a person ages and I know the risk of genetic disorders and other issues are higher for children born to older mothers. Lord Aeonian (talk) 01:17, 7 May 2017 (UTC)
- So basically those old people are jealous? DanielleD (talk) 01:30, 7 May 2017 (UTC)
- Our problem is not that people have children at 20 -- or at 16, which is hardly unexpected either. Our problem is that we have institutions that we expect young people to attend, but which do not make allowances for young mothers of 16 or 20. We'd officially prefer that young women dose themselves with synthetic hormones to turn their lady bits off, rather than deal with infants in the MBA classrooms. When culture goes to war with biology, culture loses. - Smerdis of Tlön, LOAD "*", 8, 1. 02:06, 7 May 2017 (UTC)
- People have been judgmental since the dawn of time, and all that changes is who/what we are judgmental against, not how judgmental humans are.
- As for your situation, you are being lumped in with other people in your "demographic". You are an honor student and all, but most 20 year old single moms aren't, so even as good as you are people will see you as just another *insert perjorative*. This is the same with just about everything. I could be obese due to pituitary issues or side effects from psychiatric drugs, but since 90% of all obesity is self-inflicted, if I'm in a rascal at Walmart people are going to assume I'm just another lazy dumb fatass rather than someone who has 'valid' reasons for being fat. CorruptUser (talk) 14:43, 7 May 2017 (UTC)
- About that comment that "20 years old is the ideal age to have children"... I just want to add that aren't girls going through puberty earlier? I think I remember hitting my first period when I was 12, but I think some girls are getting it earlier and earlier. I kind of wonder, if culture delays us getting married and having children until mid-30's, then why are we undergoing puberty earlier? --It's-a me, LeftyGreenMario!(Mod) 03:04, 8 May 2017 (UTC)
- Some of that is due to lifestyle factors. Obesity makes girls go through puberty earlier. (For boys, it apparently has the opposite effect, and delays puberty instead.) (((Zack Martin)))™ 09:32, 8 May 2017 (UTC)
- If the above "questionable content" by MRE is not harassment, then I don't know what is. I have given him a long-term block. Given his lack of constructive work here and his trollish behavior, I don't see why we need to tolerate such behavior. Bongolian (talk) 07:24, 9 May 2017 (UTC)
R.I.P., feminists[edit]
Feminism is a belief system of privileged white women and the white
knights men who cater to them. But, uh oh, because of white women's heeding feminists' call to postpone marriage and childbearing till their 30s, that population is in demographic collapse! Who's going to carry the torch in the future? The women's studies departments and anti-human-trafficking NGOs will be as empty and silent as a raided Egyptian tomb.
R.I.P., feminism. Looks like you'll be going the way of the Shakers! Men's Rights EXTREMIST (talk) 00:20, 7 May 2017 (UTC)
- I like how the article you linked discusses neither gender nor feminism. It simply states that the proportion of white people in the US has gone down in recent history and will continue to go down for the foreseeable future. Then, by mechanisms you fail to elaborate on, extrapolate that into the decline of "feminism", as per your definition of the term. It's easy to feel smart when you live inside your own head, isn't it? 98.110.112.28 (talk) 00:39, 7 May 2017 (UTC)
- MRE's not necessarily hypocritical when he says it's primarily white women. But still, I'm not convinced on the connection between
white genocidepopulation decline and feminism. —Evo and Meta (speak, speak) | Look at what I've done! 01:17, 7 May 2017 (UTC)
- Rest assured that if white people's population declines, their roles will be taken over by non-whites. And unless something ELSE changes, non-whites occupying those economic roles will not find breeding more economically rewarding than the white people did. As their status rises, their birthrate too will decline. This is close to a human universal. The higher up the ladder you go, the less advantage there is in breeding children, and at a sufficiently high status breeding is only an expensive, time consuming hobby, and basically a vanity project. - Smerdis of Tlön, LOAD "*", 8, 1. 02:12, 7 May 2017 (UTC)
- That's true, but there is a fundamental, socioscientific explanation (if that word exists) as to why in any country (not just "white" ones) like Japan or Italy its demographics decline. —Evo and Meta (speak, speak) | Look at what I've done! 02:21, 7 May 2017 (UTC)
Well, again MRE may have a somewhat valid point expressed in an overly inflammatory and trollish way. People who espouse feminism are largely secular or religious liberals, and seculars and religious liberals have a low population growth rate. Religious conservatives, and especially ultra-conservative groups – such as ultra-orthodox Jews, the Amish, Mormon polygamists, etc – have a far higher population growth rate, but also espouse patriarchial anti-feminism. So, it appears in the long run that patriarchial anti-feminists may well conquer and destroy feminism through outbreeding. Of course, as Keynes said, "in the long run we're all dead", and I think the overrun of feminism by exponential (ultra-)conservative population growth is something none of us will likely live to see, but still I think it probably will eventually happen. Vale feminism. (((Zack Martin)))™ 10:02, 7 May 2017 (UTC)
- I think focusing on just population is only part of the picture and MRE's argument is very flimsy and focused on a demographic based on a shaky definition (race) and how they're supposedly "dying out". I think it's pretty simplified as feminism falls under "egalitarian" attitudes. I mean, abolitionists... they were a numerical minority but there are still a strong and healthy amount of people that are and need to advocate racial equality even today. And to categorize feminism as a white woman's thing, I guess it's partially correct, but it may be undergoing a more broad appeal as we have currently a third-wave feminism movement which focuses on women's issues around the world and so it's attracting more diverse people. --It's-a me, LeftyGreenMario!(Mod) 03:08, 8 May 2017 (UTC)
- The racial element in MRE's argument is rather silly, no doubt. Obviously feminism is not restricted to white people–although, it is pretty much restricted to secularists and religious liberals (of all races), so their overall low fertility bodes poorly for its future. (And I don't think race by itself does much to determine birth rates – education levels, social class, religiosity, etc., play a much bigger role, and the apparent associations between race and birth rates is really due to the correlations between race and those other factors than due to race alone.) I was steelmanning him, picking on the aspect of his case which I thought had some validity and ignoring the elements of his case which I didn't think were supportable. MRE isn't very good at making coherent arguments, but there is at times some nugget of sense in there which can be rationally extended in interesting directions. And I'm not sure abolitionism is really a relevant comparison–reintroducing slavery is a rather fringe idea, with few actual supporters anywhere–by contrast, patriarchial antifeminism is far from a fringe idea, it remains alive and well over much of the planet. While obviously there are a lot of economic advantages to having a workforce in which women are highly educated and active in the economy, it isn't clear if that strategy can in the long-run beat the competing patriarchial strategy in which women instead focus on having as many children as possible, and on indoctrinating those children into a religious worldview. (((Zack Martin)))™ 08:56, 8 May 2017 (UTC)
- There are patriarchal strategies that can be deployed if fertility is that big a deal. I read recently about Usama bin Ladin's four wives and eighteen children. Polygamy and harems do wonders for the reproductive success of upper class males. - Smerdis of Tlön, LOAD "*", 8, 1. 16:55, 8 May 2017 (UTC)
- Don't worry feminists, this discussion isn't actually even hinting at the idea that such patriarchal strategies are even acceptable and that women reproductive rights are a kind concession of men, isn't it not. This is not bro talking from their point of view, articulating a machiavellian plan which involves disposing on women bodies if there was the case to win the presumed breeding war with conservatives, as if they could revoke the concession of women autonomy over their bodies in any moment to take control of them if it were the case :). Because needless to say, you can't. Yeah, MraE has definitely a point, if only he were more educated in exposing it, the problem was his cussing. We might think the idea of feminism at "fault" for decreased fertility rate and that it's a tired plot device to use fear of muslim, black or other boogeyman outbreeding and genociding whites, to justify control on women bodies, assuming any race or culture is an isolated community with a hive mind and determined on ethnic substitution of "regular" whites, using women bodies. It's definitely the case with fundamentalists of all kind, I won't say it's not, but what about the coherence between means and ends (this little known) if we even fantasize of enabling such narrative for which sex equality is at fault and has a problem with fertility. First of all, overpopulation, a fertility war would only lead to this, on top of being a vile battle over the control of women bodies. Then, economy inequality, insecurity and exploitaiton is again at fault. Although desperate poverty, especially among emarginated groups, especially popular-religious as said, might ambivalently contribute to overbreeding as a survival mean, in spite of economical security, having less to lose, as they grow to be better off (like you illustrated in case of black people outbreeding, which, though, I don't see why would they necessarily have such a plan against whites and only reproduce among them) they would also likely slow down to stationary- moderately positive or decreasing. I wouldn't paint conservative with such a broad brush, women among them also benefit from feminist movements and the resulting equality and are often quite ambitious, I doubt they are so submitting, when some criticize feminism, they have strawman in mind and don't know the history or, more wisely distinguish second and third wave and the part of it they perceive as mysandrist. This is pretty much a paranoid power struggle fantasy of Rotk or such ultraconservative fringe blogs in which I actually read such a plan in which they hope to outbreeding debauchè liberals and then beat them. How desperate. On being more "natural" to reproduce at 20 for women, I have nothing against those who want, no judgement, although some here said judging is natural too, but one think is making valutations which we all do, another is enabling prejudice and condemning for the wrong reasons. Mind the naturalistic fallacy ;). Now, I read somewhere that not always, even naturally speaking the younger the better for women, that might be true for over 35, but not for below +-20. Also there is now the genetic evaluation, which allows all kinds of planning, on top of fertility age possibly already in the verge of extending, still due to scientific progress and life expectation (which of course, though, is far from linearly aligning with fertility age expectation, but still) . Still, let's talk instead about tackling the problem, from the more important economic angle, preventing wealth concentration and the impoverishment which comes with it, along with the decline in work rights. Also something has to be done against cradle strong religious fundamentalist indoctrination, be it from Christians or Muslims. Without demonizing religion in general, but literalism. This is especially rampant among evangelicals. This idea of anti indoctrination is something many Christians (but atheists too) are for, but only when it comes to Muslims, see the idea of banning the Quran, needless to say, hypocrisy elevated to nth.--78.15.253.193 (talk) 14:11, 12 May 2017 (UTC)
- What on Earth are you on about? Christopher (talk) 14:15, 12 May 2017 (UTC)
- I might admit that I simply have been too lengthy, because the topic was too complex to be exausted in a few lines. And even then, it's far from being exausted, because fortunately, we never run out of things to learn. You might not agree with something I have said, no problem, but if you think I am on something, it's too bad I am not, otherwise I'd gladly suggest it to you, if you allow me to kid a little about it :). Do you see what I was responding to and it's implications, along with a bit of irony. We need to reflect about it, sometimes. No offence taken at your joke.--78.15.253.193 (talk) 15:15, 12 May 2017 (UTC)
- I am really struggling to make out what you were trying to say. You raise numerous issues but I am struggling to detect an overarching point or argument. You seem to be mixing questions of Ought (whether patriarchial antifeminist strategies are morally acceptable) and Is (whether their proponents will prosper or dwindle in the long-term.) The philosophical question of the relationship between Ought and Is is very complex, so I think we should either keep them clearly separated, or else if you are going to argue for some linkage between them, you should be very explicit about exactly what you think that linkage is. You also seem to be mixing in a lot of racial stuff, when as I've said I think questions of race aren't very relevant to the question of the long-term demographic prospects of feminist vs antifeminist communities, and so should probably be kept out of the discussion. I mean, are Amish a different "race" from the US white majority? They look pretty white to me. And even ultra-Orthodox Jews, although neo-Nazis will insist that "Jews aren't white", and I know even some Jews have expressed mixed feelings about the "white" label, in terms of physical appearance there is very little difference between Ashkenazi Jews and other Europeans, so if we are going to define "race" in terms of physical appearance, then ultra-Orthodox Jews (who in the US are predominantly Ashkenazi) are clearly "white" (and Sephardi and Mizrahi Jews are "white" too, if we take "white" to equal the US Census Bureau's definition of "Caucasian"). There is no direct connection between "race" and fertility rates, because fertility rates are determined by reproductive behaviour, by culture, not by the color of your skin. Observed correlations between "race" and fertility are actually indirect, they are consequences of the correlations which existing between biological ancestry and culture. So, contrary to alt right fantasies of "white genocide", the highest fertility groups in the US are actually "white", which suggests a growing white majority in the long term (even while other forces are currently shrinking the relative share of the current white majority, a lot of those other forces are historically much more temporary.) Your suggestion that poorer immigrant groups decline in fertility as they become more economically secure is quite true, but not really relevant to the question of Amish or ultra-Orthodox Jewish demographics, since neither are particularly recent immigrant groups, and they show clear signs of deviating from the normal demographic trajectory for immigrant minorities. I think linking this to the question of Muslim immigration doesn't make much sense, because most Muslims are probably going to follow the standard demographic trajectory of declining fertility over the generations–and while the Amish and ultra-Orthodox Jews show some minority groups can succeed in deviating from that trajectory, it seems doubtful that most Muslims will do so. On a final point, I think what MRAs have to say is pretty irrelevant to this overall, because when MRAs talk about antifeminism, the Amish and the ultra-Orthodox are very much not what they have in mind. MRAs show no signs of higher fertility (if anything I think the MRA ideology encourages lower fertility–"don't bother having kids because your wife will just divorce you and get full custody and make you pay child support while her new partner takes your role as father"), so their long-term demographic prospects are no better than that of feminism. MRAism and feminism are both fundamentally species of secularism, and so both are about as demographically threatened as secularism as a whole is. (((Zack Martin)))™ 03:37, 13 May 2017 (UTC)
- Hi, thanks for the insight. Sorry for my grammar horrors :), it also led to some misunderstanding, as not sure if you meant to say that I brought out race to make racialist argument, linking groups behaviors to the dominant race groups that composes them at genetical level, etc. I didn't. Exactly, there are correlation with the dominant biological traits and culture, but not causations and Jews are really of all types. Fertility is based on the dominant culture of a group and how strict and prevalence is the adherence to it. Sorry if I sensed a hint of "ought" in the analysis at first. I probably failed to convey the ironic overtones, partly because of grammar and lengthiness, especially the one about MRE being apparently right in his main point and the probelm being his cussing and flaming. My point was that part of the lower fertility is economical insecurity and not feminism and women autonomy, reproductive rights and participation, etc. At least there are given thresholds, asthere's apparently a mix of cultural and economical factors and how they intermingle. Capitalism's paradigmatic crisis hit the fertility rate of then economically secure, certainly not outright rich people, so, to a certain point economical growth abates survival fertility, also favours the yielding of secular culture, but at the opposite, being hit by crisis in such condition tends to pospose kids in the search and sight of further economic stability. I also wanted to resize the idea of there being such breeding wars and what you said seems to further reinforce it even more than I myself tend to thing, basically resizing the idea of muslim demographic bomb, because as you said, they also follow, although I'd say to different outcomes because of their culture, the pattern of fertility dropping after improving general conditions, I hope despite Erdogan and Saudi's exortation to breed like there's no tomorrow :). Mra's and Mgtow are very diverse and some of them mingle with extremely traditional anti women rights conservative groups, not all of them are mra's but them and part of the Mra's share the same fantasy, controlling women and their reproductive rights, they think the traditional and religious whites can and should outbreed others, the usual external boogeymen, of course, but also those "debauchè" white liberals, feminists and their "cucks" (lol). Reactionaries are not linear and they might use secular values to hit non westerns as well as traditional christian ones. So basically it's not mra's in themselves, but part of the main argument is ultra orthodox conservatives many Mra fantasize being as they "govern" the women, might outbreed seculars. But if we mean Amish and Orthodox jews, maybe including the holywarmongering Trump happy part of evangelical, they seem a minority, are they steady growing so much? And if muslims, quite conservative (mainly also due to geopolitical situation and salafism being pushed worldwide without control at least until recently, but we might talk about that elsewhere ^_^) are also decreasing fertility, according to you, why wouldn't white conservatives as well share that pattern? Also, at some point they would have to share resources and inconsiderate reproduction might be dangerous in terms of overpopulation, while on the other hand, as said, secular groups are likely to breed more if the social conditions improve, although still inside a reasonable average, because of birth control, little reasons to go into religiously driven breeding wars which imply directly or indirectly control of women bodies. Cya :) --78.15.253.193 (talk) 11:24, 13 May 2017 (UTC)
- You are right that economic insecurity leads some people to delay having children or to have fewer children. However, even in the best possible economic conditions, secular people still tend to have relatively few children. It is not unheard of for some ultra-Orthodox Jews to have even twelve(!) children; even in the best possible economic conditions, secular people are unlikely to choose to have families that large. Another fertility advantage possessed by ultra-conservative religious groups such as ultra-Orthodox Jews is that people start families much younger (e.g. at 18 instead of in their late twenties or even thirties); secular people show little interest in doing this even when it is economically feasible for them. If you tell people "wait until you feel ready to have kids before having them, and in the meantime feel free to use whatever forms of birth control you feel are right for you", most people will wait until their late twenties or even thirties to have kids, and then only have 2 or 3, maybe 4. If you tell people "you must get married at age 18, birth control is a sin, God wants you to have as many children as possible", that's how they end up with a dozen kids. Religion is a much bigger factor in fertility than economics. You ask "if muslims, quite conservative... are also decreasing fertility, according to you, why wouldn't white conservatives as well share that pattern?" If you've been following, I haven't been making this argument about white conservatives in general. I've been making it about a certain type of high fertility isolationist religious sect of which I cite Old Order Amish and ultra-Orthodox Jews as examples. I believe these sects are structured that they avoid this general pattern/trajectory. White conservatives collectively don't constitute such a sect, so as a whole I don't see them avoiding the usual trajectory/pattern, although there are subgroups within them which do constitute such sects and so may do so. Likewise, Islam as a whole doesn't constitute such a sect, but there may be sects like the Old Order Amish and ultra-Orthodox Jews within Islam too. (I don't know enough about Islam to comment confidently on whether such sects exist in it or not.) You call Muslims "quite conservative", but I think most Muslim immigrants are actually rather moderate relative to the societies they are coming from (even if what is moderate in those societies sometimes seems rather conservative or even extreme by Western standards), and their moderation suggests their descendants are unlikely to resist the allure of secularisation/liberalisation/assimilation/intermarriage. (((Zack Martin)))™ 12:20, 13 May 2017 (UTC)
Well, as they say, quality over quantity. megalodon (talk) 03:13, 8 May 2017 (UTC)
- But quantity can be quality. When in doubt, get more Dakka. 2d4chanfag (talk) 03:41, 8 May 2017 (UTC)
- Quantity has a quality all its own, as Stalin probably never said. (((Zack Martin)))™ 08:56, 8 May 2017 (UTC) | https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive273 | CC-MAIN-2022-21 | refinedweb | 33,588 | 60.14 |
UPDATE 2018/3/13: Cloudflare Workers is now available to everyone., graphics hardware generally provided a fixed set of functionality. The OpenGL standard specified that the geometry pipeline would project points from 3D space onto your viewport, then the raster pipeline would draw triangles between them, with gradient shading and perhaps a texture applied. You could only use one texture at a time. There was only one lighting algorithm, which more or less made every surface look like plastic. If you wanted to do anything else, you often had to give up the hardware entirely and drop back to software.
Of course, new algorithms and techniques were being developed all the time. So, hardware vendors would add the best ideas to their hardware as "extensions". OpenGL ended up with hundreds of vendor-specific extensions to support things like multi-texturing, bump maps, reflections, dynamic shadows, and more.
Then, in 2001, everything changed. The first GPU with a programmable shading pipeline was released. Now you could write little programs that ran directly on the hardware, processing each vertex or pixel in arbitrary ways. Now people could experiment with algorithms for rendering realistic skin, or cartoon shading, or so much else, without waiting for hardware vendors to implement their ideas for them.
Cloudflare is about to go through a similar transition..
Of course, when you have hundreds of locations and millions of customers, traditional means of hosting software don't quite work. We can't very well give every customer their own virtual machine in each location -- or even their own container. We need something both more scalable and easier for developers to manage. Of course, security is also a concern: we must ensure that code deployed to Cloudflare cannot damage our network nor harm other customers.
After looking at many possibilities, we settled on the most ubiquitous language on the web today: JavaScript.
We run JavaScript using V8, the JavaScript engine developed for Google Chrome. That means we can securely run scripts from multiple customers on our servers in much the same way Chrome runs scripts from multiple web sites -- using technology that has had nearly a decade of scrutiny. (Of course, we add a few sandboxing layers of our own on top of this.)
But what API is this JavaScript written against? For this, we looked to web standards -- specifically, the Service Worker API.. If you've ever written a Service Worker, then you already know how to write a Cloudflare Service Worker.
What it looks like
Here are some examples of Service Workers you might run on Cloudflare.
Remember: these are written against the standard Service Workers API. The only difference is that they run on Cloudflare's edge rather than in the browser.
Here is a worker which skips the cache for requests that have a
Cookie header (e.g. because the user is logged in). Of course, a real-life site would probably have more complicated conditions for caching, but this is code, so you can do anything.
// A Service Worker which skips cache if the request contains // a cookie. addEventListener('fetch', event => { let request = event.request if (request.headers.has('Cookie')) { // Cookie present. Add Cache-Control: no-cache. let newHeaders = new Headers(request.headers) newHeaders.set('Cache-Control', 'no-cache') event.respondWith(fetch(request, {headers: newHeaders})) } // Use default behavior. return })
Here is a worker which performs a site-wide search-and-replace, replacing the word "Worker" with "Minion". Try it out on this blog post.
// A Service Worker which replaces the word "Worker" with // "Minion" in all site content. addEventListener("fetch", event => { event.respondWith(fetchAndReplace(event.request)) }) async function fetchAndReplace(request) { // Fetch from origin server. let response = await fetch(request) // Make sure we only modify text, not images. let type = response.headers.get("Content-Type") || "" if (!type.startsWith("text/")) { // Not text. Don't modify. return response } // Read response body. let text = await response.text() // Modify it. let modified = text.replace( /Worker/g, "Minion") // Return modified response. return new Response(modified, { status: response.status, statusText: response.statusText, headers: response.headers }) }
Here is a worker which searches the page content for URLs wrapped in double-curly-brackets, fetches those URLs, and then substitutes them into the page. This implements a sort of primitive template engine supporting something like "Edge Side Includes".
// A Service Worker which replaces {{URL}} with the contents of // the URL. (A simplified version of "Edge Side Includes".) addEventListener("fetch", event => { event.respondWith(fetchAndInclude(event.request)) }) async function fetchAndInclude(request) { // Fetch from origin server. let response = await fetch(request) // Make sure we only modify text, not images. let type = response.headers.get("Content-Type") || "" if (!type.startsWith("text/")) { // Not text. Don't modify. return response } // Read response body. let text = await response.text() // Search for instances of {{URL}}. let regexp = /{{([^}]*)}}/g let parts = [] let pos = 0 let match while (match = regexp.exec(text)) { let url = new URL(match[1], request.url) parts.push({ before: text.slice(pos, match.index), // Start asynchronous fetch of this URL. promise: fetch(url.toString()) .then((response) => response.text()) }) pos = regexp.lastIndex } // Now that we've started all the subrequests, // wait for each and collect the text. let chunks = [] for (let part of parts) { chunks.push(part.before) // Wait for the async fetch from earlier to complete. chunks.push(await part.promise) } chunks.push(text.slice(pos)) // Concatenate all text and return. return new Response(chunks.join(""), { status: response.status, statusText: response.statusText, headers: response.headers }) }
Play with it yourself!
We've created the Cloudflare Workers playground at cloudflareworkers.com where you can try writing your own script and applying it to your site.
Questions and Answers
Is it "Cloudflare Workers" or "Cloudflare Service Workers"?
A "Cloudflare Worker" is JavaScript you write that runs on Cloudflare's edge. A "Cloudflare Service Worker" is specifically a worker which handles HTTP traffic and is written against the Service Worker API. Currently, this is the only kind of worker we've implemented, but in the future we may introduce other worker types for certain specialized tasks.
What can I do with Service Workers on the edge?
Anything and everything. You're writing code, so the possibilities are infinite. Your Service Worker will intercept all HTTP requests destined for your domain, and can return any valid HTTP response. Your worker can make outgoing HTTP requests to any server on the public internet.
Here are just a few ideas how to use Service Workers on Cloudflare:
Improve performance
- Use custom logic to decide which requests are cacheable at the edge, and canonicalize them to improve cache hit rate.
- Expand HTML templates directly on the edge, fetching only dynamic content from your server.
- Respond to stateless requests directly from the edge without contacting your origin server at all.
- Split one request into multiple parallel requests to different servers, then combine the responses.
Enhance security
- Implement custom security rules and filters.
- Implement custom authentication and authorization mechanisms.
Increase reliability
- Deploy fast fixes to your site in seconds, without having to update your own servers.
- Implement custom load balancing and failover logic.
- Respond dynamically when your origin server is unreachable.
But these are just examples. The whole point of Cloudflare Workers is that you can do things we haven't thought of!
Why JavaScript?
Cloudflare Workers are written in JavaScript, executed using the V8 JavaScript engine (from Google Chrome). We chose JavaScript and V8 for two main reasons:
- Security: The V8 JavaScript engine is arguably the most scrutinized code sandbox in the history of computing, and the Chrome security team is one of the best in the world. Moreover, Google pays massive bug bounties to anyone who can find a vulnerability. (That said, we have added additional layers of our own sandboxing on top of V8.)
- Ubiquity: JavaScript is everywhere. Anyone building a web application already needs to know it: whereas their server could be written in a variety of languages, the client has to be JavaScript, because that's what browsers run.
We did consider several other possibilities:
- Lua: Lua is already deeply integrated into nginx, providing exactly the kind of scripting hooks that we need -- indeed, much of our own business logic running at the edge today is written in Lua. Moreover, Lua already provides facilities for sandboxing. However, in practice, Lua's security as a sandbox has received limited scrutiny, as, historically, there has not been much value in finding a Lua sandbox breakout -- this would change rapidly if we chose it, probably leading to trouble. Moreover, Lua is not very widely known among web developers today.
- Virtual machines: Virtual machines are, of course, widely used and scrutinized as sandboxes, and most web service back-end developers are familiar with them already. However, virtual machines are heavy: each one must be allocated hundreds of megabytes of RAM and typically takes tens of seconds to boot. We need a solution that allows us to deploy every customer's code to every one of our hundreds of locations. That means we need each one's RAM overhead to be as low as possible, and we need startup to be fast enough that we can do it on-demand, so that we can safely shut down workers that aren't receiving traffic. Virtual machines do not scale to these needs.
- Containers: My personal background is in container-based sandboxing. With careful use of Linux "namespaces" paired with a strong seccomp-bpf filter and other attack surface reduction techniques, it's possible to set up a pretty secure sandbox which can run native Linux binaries. This would have the advantage that we could allow developers to deploy native code, or code written in any language that runs on Linux. However, even though containers are much more efficient than virtual machines, they still aren't efficient enough. Each worker would have to run in its own OS-level process, consuming RAM and inducing context-switching overhead. And while native code can load quickly, many server-oriented language environments are not optimized for startup time. Finally, container security is still immature: although a properly-configured container can be pretty secure, we still see container breakout bugs being found in the Linux kernel every now and then.
- Vx32: We considered a fascinating little sandbox known as Vx32, which uses "software fault isolation" to be able to run native-code binaries in a sandboxed way with multiple sandboxes per process. While this approach was tantalizing in its elegance, it had the down side that developers would need to cross-compile their code to a different platform, meaning we'd have to spend a great deal of time on tooling for a smooth experience. Moreover, while it would mitigate some of the context switching overhead compared to multiple processes, RAM usage would still likely be high as very little of the software stack could be shared between sandboxes.
Ultimately, it became clear to us that V8 was the best choice. The final nail in the coffin was the realization that V8 includes WebAssembly out-of-the-box, meaning that people who really need to deploy code written in other languages can still do so.
Why not Node.js?
Node.js is a server-oriented JavaScript runtime that also uses V8. At first glance, it would seem to make a lot of sense to reuse Node.js rather than build on V8 directly.
However, as it turns out, despite being built on V8, Node is not designed to be a sandbox. Yes, we know about the vm module, but if you look closely, it says right there on the page: "Note: The vm module is not a security mechanism. Do not use it to run untrusted code."
As such, if we were to build on Node, we'd lose the benefits of V8's sandbox. We'd instead have to do process-level (a.k.a. container-based) sandboxing, which, as discussed above, is less secure and less efficient.
Why the Service Worker API?
Early on in the design process, we nearly made a big mistake.
Nearly everyone who has spent a lot of time scripting nginx or otherwise working with HTTP proxy services (so, basically everyone at Cloudflare) tends to have a very specific idea of what the API should look like. We all start from the assumption that we'd provide two main "hooks" where the developer could insert a callback: a request hook and a response hook. The request hook callback could modify the request, and the response hook callback modify the response. Then we think about the cache, and we say: ah, some hooks should run pre-cache and some post-cache. So now we have four hooks. Generally, it was assumed these hooks would be pure, non-blocking functions.
Then, between design meetings at our London office, I had lunch with Ingvar Stepanyan, who among other things had been doing work with Service Workers in the browser. Ingvar pointed out the obvious: This is exactly the use case for which the W3C Service Workers API was designed. Service Workers implement proxies and control caching, traditionally in the browser.
But the Service Worker API is not based on a request hook and a response hook. Instead, a Service Worker implements an endpoint: it registers one event handler which receives requests and responds to those requests. That handler, though, is asynchronous, meaning it can do other I/O before producing a response. Among other things, it can make its own HTTP requests (which we call "subrequests"). So, a simple service worker can modify the original request, forward it to the origin as a subrequest, receive a response, modify that, and then return it: everything the hooks model can do.
But a Service Worker is much more powerful. It can make multiple subrequests, in series or in parallel, and combine the results. It can respond directly without making a subrequest at all. It can even make an asynchronous subrequest after it has already responded to the original request. A Service Worker can also directly manipulate the cache through the Cache API. So, there's no need for "pre cache" and "post cache" hooks. You just stick the cache lookup into your code where you want it.
To add icing to the cake, the Service Worker API, and related modern web APIs like Fetch and Streams, have been designed very carefully by some incredibly smart people. It uses modern JavaScript idioms like Promises, and it is well-documented by MDN and others. Had we designed our own API, it would surely have been worse on all counts.
It quickly became obvious to us that the Service Worker API was the correct API for our use case.
When can I use it?
Cloudflare Workers are a big change to Cloudflare and we're rolling it out slowly. If you'd like to get early access -- or just want to be notified when it's ready: | https://blog.cloudflare.com/introducing-cloudflare-workers/ | CC-MAIN-2018-30 | refinedweb | 2,478 | 57.57 |
I was just poking around in the turbulence code, and it references
Noise ()
and
VScale ()
I was wondering where those were located.
I tried
find -type f -exec grep -H ' Noise(' {} \;
But it's not in pattern, texture, normal, or fnintern (that I see)
"Bald Eagle" <cre### [at] netscapenet> wrote:
> I was just poking around in the turbulence code, and it references
>
> Noise ()
> and
> VScale ()
>
> I was wondering where those were located.
>
> I tried
>
> find -type f -exec grep -H ' Noise(' {} \;
>
> But it's not in pattern, texture, normal, or fnintern (that I see)
Hello Bill
There's a definition of Noise here:
In which file did you see VScale ?
BTW: Have you ever tried Midnight Commander ?
I find it very easy to use when searching through a lot of files.
--
Tor Olav
"Tor Olav Kristensen" <tor### [at] TOBEREMOVEDgmailcom> wrote:
> Hello Bill
Hi TOK, long time no see :)
Hope you're doing well.
> There's a definition of Noise here:
>
excellent.
I think with fresh eyes, I see that Noise is a call to PortableNoise - so maybe
that will let me trace the code :)
inline DBL Noise(const Vector3d& EPoint, int noise_generator) { return
PortableNoise(EPoint, noise_generator); }
> In which file did you see VScale ?
VScale is called from the Turbulence function in texture.cpp
[I don't actually do any real C++, but it looks like "const TURB *Turb" is
declaring use of a constant named TURB which comes from - a class (?) or a
struct (?) or an internal private part of another part of the code called "Turb"
and "dereferences" that with the * ?
Similar later on with "int Octaves=Turb->Octaves;", Lambda and Omega.
I have only the most tenuous grasp of the dot . and arrow -> operators at this
point.]
DBL Turbulence(const VECTOR EPoint, const TURB *Turb, int noise_generator)
{
int i;
DBL Lambda, Omega, l, o, value;
VECTOR temp;
int Octaves=Turb->Octaves;
if (noise_generator>1)
{
value = (2.0 * Noise(EPoint, noise_generator) - 0.5);
value = min(max(value,0.0),1.0);
} else {
value = Noise(EPoint, noise_generator);
}
l = Lambda = Turb->Lambda;
o = Omega = Turb->Omega;
for (i = 2; i <= Octaves; i++)
{
VScale(temp,EPoint,l);
if (noise_generator>1)
value += o * (2.0 * Noise(temp, noise_generator) - 0.5);
else
value += o * Noise(temp, noise_generator);
if (i < Octaves)
{
l *= Lambda;
o *= Omega;
}
}
return (value);
}
and it resides in /source/backend/math/vector.h
inline void VScale(SNGL_VECT a, const SNGL_VECT b, SNGL k)
{
a[X] = b[X] * k;
a[Y] = b[Y] * k;
a[Z] = b[Z] * k;
}
> BTW: Have you ever tried Midnight Commander ?
> I find it very easy to use when searching through a lot of files.
Nope. I honestly haven't had the energy and the ability to focus on meticulous
things like this for a while - just so much IRL.
Work, the Plague, car repairs, etc........................................
But I keep hanging on by my fingernails ;)
I'll take a look at M.C. and see what it's like - thanks for the tip!
Am 20.04.2019 um 14:19 schrieb Bald Eagle:
> I think with fresh eyes, I see that Noise is a call to PortableNoise - so maybe
> that will let me trace the code :)
(Technically, `Noise` _may or may not_ be a call to `PortableNoise` -
that depends on how the binary is compiled, and possibly also the
features of the CPU it is actually run on. But since it is always a call
to either that function or an optimized variant that gives the same
results (the infamous "optimized noise generator"), this distinction is
only relevant when making changes to the function.)
> VScale is called from the Turbulence function in texture.cpp
My, that's some old code there!
`VScale(a,b,c)` was a function that implemented uniform linear scaling
of a vector back in the days when we used the C-style 3-element array
type `VECTOR` to store vectors. That type has been superseded by the
class type `Vector3d`, which provides operator overloading for the same
purpose, and instead of `VScale(a,b,c)` we would now write `a=b*c`.
(Also, the `Turbulence` function now resides in `noise.cpp`.) | http://news.povray.org/povray.programming/thread/%3Cweb.5cba5d793a7caf464eec112d0%40news.povray.org%3E/ | CC-MAIN-2019-22 | refinedweb | 686 | 69.92 |
There’s not really enough info there to tell - could you create a gist with your whole notebook?
Lesson 3 discussion
Thanks. Here it is:
@jeremy any idea what could be going wrong here? Thanks!
You didn’t pop the last layer and replace it with one with the correct number of outputs, prior to creating conv_model. I’m not sure why it is happening - but my guess is that that’s the cause. Keras often gets confused when copying layers between models - recently I’ve started writing code that instead copies the layer config and weights separately.
Got it working. Copying the config and the weights separately did the trick. Thanks!
Could someone help me understand why we had to halve the weights?
Also does this half the weights of the corresponding fc layers only or all the model’s layers… i believe model will have a lot more layers than fc_layers
def get_fc_model():
model = Sequential([
MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]),
Flatten(),
Dense(4096, activation=‘relu’),
Dropout(0.),
Dense(4096, activation=‘relu’),
Dropout(0.),
Dense(2, activation=‘softmax’)
])
for l1,l2 in zip(model.layers, fc_layers): l1.set_weights(proc_wgts(l2)) model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy']) return model
When you remove dropout, you are no longer zeroing-out half of the previous layer’s weights. Therefore the total weights of the previous layer are (approximately) twice what they were before. So to make the next layer’s weights continue to work, you’ll need to halve the weights of the layer that used to have dropout.
This only need be done for the layers that have had dropout removed (or adjusted).
ok… but given that dropout only randomly zeros out the weights, we might still be doubling some of these weights … isnt it?
Plus if drop if say 0.8, 80% of the weights will be dropout will be removed so its just not doubling the weights it … it will be much higher but by setting o/2, we are always just halving it which wont restore the effect on removed dropouts.
def proc_wgts(layer): return [o/2 for o in layer.get_weights()]
Does that make any sense? Sorry its hard to explain what i am trying to say.
proc_wgts() specifically works for removing dropout layers with p=0.5. So by definition, on average half of those weights are being zeroed out.
Is making conv layers nontrainable same as creating an FC model with just FC layers and running fit_generator on it with conv output? I am going over lesson 3 notebook, and I am trying to understand when are layers made nontrainable.
After data augmentation, conv layers are made nontrainable. Why is that?
> for layer in conv_model.layers: layer.trainable = False
Somehow, my intuition says making some layers nontrainable is sub-optimal for accuracy, as those layers do not get backpropagation benefits? Or am I misunderstanding something?
A few questions about BatchNormalization:
- I see that we are retraining the VGG model here as we think training 120m parameters using 20K images is not a good idea, isn’t that same when we added/updated other layers like DropOut?
- I don’t follow the purpose of this code block, why are we adjusting weights for all dense layers? And what does 0.3 and 0.6 signify?
def proc_wgts(layer, prev_p, new_p):
scal = (1-prev_p)/(1-new_p)
return [o*scal for o in layer.get_weights()]
for l in bn_model.layers:
if type(l)==Dense: l.set_weights(proc_wgts(l, 0.3, 0.6))
We are setting them not to learn (i.e., update their weights) because we do not need to, and thus save a bit of computation, since they have already learned lower-level features like edges, shapes, and similar objects (e.g., animals) from being trained in the ImageNet dataset.
Yes. The latter is preferred since it’s much faster, if you’re doing more than a couple of epochs.
That’s certainly true - but the early layers are so general (e.g. remember Zeiler’s visualizations - layer 1 just finds edges and gradients) that it’s extremely unlikely that you’ll need to change them, unless you’re looking at very different kinds of images. e.g. if you’re classifying line drawings, instead of photos, you’ll probably need to retrain many conv layers too.
Sorry I’m not following this question - can you clarify?
This is for when we have a pre-trained model that used a different amount of dropout to what we wish to use for our model. e.g. if the pretrained model used p=0.5, and we wish to use p=0.0, we’ll need to double all the weights. In this case, I took a pretrained model that used p=0.3, and wished to change it to p=0.6
NVM – I now have the path pointing to ft2.h5 in /results which appears to have legs – thx!!
I’m working through the Lesson 3 Notebook and I’m hitting an “Exception: You are trying to load a weight file containing 17 layers into a model with 16 layers.” error when running model.load_weights(model_path+‘finetune3.h5’) I tried changing finetune3.h5 to finetune2.h5 and finetune1.h5 but still received the same error. Searching the forums and the web didn’t yield any results either. Any ideas??
Exception Traceback (most recent call last)
in ()
----> 1 model.load_weights(model_path+‘finetune3.h5’)
/home/ubuntu/anaconda2/lib/python2.7/site-packages/keras/engine/topology.pyc in load_weights(self, filepath, by_name)
2498 self.load_weights_from_hdf5_group_by_name(f)
2499 else:
-> 2500 self.load_weights_from_hdf5_group(f)
2501
2502 if hasattr(f, ‘close’):
/home/ubuntu/anaconda2/lib/python2.7/site-packages/keras/engine/topology.pyc in load_weights_from_hdf5_group(self, f)
2550 ‘containing ’ + str(len(layer_names)) +
2551 ’ layers into a model with ’ +
-> 2552 str(len(flattened_layers)) + ’ layers.’)
2553
2554 # we batch weight value assignments in a single backend call
Exception: You are trying to load a weight file containing 17 layers into a model with 16 layers.
Steve,
some things you can check. if you use model.summary() it should show you the current layers in the model. i think vgg16 has 16 layers, hence the weights file should have 16 layers.
looks like there may be an extra layer attached to your model which generated the weights?
model.pop() would remove this, but it might be worth checking what the extra layer is. the finetuned vgg16 model for dogs/cats should have a last dense layer with a softmax activation and an output of 2 categories, which should replace the original layer which contained a similar layer but with 1000 categories.
hope that helps.
First of all thanks for this wonderful course Jeremy. Only wish this course had come out a bit earlier. The 3 days spent watching your videos were more informative than 4 months of fiddling around with Keras.
Appreciate all best practices/tricks of trade that you shared.
VGG-16 had worked very well in my last project of classifying building photos. Now I am starting on classifying localities in GIS (MapInfo) based on the type & density of the buildings in each locality. So the input would be screen captures from the GIS. I am guessing in this case I would have to make the convolutional layers also trainable. Or would I be better of training a small convnet from scratch.
Working on the data collection right now. I am guessing I would have around 100 screen captures/class prior to augmentation for training & validation.
Thanks
Satish
Correct me if I’m wrong, in the lesson 3 notebook
fc_layers has
BatchNormalization layers while the new
model inside
get_fc_model() does not. Doesn’t it mean that the weight copying process inside
get_fc_model() is bound to fail?
You might be right - we switched in lesson 4 to adding batchnorm to VGG, and went back and changed some notebooks. Apologies if there’s some inconsistencies still!
So I have 2 questions which look stupid but I cant seem to understand
For the mean (vgg_mean) that we deduct from each element of the array ,cant we just use 128 since we know it will always be within (0,255) ?
So I see we change from RGB to BGR ? What is the reason for doing so ? I read that OpenCV uses BGR for reading image files , but i don’t see any usage of openCV. Am I missing something ? | http://forums.fast.ai/t/lesson-3-discussion/186?page=2 | CC-MAIN-2018-17 | refinedweb | 1,404 | 66.84 |
I'm getting a signal when I use my snoop on a ds to mds packet trace:
[th199096@jhereg snoop]> ./snoop -V -i ~/ds2tmds.snoop > xxx WARNING: received signal 11 from packet 4
And packet 4 is:
4 0.00596 pnfs-9-25 -> pnfs-9-26.Central.Sun.COM CTL-DS C DS_EXIBI
I've gone from handcoding the XDR to generating it automatically, and both had this error. Time to see what is going on. I generated the packet trace with '-x0,2000' so I get to see the output:
0: 001b 242d e629 001b 242d e641 0800 4500 ..$-.)..$-.A..E. 16: 00a8 d3dd 4000 4006 0000 0a01 e943 0a01 ....@.@.....�C.. 32: e944 03fc 0801 1f9e 8f80 17cc 1d01 5018 �D............P. 48: c1e8 0000 0000 8000 007c d058 4d4c 0000 .�.......|.XML.. 64: 0000 0000 0002 0001 9641 0000 0001 0000 .........A...... 80: 0002 0000 0001 0000 0020 48f4 fa0b 0000 ......... H..... 96: 0009 706e 6673 2d39 2d32 3500 0000 0000 ..pnfs-9-25..... 112: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 128: 0000 ffff ff02 eef0 3b00 0000 0027 706e ........;....'pn 144: 6673 2d39 2d32 353a 2073 7663 3a2f 6e65 fs-9-25: svc:/ne 160: 7477 6f72 6b2f 6473 6572 763a 6465 6661 twork/dserv:defa 176: 756c 743a 0000 ult:..
I'm going to go back and forth in the code to look at this. First, I've tracked down where the FMRI is appearing:
case NFS4_SETPORT: uaddr = get_uaddr(nconf, addr); if (uaddr == NULL) { dserv_log(do_all_handle, LOG_INFO, gettext("NFS4_SETPORT: get_uaddr failed")); return (1); } (void) strlcpy(setportargs.dsa_uaddr, uaddr, sizeof (setportargs.dsa_uaddr)); (void) strlcpy(setportargs.dsa_proto, nconf->nc_proto, sizeof (setportargs.dsa_proto)); (void) strlcpy(setportargs.dsa_name, getenv("SMF_FMRI"), sizeof (setportargs.dsa_name));
This is in usr/src/cmd/dserv/dservd/tbind_sup.c and is a dservd call into the kernel. It ends up in usr/src/uts/common/dserv/dserv_mds.c: (minus some unpacking)
int dserv_mds_addport(const char *uaddr, const char *proto, const char *aname) { ... (void) sprintf(in, "%s: %s:", uts_nodename(), aname); inst->dmi_name = dserv_strdup(in); bzero(&res, sizeof (res)); args.ds_ident.boot_verifier = inst->dmi_verifier; args.ds_ident.instance.instance_len = strlen(inst->dmi_name) + 1; args.ds_ident.instance.instance_val = inst->dmi_name;
The defaults are also set:
dserv_mds_instance_init(dserv_mds_instance_t *inst) { inst->dmi_ds_id = 0; inst->dmi_mds_addr = NULL; inst->dmi_mds_netid = NULL; inst->dmi_verifier = (uintptr_t)curthread; inst->dmi_teardown_in_progress = B_FALSE; }
So, if we knew the curthread, we could spot check to see that this went across okay. We also need to know if this has to be unique or not. If so, could we get a dup here?
So how does this data go across the wire? We need to look in the XDR (usr/src/head/rpcsvc/ds_prot.x):
struct identity { ds_verifier boot_verifier; opaque instance
; }; /* * DS_EXIBI - Exchange Identity and Boot Instance * * ds_ident : An identiifier that the MDS can use to distinguish * between data-server instances. */ struct DS_EXIBIargs { identity ds_ident; };
So we see the boot_verifier followed by the instance. BTW: MAXPATHLEN might be too small here as we add the nodename.
And an opaque is a length and an array. Hmm, the hand-coded usr/src/cmd/cmd-inet/usr.sbin/snoop/nfs4_xdr.c calls xdr_opaque, while the machine generated code does:?
bool_t xdr_identity(XDR *xdrs, identity *objp) { rpc_inline_t *buf; if (!xdr_ds_verifier(xdrs, &objp->boot_verifier)) return (FALSE); if (!xdr_bytes(xdrs, (char **)&objp->instance.instance_val, (u_int *) &objp->instance.instance_len, MAXPATHLEN) return (FALSE); return (TRUE); }
And that makes a difference:
[th199096@jhereg snoop]> ./snoop -v -i ~/ds2tmds.snoop > xxx [th199096@jhereg snoop]>
But wait, we don't see the signal, but we do see:
CTL-DS: ----- Sun CTL-DS ----- CTL-DS: CTL-DS: Proc = 2 (Exchange Identity and Boot Instance) CTL-DS: ---- short frame ---
And a debug statement shows that the length looks off:
CTL-DS: ----- Sun CTL-DS ----- CTL-DS: CTL-DS: Proc = 2 (Exchange Identity and Boot Instance) CTL-DS: xdr_identity bombed, len = 0 CTL-DS: ---- short frame ---
Hmm, I manually set the length before the call to xdr_opaque. So back to the raw data. We know right before the nodename, we should find the length.
Hmm, my allergies are killing my thought process. A signal 11 is SIGSEGV.
I'm back after a night's rest. I recompiled snoop with gcc and I think I've found the problem after staring at it in gdb:
127 switch (xdrs->x_op) { 128 case XDR_DECODE: 129 if (nodesize == 0) 130 return (TRUE); 131 if (sp == NULL) (gdb) 132 *cpp = sp = (char *)mem_alloc(nodesize); 133 /* FALLTHROUGH */ 134 135 case XDR_ENCODE: 136 sprintf(get_line(0, 0), "tdh_xdr_bytes calling xdr_opaque with %d!", nodesize); 137 return (xdr_opaque(xdrs, sp, nodesize)); 138 139 case XDR_FREE: 140 if (sp != NULL) { 141 mem_free(sp, nodesize); (gdb) p sp $9 = 0x80c74a6 "\203�\020\203}\020" (gdb)
We need to be allocating memory here. But whatever sp is pointing to is junk:
bool_t xdr_identity(XDR *xdrs, identity *objp) { rpc_inline_t *buf; if (!xdr_ds_verifier(xdrs, &objp->boot_verifier)) { sprintf(get_line(0, 0), "xdr_identity bombed for verifier = %d", objp->boot_verifier); return (FALSE); } sprintf(get_line(0, 0), "xdr_identity okay for verifier = %lx", objp->boot_verifier); if (!tdh_xdr_bytes(xdrs, (char **)&objp->instance.instance_val, (u_int *) &objp->instance.instance_len, MAXPATHLEN)) { sprintf(get_line(0, 0), "xdr_identity bombed, len = %d", objp->instance.instance_len); return (FALSE); } return (TRUE); }
And we can see I am just grabbing it off the stack:
static void ds_exibi_sa(char *line) { DS_EXIBIargs eargs; if (!xdr_DS_EXIBIargs(&xdrm, &eargs)) longjmp(xdr_err, 1); sprintf(line, "V = %d I = (%.20s)", eargs.ds_ident.boot_verifier, utf8localize((utf8string *)&eargs.ds_ident.instance)); xdr_free(xdr_DS_EXIBIargs, (char *)&eargs); }
A quick memset and retest:
[th199096@jhereg snoop]> ./snoop -v -i ~/ds2mds2.snoop > zzz WARNING: received signal 11 from packet 4 [th199096@jhereg snoop]> ./snoop -v -i ~/ds2mds2.snoop > zzz [th199096@jhereg snoop]>
And we can see the difference!
A Classic XDR issue for first time programmers.. err but wait.. heh :-P
Posted by biteme@xdr.com on October 25, 2008 at 08:38 AM CDT #
> A Classic XDR issue for first time programmers.. err but wait.. heh :-P
You miss the point as to why I blog. This was what, a minute of my day? Why bother blogging about it at all?
The reason I blog is to help "first time programmers" with issues like this. I get *a lot* of thank you email / comments from people hitting the same problems I blog about.
Posted by Thomas Haynes on October 29, 2008 at 10:33 AM CDT # | http://blogs.sun.com/tdh/entry/snoop_doesn_t_want_to | crawl-002 | refinedweb | 1,052 | 60.21 |
You can subscribe to this list here.
Showing
2
results of 2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
More news from the stack-compact branch, bad ones this time. There's a
flaw in my ideas for tree-decomposition-based, more efficient allocation
of stack space; I'll try come up with a working solution, but I don't
expect one anytime soon.
I thus suggest to just merge the current stack-compact branch. The
block-tree bases stack allocator currently there is nowhere near what I
wanted to implement in this branch, but:
- - it is fast,
- - substantially better when using local aggregates,
- - never needs more stack space than the one in current trunk,
- - rather simple, thus probably not very buggy, and IMO thus suitable for
merge before the sdcc 3.1.0 release.
Could you test it, please?
Philipp
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla -
iEYEARECAAYFAk4sCdwACgkQbtUV+xsoLpqz6gCgwQpXUnh+tJrkB3YlU4ZQzqx3
PZUAn0gwjDTzZqJydFPXRwzt3mXIf7Aq
=AWLD
-----END PGP SIGNATURE-----
Dear fellows,
I think I discovered a bug in gcc 4.6 on Solaris i386. It appeared in
sdcc bitfields.c host regression test in svn build 6665, when -O2 gcc
option was included.
Here is the code in file t.c, which reproduces the bug:
----8<----
#include <stdio.h>
#pragma GCC optimize ("O2")
const struct
{
unsigned int : 4;
unsigned int f : 2;
} cs = { 1 };
int main(void)
{
printf("cs.f = %d, (sf.f == 1) = %d\n", cs.f, cs.f == 1);
}
---->8----
You can compile it:
gcc -o t t.c
and run it:
./t
The result is:
cs.f = 1, (sf.f == 1) = 0
The result of (sf.f == 1) is wrong: it should be 1.
Without the anonymous bit field structure member or if it is compiled
without O2 optimization or if the structure is declared as volatile, it
compiles OK.
Before submitting the bug to gcc bugzilla, I would like you to help me to:
- verify if it is really a bug (maybe I misunderstood something?)
- verify if I correctly compiled the gcc (I took the gcc 4.6 release
tarball and compile it on Solaris i386 machine)
- verify if it is reproducible also on other Solaris i386 machines with
the same or different gcc compiler versions
I'll appreciate any response.
Best regards,
Borut | http://sourceforge.net/p/sdcc/mailman/sdcc-devel/?viewmonth=201107&viewday=24 | CC-MAIN-2014-52 | refinedweb | 382 | 75.2 |
DataSet.Load Method (IDataReader, LoadOption, DataTable[])
Assembly: System.Data (in system.data.dll)
Parameters
- reader
An IDataReader that provides one or more result sets.
- loadOption
A value from the LoadOption enumeration that indicates how rows already in the DataTable instances within the DataSet will be combined with incoming rows that share the same primary key.
- tables
An array of DataTable instances, from which the Load method retrieves name and namespace information. Each of these tables must be a member of the DataTableCollection contained by this DataSet.
The Load method provides a technique for filling a single DataTable with data, retrieved from an IDataReader instance. This method provides the same functionality, but allows you to load multiple result sets from an IDataReader into multiple tables within a DataSet.
The loadOption parameter allows you to specify how you want the imported data to interact with existing data, and can be any of the values from the LoadOption enumeration. See the documentation for the DataTableLoad method for more information on using this parameter.
The tables parameter allows you to specify an array of DataTable instances, indicating the order of the tables corresponding to each result set loaded from the reader. The Loadmethod fills each supplied DataTable instance with data from a single result set from the source data reader. After each result set, the Loadmethod moves on to the next result set within the reader, until there are no more result sets.
The name resolution scheme for this method is the same as that followed by the Fill method of the DbDataAdapter class.
The following example creates a new DataSet, adds two DataTable instances to the DataSet, and then fills the DataSet using the Load method, retrieving data from a DataTableReader that contains two result sets. Finally, the example displays the contents of the tables | https://msdn.microsoft.com/en-us/library/5fd1ahe2(v=vs.85).aspx?cs-save-lang=1&cs-lang=cpp | CC-MAIN-2017-43 | refinedweb | 302 | 52.6 |
I am using ORMLite as my ORM and I am using it with following structure which contains the foreign key relation ship:
public class Order { [AutoIncrement] public int Id { get; set; } [Reference] public Item Item { get; set; } public string ProUserId { get; set; } public string Details { get; set; } } public class Item { [AutoIncrement] public int Id { get; set; } public string Description { get; set; } }
As we can see that Order contains the reference to the Item. In DB Order table has a foreign key called ItemId in the table and I have annotated that key in the design view with [Reference] attribute.
I am trying to save the Order with following code:
var order = new Order { Item = new Item { Id = 3, Description = "Something" }, ProUserId = "[email protected]", Details = "fdfsdfsd" }; Db.Save(order,references:true);
I was hoping that ORMLite would pick up the relationship and with ItemID in the Order table but it did not and it did throw following error instead:
Cannot insert the value NULL into column 'ItemId', table 'WebApp.dbo.Order'; column does not allow nulls. INSERT fails.
I tried changing my schema and addred OrderId column in my Item table with reference there and that works fine. But that is not the correct design. Should I make any changes in my code/schema to support this feature? | http://www.howtobuildsoftware.com/index.php/how-do/bnpD/orm-servicestack-ormlite-servicestack-saving-reference-using-servicestack-ormlite | CC-MAIN-2018-09 | refinedweb | 217 | 53.24 |
background
At present, video live broadcasting is so popular. What technologies are involved in building an online live broadcasting room?
The live video is composed of the live end of the anchor and the viewing end of the audience. A simple viewing terminal should at least include a player and a chat room. The following describes the related technologies around these two modules.
Live video
Live video broadcasting can be divided into video acquisition, pre-processing, encoding and packaging, transmission, unpacking and decoding, and playback.
The live broadcasting end collects audio and video data through hardware equipment, and transmits it to the viewing end after pre-processing, coding and packaging. This step is generally completed by CDN relay. The streaming end will push the video stream to the source station, and the CDN will pull the stream from the source station. After the streaming is successful, it will be encoded and encapsulated into different formats for playback at each viewing end. The simple schematic diagram is as follows:
(network reference picture)
Next, let's talk about the basic requirements of the viewing end:
- Multi terminal viewing
- Watch stable, not Caton
- Low latency and high concurrency
Multi terminal viewing
First, specify the terminals to be supported, including mobile APP (iOS, Android), mobile browser, applet, PC browser and PC client. For PC browsers, IE8 is generally supported. Moreover, since Chrome browser blocks Flash by default, the strategy adopted in PC browser is: give priority to H5 playback in H5 compatible browsers, otherwise downgrade to Flash playback. The differences between the two supported live video formats are as follows:
- Flash supports rtmp or HTTP flv live broadcast. Delay ~ 3 seconds.
- H5 supports M3u8 live broadcast. Delay ~ 15 seconds.
Watch stable, not Caton
There may be many reasons for video live broadcast jamming, including live broadcast terminal, network and viewing terminal.
Live broadcast terminal
The main problems are too low hardware configuration, streaming parameter configuration, and asynchronous audio and video timestamps. It can be solved by the following measures:
- Upgrade hardware and software settings to improve compatibility and fault tolerance (this part is hard installed, and good streaming quality can only be achieved with good equipment).
- Use hard coding and hard decoding scheme to make full use of GPU acceleration.
- Reduce the video bit rate, choose smooth, standard definition image quality, or use dynamic bit rate to push the stream.
network
The main problems are network jitter and long link between streaming server and viewing end, which can be solved by the following measures:
- Select a stable operator network and reasonably arrange CDN nodes.
- Use sufficient network bandwidth.
Viewing end
When watching video on the network, the buffer is to store part of the video data in advance when you watch the video, and then play the picture when the data reaches a certain amount, so as to play more smoothly. If the setting is too small, it will not play smoothly and continuously when the network is unstable; If the setting is too large, the delay will be accumulated. So set a moderate buffer.
// Flash netStream.bufferTime = 1 // Unit: Second // FLV.js flvjs.createPlayer({ type: 'flv', isLive: true, url: 'video.flv' },{ stashInitialSize: 120 // Default: 384KB })
Low latency and high concurrency
We know that video is actually composed of images frame by frame. RTMP is based on TCP and will not lose packets. Therefore, when the network state is poor, the server will cache the packets. When the network condition is good, it will be sent to the viewing end together, resulting in too many video frame data accumulated at the viewing end, and the delay increases with time. For this problem, in addition to setting the appropriate buffer length mentioned above, frame chasing and frame dropping operations can also be added to realize playback chasing.
Flash code:
// Flash realizes frame tracing: the timer polls and detects that when the current buffer length is greater than 30 seconds, it reconnects and pulls the live stream again netStream.bufferTimeMax = 0.1 // Set bufferTimeMax active frame tracking if(netStream.bufferLength > 30) { // Buffer length greater than 30, reconnect reconnectStream() }
H5 Code:
// H5 realizes frame tracing. If the difference between the end time of the current buffer and the current time exceeds 5 seconds, the frame will be traced if (video.buffered.length > 0 && video.buffered.end(0) - video.currentTime > 5) { // If the live stream time is close to the buffer time, the picture is easy to get stuck, so be on the safe side - 1 second video.currentTime = video.buffered.end(0) - 1; }
In addition, if you use FLV.js to play video, you can turn on its Worker feature, multi-threaded parsing, optimize latency, and reduce buffer.
// FLV.js flvjs.createPlayer({ type: 'flv', isLive: true, url: 'video.flv' },{ enableWorker: true, enableStashBuffer: false, stashInitialSize: 120 // Default: 384KB })
chat room
Instant chat IM service should not only ensure real-time and reliability, but also resist high concurrency. In the implementation process, we use the following methods to solve the problem.
1. WebSocket is the preferred transmission mode. If it is not supported, it will be degraded to polling.
const io = require('socket.io')({ "transports":['websocket', 'polling']})
2. The Node.js server has low performance due to large message concurrency.
The following scheme greatly optimizes the stability and reliability of the chat room.
(1) Features using namespaces
The function of namespace is to limit the propagation of messages within a certain range. Adding a namespace to some messages that do not need to be received globally can greatly save resource transmission.
// Create namespace const io = require('socket.io')() const adminNamespace = io.of('/admin') adminNamespace.to('level1').emit('an event', { some: 'data' })
(2) Chat message queue
When the audience enters the chat room, the room will broadcast the login message. For example, there are 2W people in the room at the same time. When each person logs in, they should broadcast "I" login to everyone in the room, which is equivalent to sending 2W messages. If the amount of concurrency is large, it requires very high server performance. Using chat queue message batch display can prevent processing a large number of messages at the same time and improve processing performance.
// Message queue let scoektMsgArr = [{ EVENT: 'SPEAK', uid: socketId, content: 'This is the first chat message' },...] let minCount = 0 setInterval(()=>{ const maxCount = minCount + 100 const newScoektMsgArr = scoektMsgArr.slice(minCount, maxCount) newScoektMsgArr.forEach((item) => { socket.emit('message', JSON.stringify(item)) }) }, 1000)
(3) Server resiliency
Offer the last big move. Those that can be optimized have been optimized. The rest is to configure the server to play (jia), stretch (fu) and shrink (qi).
3. Drop line reconnection mechanism.
Dropping the line will trigger the discrete event. Listen to it and create a socket connection. Heartbeat check is to send a message regularly to maintain the connection status.
// Keep your heart beating setInterval(()=>{ socket.emit('message', JSON.stringify({ EVENT: 'HEARTBEAT', uid: socketId })) }, 30 * 60 * 1000) // Disconnect and reconnect socket.on('disconnect', () => { this.connect() }) connect() { socket.on('connect', () => { //TODO }) }
POLYV SDK to quickly build an online live broadcasting room
As mentioned above, there are many details to consider in building a live studio, including collection and streaming, CDN distribution, playback experience optimization, chat room performance optimization, etc. Don't worry. Calling the POLYV SDK can quickly build a live studio.
(you need to use POLYV live video service first Free account registration)
STEP1 embedded player:
<script src=""></script> <div id='player'></div> <script> var player = polyvObject('#player').livePlayer({ 'width':'498', 'height':'409', 'uid':'e3wx706i3v', 'vid':'268682' // polyv live channel number }); </script>
STEP2 embedded chat room:
// Default style <link rel="stylesheet" href=""> <script src=""></script> <div id="wrap"></div> var chatroom = new PolyvChatRoom({ roomId: 268682, userId: 153075602311, nick: 'tourist', pic: '', token: token, container: '#wrap', width: 300, height: 600, userType: '', roomMessage: function(data) { // TODO // data is the chat room socket message. This method will be triggered when there is a chat room message console.log(data); } });
As shown in the above figure, the live broadcast room can be created by embedding the live broadcast SDK + chat room SDK. The chat room SDK has its own default skin, send expression, like, send flowers, online list, question and other functions. In addition, for other functions required for live education scenes, such as answer cards, check-in, etc., you can listen to the socket message in the chat room and customize the implementation:
1. Answer sheet
// Monitor answer content var chatroom = new PolyvChatRoom({ roomId: 268682, userId: 153075602313, nick: 'student_1', pic: '', token: token, container: '#wrap', width: 300, height: 600, userType: '', roomMessage: function(data) { // Listen for chat messages switch(data.EVENT){ case 'GET_TEST_QUESTION_RESULT': // Get the content of the answer sheet and display the answer sheet break; case 'GET_TEST_QUESTION_RESULT': // Obtain the answer sheet results and display the answer results break; } } }); // Send answer results chatroom.socket.emit('message', JSON.stringify({ EVENT: 'ANSWER_TEST_QUESTION', roomId: channelId, nick: nick, userId: userId, option: result, questionId: questionId }));
2. Sign in
// Sign in initiated by the live broadcast terminal roomMessage: function(data) { // Listen for chat messages switch(data.EVENT){ case 'SIGN_IN': // Initiate sign in break; case 'STOP_SIGN_IN': // Stop signing in break; } } // Audience sign in chatroom.socket.emit('message', JSON.stringify({ EVENT: 'TO_SIGN_IN', roomId: roomId, checkinId: checkinId, user: { userId: 123456, nick: 'polyv' } }));
Applet
In addition to the browser side, we also provide the corresponding SDK on the applet side.
download Applet SDK After that, the calling component quickly generates live broadcast rooms including players, chat rooms and other functions.
// Embedded polyv page component <view> <polyv /> </view> // Initialization data import plv from '*/polyv-sdk/index'; // onLoad onLoad() { const options = { channelId: '', // Channel ID openId: '', // User openId userName: '', // user name avatarUrl: '' // User Avatar }; plv.init(options); } // onUnload onUnload() { plv.destory(); }
Summary:
If the basic function of educational live broadcasting is realized by completely self-research, it needs at least a technical team of 10 and a product operation team of 5 to complete the launch of the product within 3 months. It takes at least hundreds of thousands or even millions. POLYV provides enterprises with comprehensive solutions and relevant documents to achieve fast access and easily open online education live broadcast.
Information:
Live broadcast using flv.js
Technology and optimization behind the second opening of live video
Check | https://programmer.help/blogs/how-to-build-an-online-live-broadcasting-room-technical-post.html | CC-MAIN-2021-43 | refinedweb | 1,694 | 54.52 |
Free Open Source Electronic Document Management System
Project description
Mayan EDMS NG is a modern fork of Mayan EDMS focused on stability, perfomance and new features.
Mayan EDMS is a document management system. Its main purpose is to store, introspect, and categorize files, with a strong emphasis on preserving the contextual and business information of documents. It can also OCR, preview, label, sign, send, and receive thoses files. Other features of interest are its workflow system, role based access control, and REST API.
The easiest way to use Mayan EDMS is by using the official Docker image. Make sure Docker is properly installed and working before attempting to install Mayan EDMS.
For the complete set of installation, configuration, upgrade, and backup instructions visit the Mayan EDMS Docker Hub page at:
Hardware requirements
- 2 Gigabytes of RAM (1 Gigabyte if OCR is turned off).
- Multiple core CPU (64 bit, faster than 1 GHz recommended).
Important links
- Videos
- Documentation
- Paid support
- Roadmap
- Contributing
- Community forum
- Community forum archive
- Source code, issues, bugs
- Plug-ins, other related projects
- Translations
3.0.2 (2018-03-22)
- Fix event and document states apps migration depedencies.
- Add the “to=” keyword argument to all ForeignKey, ManayToMany and OneToOne Fields.
3.0.1 (2018-03-22)
- Remove squashed migrations. This Django feature is not yet ready for production use.
- Fix “check for update” feature.
- Add Makefile target to check the format of the README.rst file.
- Fix carousel item height issues.
- Place the page number summary at the bottom of the carousel pages.
3.0 (2018-03-19)
- Fix permission filtering when performing document page searching.
- Fix cabinet detail view pagination.
- Update project to work with Django 1.11.11.
- Fix deprecations in preparation for Django 2.0.
- Improve permission handling in the workflow app.
- The checkedout detail view permission is now required for the checked out document detail API view.
- Switch to a resource and service based API from previous app based one.
- Add missing services for the checkout API.
- Fix existing checkout APIs.
- Update API vies and serializers for the latest Django REST framework version. Replace DRF Swagger with DRF-YASG.
- Update to the latest version of Pillow, django-activity-stream, django-compressor, django-cors-headers, django-formtools, django-qsstats-magic, django-stronghold, django-suit, furl, graphviz, pyocr, python-dateutil, python-magic, pytz, sh.
- Update to the latest version the packages for building, development, documentation and testing.
- Add statistics script to produce a report of the views, APIs and test for each app.
- Merge base64 filename patch from Cornelius Ludmann.
- SearchModel retrun interface changed. The class no longer returns the result_set value. Use the queryset returned instead.
- Squash migrations for apps: acls(1-2), checkouts(1-2), converter(1-12), django_gpg(1-6), document_parsing(1-2), document_states(1-2), dynamic_search(1-3), motd(1-5), permissions(1-3), sources(1-16).
- Update to Font Awesome 5.
- Turn Mayan EDMS into a single page app.
- Split base.js into mayan_app.js, mayan_image.js, partial_navigation.js.
- Add a HOME_VIEW setting. Use it for the default view to be loaded.
- Fix bug in document page view. Was storing the URL and the querystring as a single url variable.
- Use history.back instead of history.go(-1).
- Don’t use the previous variable when canceling a form action. Form now use only javascript’s history.back().
- Add template and modal to display server side errors.
- Remove the unused scrollable_content internal feature.
- Remove unused animate.css package.
- Add page loading indicator.
- Add periodic AJAX workers to update the value of the notifications link.
- Add notification count inside a badge on the notification link.
- Add the MERC specifying javascript library usage.
- Documents without at least a version are not scanned for duplicates.
- Use a SHA256 hex digest of the secret key at the name of the lockfile. This makes the generation of the name repeatable while unique between installations.
- Squashed apps migrations.
- Convert document thumbnails, preview, image preview and staging files to template base widgets.
- Unify all document widgets.
- Display resolution settings are now specified as width and height and not a single resolution value.
- Printed pages are now full width.
- Move the invalid document markup to a separate HTML template.
- Update to Fancybox 3.
- Update to jQuery 3.3.1
- Move transfomations to their own module.
- Split documents.tests.test_views into base.py, test_deleted_document_views.py, test_document_page_views.py, test_document_type_views.py, test_document_version_views.py, test_document_views.py, test_duplicated_document_views.py
- Sort smart links by label.
- Rename the internal name of the document type permissions namespace. Existing permissions will need to be updated.
- Add support for OR type searches. Use the “OR” string between the terms. Example: term1 OR term2.
- Removed redundant permissions checks.
- Move the page count display to the top of the image.
- Unify the way to gather the project’s metadata. Use mayan.__XX__ and a new common tag named {% project_information ‘’ %}
- Update logo.
- Return to the same source view after uploading a document.
- Add new WizardStep class to decouple the wizard step configuration.
- Add support for deregister upload wizard steps.
- Add wizard step to insert the document being uploaded to a cabinet.
- Fix documentation formatting.
- Add upload wizard step chapte.
- Improve and add additional diagrams.
- Change documenation theme to rtd.
2.8 (2018-02-27)
- Rename the role groups link label from “Members” to “Groups”.
- Rename the group users link label from “Members” to “Users”.
- Don’t show full document version label in the heading of the document version list view.
- Show the number of pages of a document and of document versions in the document list view and document versions list views respectively.
- Display a document version’s thumbnail before other attributes.
- User Django’s provided form for setting an users password. This change allows displaying the current password policies and validation.
- Add method to modify a group’s role membership from the group’s view.
- Rename the group user count column label from “Members” to “Users”.
- Backport support for global and object event notification. GitLab issue #262.
- Remove Vagrant section of the document. Anything related to Vagrant has been move into its own repository at:
- Add view to show list of events performed by an user.
- Allow filtering an event list by clicking on the user column.
- Display a proper message in the document type metadata type relationship view when there are no metadata types exist.
- Improved styling and interaction of the multiple object action form.
- Add checkbox to allow selecting all item in the item list view.
- Rename project to Mayan EDMS NG.
2.7.3 (2017-09-11)
- Fix task manager queue list view. Thanks to LeVon Smoker for the report.
- Fix resolved link class URL mangling when the keep_query argument is used. Thanks to Nick Douma (LordGaav) for the report and diagnostic information. Fixes source navigation on the document upload wizard.
2.7.2 (2017-09-06)
- Fix new mailer creation view. GitLab issue #431. Thanks to Robert Schöftner (@robert.schoeftner) for the report and the solution.
- Consolidate intial document created event and the first document properties edited events. Preserve the user that initially creates the document. GitLab issue #433. Thanks to Jesaja Everling (@jeverling) for the report.
- Sort the list of root cabinets. Thanks to Thomas Plotkowiak for the request.
- Sort the list of a document’s cabinets.
- Display a document’s cabinet list in italics. GitLab issue #435. Thanks to LeVon Smoker for the request.
- Install mock by default to allow easier testing of deployed instances.
2.7.1 (2017-09-03)
- Support unicode in URL querystring. GitLab issue #423. Thanks to Gustavo Teixeira (@gsteixei) for the find.
- Import errors during initialization are only ignored if they are cause by a missing local.py. Thanks to MacRobb Simpson for the report and solution.
- Make sure the local.py created used unicode for strings by default. GitLab issue #424. Thanks to Gustavo Teixeira (@gsteixei) for the find.
2.7 (2017-08-30)
- Add workaround for PDF with IndirectObject class. GitLab issue #417.
- Shows the cabinets in the document list. GitLab #417 @corneliusludmann
- setting. GitHub issues #256 #257 GitLab issue #416.
- Add support for workflow triggers.
- Add support for workflow actions.
- Add support for rendering workflows.
- extenstion when downloading a document version. GitLab #415.
- Split OCR app into OCR and parsing.
- Remove Folders app.
- Use the literal ‘System’ instead of the target name when the action user in unknown.
- Remove the view to submit all document for OCR.
- When changing document types, don’t delete the old metadata that is also found in the new document type. GitLab issue #421.
- Add tag attach and tag remove events.
- Change the permission needed to attach and remove tags.
- Add HTTP POST workflow state action.
- Add access control grant workflow state action.
- Beta Python 3 support.
2.6.4 (2017-07-26)
- Add missing replacements of reverse to resolve_url.
2.6.3 (2017-07-25)
- Add makefile target to launch a PostgreSQL container.
- Use resolve_url instead of redirect to resolve the post login URL.
- Make the intialsetup and performupgrade management tasks work with signals to allow customization from 3rd party apps.
- PEP8 cleanups.
- Add tag_ids keyword argument to the Source.handle_upload model method. GitLab issue #413.
- Add overflow wrapping so wrap long titles in Firefox too.
- Makes Roles searchable. GitLab issue #402.
- Add line numbers to the debug and production loggers. Add date and time to the production logger.
- Add support for generating setup.py from a template. GitLab #149 #200.
- Add fade in animation to document images.
2.6.2 (2017-07-19)
- Fix deprecation warning to prepare upgrade to Django 1.11 and 2.0.
- Fix document page zoom.
- Add support to run tests against a MySQL, Postgres or Oracle.
- Oracle database compatibility update in the cabinets app. GitHub #258.
2.6.1 (2017-07-18)
- Fix issue when editing or removing metadata from multiple documents.
2.6 (2017-07-18)
- Fix HTML mark up in window title. GitLab #397.
- Add support for emailing documents to a recipient list. GitLab #396.
- Backport metadata widget changes from @Macrobb. GitLab #377.
- Make users and group searchable.
- Add support for logging errors during in production mode. Add COMMON_PRODUCTION_ERROR_LOG_PATH to control path of log file. Defaults to mayan/error.log.
- Add support logging request exceptions.
- Add document list item view.
- Sort setting by namespace label and by global name second.
- Sort indexes by label.
- Fix cabinets permission and access control checking.
- The permission to add or remove documents to cabinets now applies to documents too.
- Equalize dashboard widgets heights.
- Switch the order of the DEFAULT_AUTHENTICATION_CLASSES of DRF. GitLab #400.
- Backport document’s version list view permission.
- Improve code to unbind menu entries.
- Renamed the document type permission namespace from “Document setup” to “Document types”.
- Add support for granting the document type edit, document type delete, and document type view permissions to individual document type instances.
- Improved tests by testing for accesses.
- Increase the size of the mailing profile label field to 128 characters.
2.5.2 (2017-07-08)
- Improve new document creation signal handling. Fixes issue with duplicate scanning at upload.
2.5.1 (2017-07-08)
- Update release target due to changes in PyPI.
2.5 (2017-07-07)
- Add view to download a document’s OCR text. GitLab #215
- Add user configurable mailer. GitLab #286.
- Use Toasts library for screen messages.
- Reduce verbosity of some debug messages.
- Add new lineart transformation.
- Fix SANE source resolution field.
- About and Profile menu reorganization.
- PDF compatibility improvements.
- Office document coversion improvements.
- New metadata type setup UI.
- Duplicated document scan support.
- Forgotten password restore via email.
- Document cache disabling.
- Translation improvements.
- Image loading improvements.
- Lower Javascript memory utilization.
- HTML reponsive layout improvements.
- Make document deletion a background task.
- Unicode handling improvements.
- Python3 compatilibyt improvements.
- New screen messages using Toastr.
2.4 (2017-06-23)
- Add Django-mathfilters.
- Improve render of documents with no pages.
- Add SANE scanner document source.
- Added PDF orientation detection. GitLab issue #387.
- Fix repeated permission list API URL. GitLab issue #389.
- Fix role creation API endpoint not returning id. GitLab issue #390.
- Make tags, metadata types and cabinets searchable via the dynamic search API. GitLab issue #344.
- Add support for updating configuration options from environment variables.
- Add purgelocks management command. GitLab issue #221.
- Fix index rebuilding for multi value first levels. GitLab issue #391.
- Truncate views titles via the APPEARANCE_MAXIMUM_TITLE_LENGTH setting. GitLab issue #217.
- Add background task manager app. GitLab issue #132.
- Add link to show a document’s OCR errors. GitLab issue #291.
2.3 (2017-06-08)
- Allow for bigger indexing expression templates.
- Auto select checkbox when updating metadata values. GitLab issue #371.
- Added support for passing the options allow-other and allow-root to the FUSE index mirror. GitLab issue #385
- Add support for check for the latest released version of Mayan from the About menu.
- Support for rebuilding specific indexes. GitLab issue #372.
- Rewrite document indexing code to be faster and use less locking.
- Use a predefined file path for the file lock.
- Catch documents with not document version when displaying their thumbnails.
- Document page navigation fix when using Mayan as a sub URL app.
- Add support for indexing on workflow state changes.
- Add search model list API endpoint.
2.2 (2017-04-26)
- Remove the installation app (GitLab #301).
- Add support for document page search
- Remove recent searches feature
- Remove dependency on the django-filetransfer library
- Fix height calculation in resize transformation
- Improve upgrade instructions
- New image caching pipeline
- New drop down menus for the documents, folders and tags app as well as for the user links.
- New Dashboard view
- Moved licenses to their own module in every app
- Update project to work with Django 1.10.4.
- Tags are alphabetically ordered by label (GitLab #342).
- Stop loading theme fonts from the web (GitLab #343).
- Add support for attaching multiple tags (GitLab #307).
- Integrate the Cabinets app.
2.1.11 (2017-03-14)
- Added a quick rename serializer to the document type API serializer.
- Added per document type, workflow list API view.
- Mayan EDMS was adopted a version 1.1 of the Linux Foundation Developer Certificate of Origin.
- Added the detail url of a permission in the permission serializer.
- Added endpoints for the ACL app API.
- Implemented document workflows transition ACLs. GitLab issue #321.
- Add document comments API endpoints. GitHub issue #249.
- Add support for overriding the Celery class.
- Changed the document upload view in source app to not use the HTTP referer URL blindly, but instead recompose the URL using known view name. Needed when integrating Mayan EDMS into other app via using iframes.
- Addes size field to the document version serializer.
- Removed the serializer from the deleted document restore API endpoint.
- Added support for adding or editing document types to smart links via the API.
2.1.10 (2017-02-13)
- Update Makefile to use twine for releases.
- Add Makefile target to make test releases.
2.1.9 (2017-02-13)
- Update make file to Workaround long standing pypa wheel bug #99
2.1.8 (2017-02-12)
- Fixes in the trashed document API endpoints.
- Improved tags API PUT and PATCH endpoints.
- Bulk document adding when creating and editing tags.
- The version of django-mptt is preserved in case mayan-cabinets is installed.
- Add Django GPG API endpoints for singing keys.
- Add API endpoints for the document states (workflows) app.
- Add API endpoints for the messsage of the day (MOTD) app.
- Add Smart link API endpoints.
- Add writable versions of the Document and Document Type serializers (GitLab issues #348 and #349).
- Close GitLab issue #310 “Metadata’s lookup with chinese messages when new document”
2.1.7 (2017-02-01)
- Improved user management API endpoints.
- Improved permissions API endpoints.
- Improvements in the API tests of a few apps.
- Addition Content type list API view to the common app.
- Add API endpoints to the events app.
- Enable the parser and validation fields of the metadata serializer.
2.1.6 (2016-11-23)
- Fix variable name typo in the rotation transformation class.
- Update translations
2.1.5 (2016-11-08)
- Backport resize transformation math operation fix (GitLab #319).
- Update Pillow to 3.1.2 (Security fix).
- Backport zoom transformation performance improvement (GitLab #334).
- Backport trash can navigation link resolution fix (GitLab #331).
- Improve documentation regarding the use of GPG version 1 (GitLab #333).
- Fix ACL create view HTML response type. (GitLab #335).
- Expland staging folder and watch folder explanation.
2.1.4 (2016-10-28)
- Add missing link to the 2.1.3 release notes in the index file.
- Improve TempfileCheckMixin.
- Fix statistics namespace list display view.
- Fix events list display view.
- Update required Django version to 1.8.15.
- Update required python-gnupg version to 0.3.9.
- Improved orphaned temporary files test mixin.
- Re-enable and improve GitLab CI MySQL testing.
- Improved GPG handling.
- New GPG backend system.
- Minor documentation updates.
2.1.3 (2016-06-29)
-.
- Fix GitLab issue #309, “Temp files quickly filling-up my /tmp (1GB tmpfs)”.
- Explicitly check for residual temporary files in tests.
- Add missing temporary file cleanup for office documents.
- Fix file descriptor leak in the document signature download test.
2.1.2 (2016-05-20)
- Sort document languages and user profile locale language lists. GitLab issue #292.
- Fix metadata lookup for {{ users }} and {{ group }}. Fixes GitLab #290.
- Add Makefile for common development tasks
2.1.1 (2016-05-17)
- Fix navigation issue that make it impossible to add new sources. GitLab issue #288.
- The Tesseract OCR backend now reports if the requested language file is missing. GitLab issue #289.
- Ensure the automatic default index is created after the default document type.
2.1 (2016-05-14)
- Upgrade to use Django 1.8.13. Issue #246.
- Upgrade requirements.
- Remove remaining references to Django’s User model. GitLab issue #225
- Rename ‘Content’ search box to ‘OCR’.
- Remove included login required middleware using django-stronghold instead ().
- Improve generation of success and error messages for class based views.
- Remove ownership concept from folders.
- Replace strip_spaces middleware with the spaceless template tag. GitLab issue #255
- Deselect the update checkbox for optional metadata by default.
- Silence all Django 1.8 model import warnings.
- Implement per document type document creation permission. Closes GitLab issue #232.
- Add icons to the document face menu links.
- Increase icon to text spacing to 3px.
- Make document type delete time period optional.
- Fixed date locale handling in document properties, checkout and user detail views.
- Add new permission: checkout details view.
- Add HTML5 upload widget. Issue #162.
- Add Message of the Day app. Issue #222
- Update Document model’s uuid field to use Django’s native UUIDField class.
- Add new split view index navigation
- Newly uploaded documents appear in the Recent document list of the user.
- Document indexes now have ACL support.
- Remove the document index setup permission.
- Status messages now display the object class on which they operate not just the word “Object”.
- More tests added.
- Handle unicode filenames in staging folders.
- Add staging file deletion permission.
- New document_signature_view permission.
- Add support for signing documents.
- Instead of multiple keyservers only one keyserver is now supported.
- Replace document type selection widget with an opened selection list.
- Add mailing documentation chapter.
- Add roadmap documentation chapter.
- API updates.
2.0.2 (2016-02-09)
- Install testing dependencies when installing development dependencies.
- Fix GitLab issue #250 “Empty optional lookup metadata trigger validation error”.
- Fix OCR API test.
- Move metadata form value validation to .clean() method.
- Only extract validation error messages from ValidationError exception instances.
- Don’t store empty metadata value if the update checkbox is not checked.
- Add 2 second delay to document version tests to workaround MySQL limitation.
- Strip HTML tags from the browser title.
- Remove Docker and Docker Compose files.
2.0.1 (2016-01-22)
- Fix GitLab issue #243, “System allows a user to skip entering values for a required metadata field while uploading a new document”
- Fix GitLab issue #245, “Add multiple metadata not possible”
- Updated Vagrantfile to provision a production box too.
2.0 (2015-12-04)
- New source homepage:
- Update to Django 1.7
- New Bootstrap Frontend UI
- Easier theming and rebranding
- Improved page navigation interface
- Menu reorganization
- Removal of famfam icon set
- Improved document preview generation
- Document submission for OCR changed to POST
- New YAML based settings system
- Removal of auto admin creation as separate app
- Removal of dependencies
- ACL system refactor
- Object access control inheritance
- Removal of anonymous user support
- Metadata validators refactor
- Trash can support
- Retention policies
- Support for sharing indexes as FUSE filesystems
- Clickable preview images titles
- Removal of eval
- Smarter OCR, per page parsing or OCR fallback
- Improve failure tolerance (not all Operational Errors are critical now)
- RGB tags
- Default document type and default document source
- Link unbinding
- Statistics refactor
- Apps merge
- New signals
- Test improvements
- Indexes recalculation after document creation too
- Upgrade command
- OCR data moved to ocr app from documents app
- New internal document creation workflow return a document stub
- Auto console debug logging during development and info during production
- New class based and menu based navigation system
- New class based transformations
- Usage of Font Awesome icons set
- Management command to remove obsolete permissions: purgepermissions
- Normalization of ‘title’ and ‘name’ fields to ‘label’
- Improved API, now at version 1
- Invert page title/project name order in browser title
- Django’s class based views pagination
- Reduction of text strings
- Removal of the CombinedSource class
- Removal of default class ACLs
- Removal of the ImageMagick and GraphicsMagick converter backends
- Remove support for applying roles to new users automatically
- Removal of the DOCUMENT_RESTRICTIONS_OVERRIDE permission
- Removed the page_label field
1.1.1 (2015-05-21)
- Update to Django 1.6.11
-
1.1 (2015-02-10)
- Uses Celery for background tasks
- Removal of the splash screen
- Adds a home view with common function buttons
- Support for sending and receiving documents via email
- Removed custom logging app in favor of django-actvity-stream
- Adds watch folders
- Includes Vagrant file for unified development and testing environments
- Per user locale profile (language and timezone)
- Includes news document workflow app
- Optional and required metadata types
- Improved testings. Automated tests against SQLite, MySQL, PostgreSQL
- Many new REST API endpoints added
- Simplified text messages
- Improved method for custom settings
- Addition of CORS support to the REST API
- Per document language setting instead of per installation language setting
- Metadata validation and parsing support
- Start of code updates towards Python 3 support
- Simplified UI
- Stable PDF previews generation
- More technical documentation
1.0 (2014-08-27)
- New home @
- Updated to use Django 1.6
- Translation updates
- Custom model properties removal
- Source code improvements
- Removal of included 3rd party modules
- Automatic testing and code coverage check
- Update of required modules and libraries versions
- Database connection leaks fixes
- Support for deletion of detached signatures
- Removal of Fabric based installations script
- Pluggable OCR backends
- OCR improvements
- License change, Mayan EDMS in now licensed under the Apache 2.0 License
- PyPI package, Mayan EDMS in now available on PyPI:
- New REST API
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/mayan-edms-ng/ | CC-MAIN-2018-39 | refinedweb | 3,832 | 53.47 |
Primavera database logon failed jobs
Hi swat4dev, I noticed your profile and would like to talk to you about a logon, profile iOS app. We can discuss the details over chat.
i have problem with my outlook. it seems very easy but i dont want make something wrong Failed to register VB Script DLL .. its says Reinstall or run Regsvr32,exe [login to view URL] to self register. only get this problems with
Redirect folder "Can not create folder "ServerNameRedirected_User_FilesUserNameDesktop" Error details: "Access is denied. OS: Windows 7 x64 + "$" endif /* Map...
You can see the error here: [login to view URL] Site uses Yii, PHP and Mysql | https://www.freelancer.com/job-search/primavera-database-logon-failed/ | CC-MAIN-2018-34 | refinedweb | 107 | 74.9 |
Convert java .properties files to javascript
"JavaScript isn't a great way to store configuration data. That's because the syntax is still that of a programming language, so you need to be sure you haven't introduced syntax errors. If you end up concatenating JavaScript files together, a syntax error in a single line breaks the overall application" ( Nicholas C. Zakas, Maintainable JavaScript, Writing Readable Code, O'Reilly Media, May-properties --save-dev
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
grunt;
In your project's Gruntfile, add a section named
properties to the data object passed into
grunt.initConfig().
grunt
Type:
String
Default value:
'config'
Use a previously defined namespace.
grunt
grunt
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt. | https://www.npmjs.com/package/grunt-properties | CC-MAIN-2017-22 | refinedweb | 154 | 61.36 |
Thread life cycle example in Java explains the life cycle of a Thread using a simple example.Thread life cycle example in Java explains the life cycle of a Thread using a simple example.
In this section we will read about the life cycle example of Thread in Java.
Life cycle of Thread explains you the various stages of Thread in Java. These states are New State, Runnable State, Running State, Blocked State and Dead State.
New State : A Thread is called in new state when it is created. To create a new thread you may create an instance of Thread class or you can create a subclass of Thread and then you can create an instance of your class.
Example :
Thread thread = new Thread();
Newly created thread is not in the running state. To move the thread in running state the start() method is used.
Runnable State : A Thread is called in runnable state when it is ready to run and its waiting to give control. To move control to another thread we can use yield() method.
Example :
Thread thread = new Thread(); thread.yield();
Running State : A Thread is called in running state when it is in its execution mode. In this state control of CPU is given to the Thread. To execute a Thread the scheduler select the specified thread from runnable pool.
Blocked State : A Thread is called in blocked state when it is not allowed to enter in runnable and/or running state. A thread is in blocked state when it is suspend, sleep or waiting.
Example :
Thread thread = new Thread(); thread.sleep();
Dead State : A Thread is called in dead state when its run() method execution is completed. The life cycle of Thread is ended after execution of run() method. A Thread is moved into dead state if it returns the run() method.
We will explain the Life cycle of thread mentioned above using a simple example. This section will contain the line by line description of example.
Example
Here we are giving a simple example of Thread life cycle. In this example we will create a Java class where we will create a Thread and then we will use some of its methods that represents its life cycle. In this example we have used the methods and indicate their purposes with the comment line. In this example you will see we have created two Thread subclasses named A.java and B.java. In both of the classes we have override the run() method and executed the statements. Then I have created a Main.java class where I have created instances of both classes and uses the start() method to move the threads into running state, yield() method to move the control to another thread, sleep() method to move into blocked state. And after successfully completion of run() method the Thread is automatically moved into Dead state.
A.java
public class A extends Thread { public void run() { System.out.println("Thread A"); System.out.println("i in Thread A "); for(int i=1;i<=5;i++) { System.out.println("i = " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Thread A Completed."); } }
B.java
public class B extends Thread { public void run() { System.out.println("Thread B"); System.out.println("i in Thread B "); for(int i=1;i<=5;i++) { System.out.println("i = " + i); } System.out.println("Thread B Completed."); } }
Main.java
public class Main { public static void main(String[] args) { //life cycle of Thread // Thread's New State A threadA = new A(); B threadB = new B(); // Both the above threads are in runnable state //Running state of thread A & B threadA.start(); //Move control to another thread threadA.yield(); //Bolcked State of thread B try { threadA.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } threadB.start(); System.out.println("Main Thread End"); } }
Output
When you will execute the above Java class (Main.java) you will get the output as follows :
Ads | https://www.roseindia.net/java/thread/thread-life-cycle-example.shtml | CC-MAIN-2021-39 | refinedweb | 672 | 67.25 |
DIY, June 2013
Featuring The National, Disclosure, Gold Panda, Waxahatchee, Jagwar Ma and more
D i s c l o s u r e G o l d P a n d a Wa x a h a t c h e e J a g wa r M a f ree | i s s ue 1 9 | j une 2 013 thisisfakediy.co.uk DIY the national Funny Songs About Death 1 city and colour the hurry and the harm the new album featuring the singles ‘thirst’ and ‘of space and time’ out 3rd june 2013 cookingvinyl.com 2 thisisfakediy.co.uk cityandcolour.com dinealonerecords.com EDITOR’S LETTER Midnight screenings of blockbuster films. Turns out they’re actually quite fun, if the cinema can, y’know, show the movie. Congratulations to the Cineworld at London’s O2, then, for failing to air the end of Iron Man 3’s debut showing. Imagine if we did that with band names. This month you might read our cover feature with seminal US crooners The National without interuption, but you’d also be able to enjoy features with the risque Waxahatch and the culinary genius Gold Pan. We’d be big fans of the Daft Pun album review, but nobody would want to go to Livepoo Sound City. Liverpoo. Snigger. It’s important to finish what you star..... <snip> GOODVSevil What's on the DIY team's radar Victoria Sinden Deputy Editor GOOD: DIY hosted stages at both The Great Escape and Liverpool Sound City last month. Busy busy. evil: Tjfhwefgnu. Thinking of evils is hard. Jake May Deputy Online Editor GOOD: Touching in real life Mac DeMarco during his excellent set at The Great Escape when he jumped into the crowd. evil: Secretly not having the guts to touch in real life Mac DeMarco during his excellent set at The Great Escape when he jumped into the crowd but lying to all of my friends that I did. Jamie Milton Online Editor GOOD: Finishing university, finding refuge in The Great Escape and being as drunk as The Orwells’ frontman, Mario Cuomo. evil: A perfectly good pair of shoes were destroyed during Merchandise’s Great Escape set. It was probably worth it. Louise Mason Art Director GOOD: The volume of Sailing’ on the new Queens Of The Stone Age record is the best kind of funky. GOOD: ‘Smooth evil: I just used the word funky without any irony whatsoever. ‘Get Lucky’ comedy remixes on the internet, obviously peaking with ‘Get Clucky’. evil: The 5am police raid in my hotel at The Great Escape... wrong room, apparently. this issue has been brought to you by... Songs played by Parquet Courts at a secret Great Escape show before being pulled short. Crowds weren’t happy. 4 Days Jamie spent cursing the fact he wasn’t Ryan Hemsworth. 31 2 Photoshoots this month that involved a sheet of glass and a hammer. Smashing. 1 1 Members of The People Jake attempted Minutes Stephen spent to give love bites to thinking Jamie wanted National on which we have photoshopped at The Great Escape. to be Thor (Chris sunglasses. Gross, Jake. Hemsworth). 3 15 co n t e n ts 6 t h e g r e at es ca p e 12 k i l l e r m i k e 14 c i t y a n d c o l o u r 18 s p e c t r a l s 20 b i g d e a l 22 f e s t i v a l s 24 a r t h u r b e a t r i c e 28 m s m r 29 c l e a n b a n d i t 32 t h e n a t i o n a l 40 W a x a h a t c h e e 44 G o l d P a n d a 48 J a g w a r M a 50 E m p i r e O f T h e s u n 54 D i s c l o s u Andrew Jones, Anna Byrne, Coral Williamson, Danny Wright, David Zammitt, George Smale, Hannah Phillips, Hugh Morris, Jack McKenna, Jack Parker, Jon Hatchman, Laura Eley, Martyn Young, Matthew Bridson, Matthew Davies, Sam Cornforth, Shefali Srivastava, Tom Doyle, Tom Walters, Will Richards Photographers Carolina Faruolo, Fraser Stephen, Hannah Cordingley, Leah Henson, Mike Massaro, Sam Bond For DIY editorial info@thisisfakediy.co.uk tel: +44 (0)20 76137248. r eg ul ars 6 n e w s 24 n e u r e v i e w s 60 a l b u m s 70 l i v e 78 f i l m s 80 g a m e s 4 thisisfakediy.co.uk 5 NEWS photos: mike massaro, emma swann O n e o f t h e b i gg e s t a n d m o s t e x c i t i n g f e s t i va l s f o r n e w m u s i c , t h i s y e a r ’ s e d i t i o n o f B r i g h t o n ’ s T h e G r e at E s c a p e p r o v e s n o d i f f e r e n t. E m b l a zo n e d o n t h e l e g i o n o f t o t e b ag s c a r r i e d ac r o s s t h e c i t y a r e t h e l i k e s o f M e r c h a n d i s e , Pa r q u e t Co u r t s , M Ø, CHVRCHES , a n d S u p e r f ood. I f a b u z z b a n d i s n ’ t p l ay i n g t h e s o u t h c oa s t o f E n g l a n d t h i s w e e k e n d, t h e y ’ r e n o t wo r t h b o t h e r i n g w i t h . THE GREAT ESCAPE 6 thisisfakediy.co.uk deap vally t doesn’t matter who started the fight, one way or another Superfood (The Haunt, Thursday) are going to finish it. If their Birmingham brethren Peace have proved divisive players over the past twelve months, they’re nothing in comparison to this lot. Like Menswe@r’s genetically perfect test tube baby, whether that’s seen a good or bad thing (or even means anything at all) will more than likely indelibly colour any opinion. For what it’s worth, the four piece do what they do really rather well. Each and every trick from The Big Britpop Handbook is played to perfection. It’s early days still, but the battle lines are undeniably already drawn. I Mac DeMarco (Corn Exchange, Thursday) is an odd live performer. With a cheeky wink and a goofy smile, he’s a character that looks incapable of writing and performing with any kind of self-control - but as soon as a song starts he’s the ideal artist. Songs taken from both of his excellent guitar-pop albums are performed beautifully, making the kind of show that stands hairs on end. Although it’s a set fairly void of his usual messing around (which, it turns out, he saves for his later show at the Green Door Store where he crowd surfs while playing guitar and hangs upside-down from the rafters), the Canadian still manages to incorporate Rammstein’s ‘Du Hast’ into the set and squeeze in a shouty screamo version of ‘Blackbird’ by The Beatles. Excellent fun. They may not be the kind of band you’d expect to see gracing the line-up of a festival like this, but Kingston, Pennsylvania’s Title Fight (Concorde 2, Thursday) are no strangers to straddling genres. Using their brand of aggressive pop punk to meld together the most powerful moments of hardcore and poignant eruptions of shoegaze, the result is chaotic but electrifying; proven by the sheer ferocity of their performance and neverending stream of crowd surfers. Whether it’s in the delicate sentiments of ‘27’, or the mesmerising fuzziness of ‘Head In The Ceiling Fan’, here are a band pushing the boundaries and preconceptions of their genre to a whole new place. “We’re going to start slow and then get fast,” says Raph Standell-Preston, one half of Montreal duo Blue Hawaii (Brighthelm Centre, Thursday) at the start of their set. And indeed they do. To begin with it’s all delicate electronics and Standell-Preston’s beautiful, Mac DeMarco 7 news the great escape mournful vocal, before the tempo rises, the bass gets heavier, and the beats louder. By the end it’s more like a nightclub dance set, the everswelling crowd finding it increasingly difficult to not bop their heads and shake their hips. With a queue winding well out of the door, we’re only just lucky enough to squeeze ourselves into Komedia for the second performance of Deap Vally’s (Komedia, Friday) weekend. Dressed perfectly for the summer heat of California, their outfits are maybe a tad optimistic for the weather here in Brighton, but their set still comes packed with enough rock and roll punch to have the whole room working up a sweat. Debuting an array of the explosive tracks from their forthcoming debut full-length ‘Sistrionix’, this hair flailing, head banging duo are nothing short of captivating. You can’t help but wonder how the hell they manage to make such an insatiable racket. deap vally young fathers “The Great Escape was an adventure and we are all really grateful we survived. It was close but we did it.” Superfood By 1am The Haunt has reached its sticky, murky peak, which is ideal considering the band taking to the stage. Rumours abound before the show that Merchandise’s (The Haunt, Friday) Corn Exchange set the previous night wasn’t all that great; that spacious halls weren’t the finest companion to a band sporting fierce, progressive punk. If this was the case, The Haunt provides a polar opposite. Carson Cox looks Terminator-esque in his rectangular sunglasses, spilling water out into the front rows of undying fans. The songs themselves find a fitting home here, particularly when ‘In Nightmare Room’ spills unrelenting energy into the already flailing arms and hoarse, returning voices. 8 thisisfakediy.co.uk If the two skinny guys from Berlin on stage just past Midday on Saturday decided to sport robot outfits, there’s a good chance they could be associated with a ‘Daft Punk mk.II’ arrival. It’s all in the basslines. A venue so dark you can’t see your own tapping shoes comes to life with Roosevelt’s (Komedia, Saturday) expansive electronica. The only downside is the setting itself. It’s so quiet every landing of feet from excitable dancing fans is audible. More ‘Get Louder’ than ‘Get Lucky’, but that’s no disservice to the duo’s disco-filled set. Stumbling into a pitch black venue out of the bright Saturday seaside sun just in time, Teleman (Smack, Saturday) play a short, effortlessly charming afternoon set before their headline show that night. Highlights are new single ‘Steam Train Girl’ and debut ‘Cristina’, with instruments and vocals stripped down with a politely economical fragility, letting the intelligent songwriting shine through. Everything’s got a hook, and every note and word flows with a fun charm. They’re not a band to yell for your attention, though; they’re far too well mannered and busy making perfect pop music. Nothing deters The Orwells (The Haunt, Saturday) tonight. Age barriers certainly didn’t stop these guys - aged between 17 and 18 from getting their hands on some booze in the early evening. Frontman Mario Cuomo races onto the stage, long blonde locks entangled in his microphone wire. “I’m piiiiised”, he openly declares, before kindly clarifying, “in America that means mad, but I’m just really druuuunk”. What follows is a perfectly-wound set, a balancing act between foolish brooke candy concrete knives everything everything 9 carnage and meticulous craft. Beered-up Cuomo doesn’t miss a note, and even amongst a broken string and an air conditioning machine that waves a deadly smell – the collective after-effect of three days of Brighton booze-ups - into the crowd, The Orwells apply astonishing method to their charming madness. we can only describe as a rather bizarre stripping routine (oh, alright, Zachary took his top off ) and we’re not sure what could’ve ended the night better. Well, okay, maybe if they had stayed fully clothed... Strictly speaking an after-party set, all surviving TGE revellers are packed in tight for Parquet CourTS (The Loft, By the time the final band on DIY’s “This is our first time here and it’s Saturday). From start to finish fans stage begins, Audio is pitch black and always exciting to play somewhere chant the New Yorkers’ ‘Stoned And rammed. A mismatch of coloured we haven’t played before. It’s one of Starving’ track in between songs, clothing and variously dyed hair, those festivals that a lot of people talk about and say that it’s a really Swim Deep (Audio, Saturday) even though the centrepiece of the good experience. It’s great to be here!” emerge – a few minutes late, we’ll group’s ‘Light Up Gold’ record doesn’t Temples admit – in front of the packed out make an appearance in their set. The room to showcase their shimmering show is hampered slightly by sound brand of pop, as the home stretch of issues, which prevent an encore. the weekend kicks in. Feeling like a perfect ending to the Those desperately craving something more should be amply weekend’s events, tracks like ‘She Changes The Weather’ and satisfied by the transition from ‘Master Of My Craft’ to ‘The Sea’ are the ideal ditties to have a bit of a dance to, all ‘Borrowed Time’, a highlight of the album that finds true the while proving the band to be one of the most exciting to form in the company of drunken fans bouncing around a emerge from their home scene of B-Town. Throw in what sweaty room after midnight. “The Great Escape was really great! Cav tried to get with Iggy Azalea and failed. We all had a big moment playing the Corn Exchange, for about two seconds I thought I actually was Mick Jagger. I ate so well, fish cakes for breakfast, saveloy for lunch and a cone of salty chips for pudding.” Swim Deep 10 thisisfakediy.co.uk 11 news killer mike A tlanta rapper Killer Mike is the true definition of a contemporary legend in the rap game. From his beginnings more than 10 years ago as an associate of Outkast, Michael Render has progressed to become one of the genre’s most vital, visceral and incendiary voices. Last year’s ‘R.A.P Music’, produced by El-P, is a certified hip hop classic; an album that thrills, questions and provokes. As he prepares to embark on a series of European festival shows, DIY caught up with Mike in his barbershop in Atlanta. It’s now almost a year exactly since ‘R.A.P Music’ was released. What are your feelings on the album now looking back on it with a bit of distance? I’ve been overwhelmed because last year in rap was better than the first 8/9 years of rap put together for me because it featured one of my real rap fantasies; to be one of the premier rappers who is appreciated by real rap fans. How does the dynamic work between El-P’s beats and your rhymes and focus? The simplest explanation I can give you is this: when you hear me on an El-P beat then God meant for those two things to happen. I was made to rap on an El-P beat. It doesn’t mean I won’t ever work with another producer but it’s definitely important to understand my seriousness when it comes to my allegiance. How did you formulate this partnership into something more concrete with Run The Jewels? As a rapper, you like to be in the presence of other rappers. El was going to do a solo EP, so he was starting the process of that and we were talking and kicking it. Somewhere in the whole conversation it came to, “Yo El! Why don’t you let me jump on the whole EP with you?” In less than two weeks, we did the whole entire album. It’s brutal; it’s a lesson in the brutality of rhyme. We’re really going hard. RunThe Jewels K i l l e r M i k e & E l - P h av e b i g p l a n S W o r d s : M a r t y n Yo u n g Run The Jewels sounds like nothing else out there. Is it your intention to go against the mainstream? I think that what we do together is just different and bears no relation to what’s out there because, let’s be honest, what’s out there is just a variation of whatever’s popular. That’s part of what’s plaguing our music. Imitation is the sincerest form of flattery but it’s also a great way to create a shitty formula to create more shitty songs. Killer Mike and El-P’s new album ‘Run The Jewels’ will be released later this year via Fool’s Gold. 12 thisisfakediy.co.uk TV On The Radio Album On The Way W o r d s : Dav i d Z a mm i t t n e b r i e f Rihanna on her upcoming UK tour. The superstar will embark upon a nine date run this summer, with the trio opening her Manchester Arena shows on 12th and 13th July. recorded two new songs.” And what about the type of sounds we’ll be hearing? Adebimpe doesn’t give much away, save to suggest, that they might go a little bit heavier. “Everyone’s always tinkering. I can only speak about the song that I had a bigger part in writing, but there’s sort of a Danzig vibe.” TVOTR have also split from Interscope, their home since 2006 opus, ‘Return To Cookie Mountain’. The effect of their newfound autonomy is immediately telling and Tunde’s excitement is tangible. “Right now we don’t have the pressure of a label being like, ‘You know, you guys should do something.’ Right now, it’s a far clearer and more enriching path. Everyone feels really good about making things again.” Read the full interview in the 6th May issue of DIY Weekly, available now via Apple Newsstand. franz ferdinand have announced plans to release their brand new album ‘Right Thoughts, Right Words, Right Action’ this summer. The Scottish four-piece will follow up 2009’s ‘Tonight’ on 26th August. !!! are going to headline a brand new London festival, Visions; an all-dayer that will take place across three venues, Oval Space, Netil House and New Empowering Church on 10th August. Other acts include Iceage, Still Corners and Micachu. crocodiles will release their brand new album through Frenchkiss Records on 19th August. Their fourth record, ‘Crimes Of Passions’ follows on from the San Diego rockers’ 2012 effort ‘Endless Flowers’. haim have been confirmed to support in w s A lot has been made of the break TV On The Radio intended to take in 2009, but that announcement was followed by a new album, the superb ‘Nine Types Of Light’, and a tour within just two years. Only a week after its release, however, multi-instrumentalist Gerard Smith passed away after a battle with lung cancer. In the context, a sabbatical would be understandable, but they’ve persevered. “I think I mentioned that we were taking a hiatus for a year and that hiatus only ended up being seven months,” the band’s Tunde Adebimpe explains. “Honestly, that’s probably the longest we’ve been not recording or being on the road for about six years.” When it comes to the workings of the band, the group are currently benefitting from a relatively sanguine disposition. “Right now, it feels like a very easy process and it’s great. We were just at Dave [Sitek’s] place and long-awaited follow up to ‘Tarot Sport’ on 22nd July. The duo are set to unveil their new seven-track album, ‘Slow Focus’, ahead of their headlining slot at this year’s ArcTanGent festival. 13 fuck buttons will release the news city and colour 14 thisisfakediy.co.uk the grass i s g r eene r C i t y A n d C o lo u r ’ s Da l l a s G r e e n i s r e a dy to embark upon his fourth solo album; the first album w h e r e h e ’ s t r u ly go i n g i t a l o n e . W o r d s : S a r a h J a m i e s o n . p h o t o : e m m a s wa n n T here aren’t many artists who can claim to lead double lives. While in the genreleading, Canadian post-hardcore outfit Alexisonfire, Dallas Green was also busy working under his own solo guise, City And Colour. It was only after the former’s fourth album ‘Old Crows / Young Cardinals’ was released in 2009, that Green began to feel a bit stretched. By the time he had unveiled his third album as City And Colour – which was, by this point, a full band affair, complete with a world touring schedule to boot – things had become too much. It must’ve been strange to have been playing in two wholly separate bands, which both experienced similar levels of success. “Yeah, definitely, especially as things progressed,” Green tells us. “As City And Colour became this thing of its own, this breathing, living thing... It’s a very interesting way to live. You’re just like, ‘Here are my friends, this is great but I’ve got all of these other songs that I care about, and here are all these people that want to hear them. But I have to go do this. Then I’ll go do this. Alright, I’ll go back to this.’ It’s a very weird process,” he pauses. “I mean, I never expected anyone to like one of the songs that I write, let alone two completely different styles.” The reality of things was a little different: while Green was touring the world in support of Alexisonfire’s most recent full-length, he was also juggling City And Colour’s forthcoming ‘Little Hell’, which would subsequently enter the Canadian charts at Number 1. In the UK, he played to a sold out Royal Albert Hall – tickets for which disappeared in minutes – before returning later that year to play two nights at London’s Roundhouse, at the back end of a full UK tour. People were definitely listening. Sooner rather than later, Green had to put to bed the project he had been involved with for the past decade of his life. With his creative efforts no longer halved, it’s not surprising to learn that the output of his solo guise became much more fluid. Before he even realised, he had enough material for a brand new City And Colour album, and a plan of action to match. “I didn’t think that I was going to make a record so soon after the last one, but at the same time… instead of coming up with ideas for Alexis records, every song idea that was popping into my head was now a new City And Colour song. I guess, that’s sort of why it’s here already. I got home and thought, ‘Jeez, I have all of these songs’.” “I remember calling my managers, Joel and Tricia, in June or July of last year, and saying, ‘I’m gonna make a record before the end of the year.’ They were like, ‘No, you can’t, you’ve got to do the Alexis tour; there’s no time.’ But I was like, ‘I’m doing it! Get me a studio. I’ll do it in November.’ They asked if I was serious, and I said yes, I had all of these songs… If I had gone into the Alexis tour, the farewell tour, not having made this record already, having that in the back of my mind would’ve just been the same thing all over again. I would not have been able to enjoy what we did.” The subject of his previous project also, predictably, rears its head within his forthcoming album’s lyrics. With a history in writing rather candid and autobiographical songs, there was no way that he’d be able to skirt around one of the biggest break-ups in his career. “As I look back, I definitely think there are songs that deal with me leaving Alexisonfire. When I listen to some of the songs, I can hear that longing of searching for something better; something else. Well, not necessarily better - because I don’t [literally] mean that - but searching for happiness. I don’t know what that is: I think I’ll always be searching for that. That’s new ground for me; that’s something that I was exploring.” City And Colour’s new album ‘’The Hurry And The Harm’ will be released on 3rd June via Cooking Vinyl. 15 news eurovision Eurovision 2013: Tumbling Down The Rabbit Hole D e r e k R o b e r t s o n g o e s i n o n a f i e l d t r i p to E u r ov i s i o n 2 0 1 3 , M a l m รถ, S w e d e n . 16 thisisfakediy.co.uk E urovision can, at times, seem like an anachronism, a leftover relic from simpler times and “old” Europe. As recently as the early 1990s, the number of participants hovered around 20; with democracy and selfdetermination that number has more than doubled, the competition now requiring two semi-finals to whittle down the entrants. The sheer size of the event itself is mind-boggling; 200 million TV viewers, 1200 accredited press and photographers, and an estimated 25,000 visiting fans, most of whom have no tickets but are happy just to soak up the vibes at the arena or in one of the many fan areas dotted around the city centre. There are already vast numbers milling about when I arrive at midday, helped no doubt by the presence of Europe’s largest indoor shopping centre next door. The last dress rehearsal kicks off at 1pm and there are no tickets to be had – it’s been sold out for weeks. The press centre, a vast hanger out the back that’s more used to hosting trade fairs and exhibitions, hums with a gentle efficiency as the press pack goes about the very serious business of reporting. Row upon row of desks have been lined up in front of two giant screens, whole areas commandeered by the laying out of flags. An impressive – and delicious – spread of coffee, cake, and biscuits is wolfed down between filming, editing, and recording, TV and radio seemingly the predominant media. I find the UK section, and pull up a chair. The rehearsal goes without a hitch save for Belarusian singer Alyona Lanskaya’s troubles getting out her giant glitter ball, the weekend’s most Spinal Tap moment. Ominously, Britain finishes dead last in the mock vote. I’m told that the points for this are arbitrarily allocated in advance, but it’s hard not to see this as a subconscious slight, and doesn’t bode well given our dismal performances in recent years. Afterwards, a few of the acts pop in to do some fleeting, last minute interviews, but they are heavily guarded by their handlers; rumours abound of illness and lost voices, and they stick to a few brief words with their respective countrymen. Bonnie Tyler, sadly, is nowhere to be seen. I head out into the fading afternoon sun. There’s still three hours to go before the main event, but the carnival is already in full swing. The buzz is palpable, and almost everyone is adorned with flags, face paint, or full on fancy dress. Unsurprisingly the Swedes, festooned in yellow, blue, and all manner of Viking hats and blonde wigs, are the most prominent, but the Brits and Irish run them close. Photos are snapped, friendships made, and even the police – who all carry firearms – are cajoled into posing with comedy props. It’s manic grins all-round, a mass gathering of joyous abandon that’s all the more remarkable considering the lack of alcohol involved; there’s no beer carts, larriness, or swigging from unidentifiable bottles in plastic bags. Everyone seems lucid and clearheaded, high on camaraderie and the impatient excitement of a child waiting for Christmas morning. Taking my seat high in the Gods, it becomes clear that Eurovision is a spectacle like no other. As the arena steadily fills, the anticipation builds like a crescendo, so real you can almost reach out and touch it. ‘Electric’ is a word too easily thrown about these days, but this truly is. I’ve yet to experience a mega gig by any of pop’s current big hitters – Gaga, Beyonce, Rihanna – but the scale, ambition, and technical brilliance of a show that’s not just a concert, but a live broadcast event to 150 countries is breathtaking. There are pyrotechnics, glitter bombs, and lights constantly rising and falling. A giant LED screen is synced to an array of special effects and an army of technicians scuttle around between songs with leaf blowers, instruments and mops, thirty seconds to strip the stage and reset it. Not one cue is missed, nor one mistake made; military precision personified. And what of the actual music? It’s easy to snipe about mindless, cheesy Europop, but with the bizarre – or downright awful – entries from Bulgaria, Latvia, Slovenia and Montenegro failing to qualify, the final twenty-six are, in all honestly, a decent bunch, perhaps the strongest lineup in years. Germany’s effort is a decent stab at a dance club anthem, while France’s Amandine Bourgeois injects plenty of femme fatale swagger and coquettishness into her Courtney Love impression. There are some keening, heartfelt ballads, but with a twist; both Iceland’s and the Netherlands’ are quirky and original, never threatening to sink into weepy schmaltz. Best of all is Norway’s ‘I Feed You My Love’, a tune that, if you squint, could well be a Bond theme – a dark, dramatic chorus, soaring finale, and hints of 80s synth-pop and Depeche Mode all laid over a driving beat. It loses out to Denmark, another rousing pop song about love and the pre-show favourite. It’s a fitting winner, and singer Emmelie de Forest is genuinely overwhelmed by the triumph. As is customary, she performs again before being whisked away to face the world’s media and a bright, new future. Filing out into the damp night air, a satisfied calm descends on fans departing for hotels and after-parties, a year of planning and three weeks of celebrating at an end. There’s an consensus that the best song came out on top, and an unspoken, warm glow from having been present to witness one of the best Eurovision’s in recent years. The baton for 2014 is now passed across the Øresund Strait, and the Danes have a tough act to follow. 17 news spectrals Spectrals Ge t T o T h e P o i n t As Louis J o nes p r e pa r es t o r elease h i s sophomore e f f o r t, T o m Walt e r s lea r ns about the affects of new f o u nd c o n f i den c e . T here’s being a slacker out of laziness and then there’s being a slacker purely for the cool-byassociation aesthetic. Louis Jones – or more specifically, the band he masterminds, Spectrals – falls into neither of these categories. It’s abundantly clear that’s he’s poured a lot of effort and a hell of a lot of heart into his new record, ‘Sob Story’. “I’ve tried to be less obscure in terms of the lyrics,” he says on the progression from his debut, ‘Bad Penny’. The first single to drop from ‘Sob Story’, ‘Milky Way’ is a testament to that: it’s laced with down-to-earth, dejected phrases like ‘she couldn’t be you if she tried’ and ‘I know you think a lot because I think a lot when I’m not with you’. While it’s along the same down-in-the-dumps lines we’ve come to expect, Jones explains that it’s the best way to get his point across. “I think when people are a bit more clear and less fussy with the lyrics, it’s a little bit braver,” he says. “I was hiding behind effects on the vocals, and I think maybe hiding things in wordplay and metaphors. Things that I thought were clever and funny. But I think this time I was trying to say exactly what I meant.” When you first start playing ‘Milky Way’, the difference is clear: the drums are sharp and in focus; there’s a more concise atmosphere to the guitar tones and Louis’ croon is both palpable and serene – it’s almost like listening to a kid growing up and fully realising his ambitions. “We used really nice microphones and tried to have it sound like me singing rather than something that’s played around with,” he explains on this newfound clarity. “With the last record I’d never done anything before that I felt I did well, and I got really protective over what I thought was my sound. As I’ve gone on, I’ve realised that the things I was protective about weren’t things I needed to be worrying about.” Feeling a lot prouder of his newer material has, in turn, allowed him to stop craving the certain sonic aesthetic of his previous release, in favour of his new material simply sounding good: “I think if you’re proud of something, you want it to sound as good as it can sound, you know? I didn’t want to be slack with it and I wasn’t holding on to some kind of value like D.I.Y. or lo-fi.” Spectrals’ new album ‘Sob Story’ will be released on 3rd June via Wichita. 18 thisisfakediy.co.uk 19 news big deal Big Deal R et u r n To Make J u n e L ess G loomy Wo r d s : J a k e M a y p h o t o : e m m a s wa n n T here’s a eureka moment on Big Deal’s forthcoming new album. It comes around 90 seconds into ‘June Gloom’, the second full-length from the London-based duo. After a minute and a half of minimalist pretty guitar and the beautiful, affecting boygirl harmonies that we loved so much on their ‘Lights Out’ debut, it kicks in. Drums. An ascending snare. A tom roll. Cymbals. This is it. “We didn’t want the same record again,” says Alice Costelloe in a luxurious looking, boudoir-style room above a coffee shop in Shoreditch. “I feel like we’ve made the album that we wanted to make this time round. With the first one we had so many limitations because of what we could do just with the two of us. We decided when we went in to record ‘Lights Out’ that we had to be able to do everything live, so it was just going to be two guitars. So this time round we were like, ‘No limitations... That was so hard! We want drums. And bass. And we’ll be able to do it live’.” Recorded with go-to producer Rory Attwell on his Lightship studios – an actual boat on the river Thames that “does something funny to your brain, the constant motion, it’s like you’ve taken some drugs,” according to Kacey – ‘June Gloom’ is set for release through Mute on 3rd of, erm, June. It hears Kacey and Alice stretching their wings, heading into new ground, and stepping away from the purely guitarvocals sound heard on their debut. With the debut record being received well both critically and publicly, it’d be understandable if the duo felt some anxiety or outside pressure about having to make an album that lived up to expectation. “It’s weird,” ponders Alice. “People keep asking us about pressure. I really did not ever think about pressure.” Kacey continues: “I don’t think we felt that the first record put a lot of pressure on us, it was more a pressure of needing to do something better... We want to make a better 20 thisisfakediy.co.uk n e b r i e f paramore return to the UK and Ireland this September to make seven live appearances. They’ll be playing at Dublin’s O2 Point (02), Manchester’s MEN Arena (20), Cardiff ’s Motorpoint Arena (21), Birmingham’s LG Arena (23), Nottingham Arena (24), and London’s Wembley Arena (27, 28). in w s record, that kind of thing. If there was a pressure that existed, it was that.” Though Kacey and Alice may have felt confident about producing a record that stands up to their debut, surely that ‘June Gloom’ hears a significant departure from their older sound is slight cause for nerves? “Our first gig we did as a full band we were really excited,” says Kacey of a show at London’s Shacklewell Arms earlier in the year. “We were super stoked and we come off stage like, ‘We did it! That was fun! That was great!’ And then this girl comes up and says: ‘You’ve ruined it. You were perfect as two and now you’re like everyone else.’ The good thing about it was it was a totally valid opinion that she had.” Kacey continues: “I mean, yeah, you’re definitely going to be worried about that. But that kind of line of thinking is always going to make it harder. You can’t think about doing what people want you to do because you didn’t think about that when you went in to make your first record, you know?” Alice agrees: “I think it’s having a bit of respect for your fans. We figured: people liked our first record, hopefully they just like good music. And we definitely think we made a good album.” Big Deal’s new album ‘June Gloom’ will be release on 3rd June via Mute. will open their very own record shop in their hometown of Sunderland. Pop Recs Ltd – situated on Fawcett Street - is set to open its doors to the public on 1st June. beck will play a one-off show at London’s Barbican with a string of well-known names, performing his recent ‘Song Reader’ album in full. He’ll be taking to the stage on 4th July with the likes of Jarvis Cocker, Franz Ferdinand and Beth Orton. deaf havana have confirmed plans to unveil their third album ‘Old Souls’ on 16th September. Have a listen to the first single, ‘Boston Square’, on thisisfakediy.co.uk now. everything everything have added two dates to their October UK tour. They’ll now be making two stops at both Manchester’s Ritz (11,12) and London’s Forum (24, 25). 21 frankie & The Heartstrings festivals 2013 26th - 30th June here’s no event quite like Glastonbury. Whether visiting to be steeped in musical history, or buried in beautiful isolation; to taste the mysticism that hangs in the air, or simply just to watch some great bands, it’s guaranteed to be one of the highlights of festival season. This year, the institution is back after a one-off break and it seems more than ready for its 135,000-strong audience. In 2013, the legendary Pyramid stage is set to mark the debut Glasto performance of The Rolling Stones, see Mumford & Sons take on one of their first major headlining slots, whilst welcoming back its 2007 bill-topper Arctic Monkeys for a second time. It’ll also boast performances across the weekend from the likes of Vampire Weekend, Dizzee Rascal, Nick Cave & The Bad Seeds, Primal Scream, First Aid Kit and Haim. Elsewhere on the Tor, you’ll sample the delights of Alt-J, Foals, The xx, Phoenix, Bastille, Hurts and too many more to get your head around. Rest assured, you’ll be in for one hell of a weekend... so long as there’s no mud. We wouldn’t want a repeat of last time now, would we? T 22 thisisfakediy.co.uk N 7 th - 9th June owadays, people don’t just end up visiting Loch Ness to catch a glimpse of its rumoured, infamous lake inhabitant. In fact, 35,000 people have started turning up at Clune Farm, Dores just to watch some bands. Yes, that’s right, head up to the beautiful Scottish Highlands and you’ll be greeted with another edition of RockNess festival. This year’s weekender is set be topped by Basement Jaxx, Example and Plan B, with other performances from The Vaccines, The Maccabees, Fatboy Slim, Ellie Goulding and The Futureheads. So, if you’re after a weekend of music set against a rather beautiful backdrop, this is the one for you. f you’re up for heading overseas to party this summer, Sónar could be a good bet. This year, the Barcelona event will be celebrating its 20th anniversary, and it quite clearly plans to do so in style. The festival, which bills itself as specialising in ‘advanced music and new media’, looks set to make good on that promise, with headlining performances from Kraftwerk and their infamous 3D show, Pet Shop Boys and Skrillex. Other acts on the electronicbased line-up include our Class Of 2013 alumni AlunaGeorge, along with Major Lazer, Gold Panda, Two Door Cinema Club, Bat For Lashes and Chromatics. I 13th - 15th June W 14th - 16th June This year’s headliners stand tall as titans of heavy music – come on, try arguing that Slipknot, Iron Maiden and Rammstein aren’t the perfect acts to close proceedings – and attendees will also be privy to the only scheduled UK appearance from Queens Of The Stone Age, following the release of their new record ‘...Like Clockwork’. Elsewhere, DIY favourites FIDLAR and The Hives can be spotted rubbing shoulders with Mastodon, Jimmy Eat World, The Gaslight Anthem and Thirty Seconds To Mars. 23 hile Download festival is usually undoubtedly the home of all things metal, 2013’s edition of the Donington event is set to include an array of appearances that no one will want to miss out on. neu Arthur Beatrice NEu Crossing The T’s: A n d T h e V i c e O f B e i n g A r t h u r B e a t r i c e P e r f e c t i o n i s t s photo: emma swann 24 thisisfakediy.co.uk T ake yourself back to a crammed Lexington in London, in April 2012. It’s an Open Assembly night, one of many Arthur Beatrice have curated, in turn acting as headliners. They’re playing off the back of their ‘Midland’ single from the same year, so there’s a big sense of occasion. But instead of throwing themselves straight into the set, all members look panicked. They’re apologising, seemingly dithering with wires and equipment. Turns out the stage piano - the central focus of their show - has gone kaputt. The band’s response is spontaneously put together, piano lines traded for guitar parts. And it works. “A lot of people were saying that was the best they’ve seen us,” says singer Orlando from the band’s East London studio one year on. “I actually thought ‘ah, maybe we should’ve been a guitar band!” But Arthur Beatrice were never quite cut out to be a conventional guitar-wielding type. They met at school - “normal school,” that is, not music school - and practice sessions between Orlando, Ella Girardot and Elliot Barnes started six years ago. Hamish - Elliot’s brother - soon joined. “And then we found a uniform sound,” as the story goes. Even six years back everything was meticulously crafted, with a self-professed perfectionism that has led to their soon-tobe-released debut album being recorded, re-mastered, over and over again. “It’s a big vice for us,” explains Elliot. “But I think it’s worked, in that we don’t let anything go out unless it’s 100% right. That’ll stand us in good stead in the future - it makes things less throwaway.” The band seem rooted to their own space. It’s not isolationism, necessarily that leaves them peerless. Our first online write-up compared the group to Warpaint and Wild Beasts. But Elliot stresses that they’ve “never found natural partners,” as a force. “I think a lot of other bands find scenes with other bands who play similarly... We don’t really have that community.” These Open Assembly nights weren’t by any means revolutionary, but they helped cultivate a sense of belonging. Each gig would be headlined by Arthur Beatrice themselves, but down the bill there’d be a tight fusion of electronic acts, standalone producers and a fair few DJ sets. “We always seem to do a lot more electronic stuff,” says Orlando. “It’s one of the ways that we can show our interest in that kind of music without making it ourselves.” Some might lump the tag “electronic” into previous singles ‘Midland’ and ‘Charity’; it’s one of many terms that have chased the four-piece since they first emerged. “Anonymous”, “mysterious”, “secretive”. But a scarce amount of information was again a by-product of their refusal to let anything out into the open before it was 100% to their taste. Their website URL is titled, jokingly, as Ella confirms - onlinepresence.info. It’s a tongue-and-cheek dig. “ M ay b e we s h o ul d ’ ve b e e n a gui tar ban d ” They’re against confessional Twitter posts, anti-detailed biographies about each member’s past. “I think we all hate it, to be honest,” Orlando states. “When you look at 80s and 90s bands and way before that when people obsessed over printed material, there was a lot more to grip onto.” Elliot follows: “When you have access to everything it all becomes throwaway.” But when this debut full-length eventually arrives everything will be out in the open: the singles they just about avoided releasing in 2012 as a means of “riding that hype”; the focus of their sombre, piano-led songwriting, and the very reason why perfectionism pays off in the end. ( Jamie Milton) 25 neu cover recommended fall out boy NEu Recommended n en c c e e 4 i c HAERTS Hailing from all over the globe – Germany, England and the US – now New York-based five-piece HAERTS make soaring, sentimental synth pop that invigorates the feeling of being at a festival; taking in the glowing sunset of the final day. Any song that can ignite a feeling inside of you is on to a winner, and ‘Wings’ does this brilliantly. Another band that springs to mind when you listen to HAERTS is Glasgow’s very own synth-poppers CHVRCHES, not because of any musical similarities – there aren’t many despite both rocking female leads and sharing an inability to spell – but because many might imagine their track ‘Recover’ to be the kind of 3am jam that keeps the last flicker of the party alive. If that’s so, then ‘Wings’ is the flipside - the feeling you get at 6am as your body fights sleep and your eyes wince at the break of day. (Tom Walters) 1 P r o Inn Talvi Faustmann and Josh Mcintyre are a couple living in and out of different cities, recording music as and when it suits them. And right now they’re on a hot streak. Their debut ‘Lapse’ EP is a work that conveys the energy burst you get from forming a new musical project. It’s excitable throughout, like a fresh-faced youngster seeing the world for the first time. Much of that comes from Mcintyre taking a side-route from his still prolific Little Girls project. While Josh’s songs under that guise were shrouded in every hazy glow available, these Prince Innocence tracks are direct, provocative. In this Chromatics-style glow they hone in at something special. ( Jamie Milton) 2 S u p e r f ood It wasn’t long ago that Superfood had no Facebook page, demos or YouTube videos and after only a fleeting glimpse at DIY’s ‘Hello 2013’ showcase, the latest Birmingham bunch were definitely not letting their mask slip. The only detectable fragment of their existence was their almost mythical live shows where the band flourished. While they might not have been that easy to uncover, Superfood were definitely creating waves. Word was getting out about their shows with comparisons to Pavement and early Blur. Fast forward and the four-piece finally unveiled their debut track last month, bursting with character and youthful energy. Excitable vocals and surging guitars display a band already at the top of their game. (George Smale) 5 B l a u e B l u m e How do you begin to start singing like Jonas Smith? When did he dare to raise his voice to such heady notes and run with it? It’s like asking ‘who was the first person insane enough to attempt to milk a cow and then drink the stuff ?’ Blaue Blume combine acts of lunacy. Strange shapes and untimely collisions that somehow make sense when segued together. ‘On New Years Eve’ is daring, a leap of faith. Initially it’s all about Smith’s falsetto, half smoky, half purred. But then the other members step in, announcing themselves in a grand crescendo that sends an already foolish step forwards into territory the band can’t return from. ( Jamie Milton) 3 P a ww s 6 V å r A few months back, demo tracks - which have since been removed - of Lucy Taylor’s Pawws project quickly spread. Word on the street was she had something special up her sleeve. Pah! We’ll believe it when we see it, said many a cynic. But then out came ‘Slow Love’. It was love, that’s for sure. But it certainly wasn’t slow. This was a whirlwind relationship, head-over-heels adoration. Taylor’s first track proper coyly declares “we’ve still got time / there’s no need to rush yet”, but as soon as you first play the song, you’re in the opposite mindframe, convinced there’s no time to lose in telling all of your dearest just how ruddy good she is. It’s glitterball pop with no endgame, a song that never tires. The rumours were true: this is something special. ( Jamie Milton) 26 thisisfakediy.co.uk Vår are incredibly bleak. These Danish youths have a fiery outlet for any difficulties they might encounter. They don’t vent their emotions in the same abrasive vein as the confrontational punk rock that Holograms and Iceage (Elias Rønnenfelt’s other band) spit out. Instead, they locked themselves away last summer, experimenting with electronics to achieve a hypnotic sound that will fill their debut album, ‘No One Dances Quite Like My Brothers’. The blasts of industrial noise are remarkable; eerie and unwelcoming, yet incredibly compelling. The bubbling synth in ‘The World Fell’ is multidimensional as it constantly simmers into a different shade of sound, while the vocals are like possessed chants from a distant source. Bleak isn’t always exciting, but in Vår’s case it’s utterly enthralling. (Sam Cornforth) 1 2 5 3 3 6 5 4 27 neu ms mr NEu N ew York has always been viewed as an enormous, apple shaped, melting-pot for exciting new music, and at present, the big city seems at its most prosperous in some time. It’s set the scene for a handful of Neu favourites’ careers, including the glistening electro-pop duo MS MR, speaking to us from a rain cursed day in Brussels. “Essentially, we went to school with one another, but didn’t really know each other, or start making music together until we had an email exchange where we were both looking for musical opportunities and thought that the other person might be a good match,” explains singer Lizzy Plapinger. “It was December 2010 when we first got together and it went really well,” she says. “We really liked what we’d made, but more importantly, I think we recognised that we could write music with one another.” Three years on and the pair have a remarkably anticipated debut album to their name. The rightful hip hop King of New York, Jay-Z claims to be a fan of the band. “We initially recorded the album - almost everything - even before we had a record deal,” says the ‘MR’ to the duo, Max Hershenow. “We [recorded] in my apartment on my laptop and keyboard and microphone. It was super D.I.Y., and I think we naively thought that those tracks we recorded in our apartment would be enough, then we’d be able to just find a mixer and finally release it.” The album contains all four songs from their 2012 EP, ‘Candy Bar Creep Show’, as well as singles ‘Fantasy’ and ‘Hurricane’, both of which are accompanied by astoundingly outlandish music videos, which combined have racked up over two million hits on YouTube. “I think the music videos are an extension of all the visual ideas of what we’ve been developing,” explains Hershenow. “And when we look back at them we see a clear pattern between the way we think visually and the way we think musically. I think the idea, in general, is that we want to present you with a lot of material, both musical and visual, without making the connections or the narratives a split.” All this ambition coming to fruition is the stuff of pop fairytales. Two music enthusiasts finally seeing their names in star-studded letters. “I don’t think it ever felt more real, until recently when we got the physical copy of our album in our hands. That was the first thing that really settled it for me,” Lizzy tells us. ‘Secondhand Rapture’ appears certain to secure the band’s providence even further. ( Jon Hatchman) Wild Fantasy: MS MR 28 thisisfakediy.co.uk NEu By Hook Or By Crook: T h e S t o r y O f Clean Band i t ’ s R u naway S u c c ess Photo: Mike Massaro T he UK charts are experiencing more than just a ‘good patch’. When you’ve had Rudimental, Daft Punk and Duke Dumont all sharing the top spot spoils so far this spring, you’ve little reason to ask for any more. Ok, maybe ‘Get Lucky’ could do with being the biggestseller for the rest of eternity, but that outcome doesn’t seem entirely improbable just now. Besides, even a trawl down the Top 40 brings out the odd smile, especially when you see Clean Bandit’s ‘Mozart’s House’ finally making a mark. It’s been a destined chart-botherer since it was penned in 2010, and when Jack Patterson and oft-collaborator Sseg whipped the camera out in Moscow they decided to start filming a now-famed music video for the track. Jack was working in the city at the time and they suddenly had the urge to “get some sketchy gig” in a divebar. “But there was actually this horrendous heatwave at the time,” Jack says. “All the promoters had disappeared out of the city because of this smog.” So instead, Sseg and Jack made a video. And that video’s since racked up a good couple of million plays, somehow epitomising everything that’s exciting about Clean Bandit. It’s refreshing, it’s fun, but it’s not entirely clean-cut. It’s cheeky, fierce, not afraid to take risks. It’s everything the charts require. If the ‘Mozart’s House’ video was a smog-induced whim, the more recent creations have been a little more carefullyplanned. “You shouldn’t make a song and make a video for it,” he says. “We’d like to see it as a single thing that you create together. We’ll have ideas where existing video will influence the music”, like in ‘UK Shanty’, he cites, where “this abstract 3D world became part of the visual concept.” Jack jumps at the idea of seeing these videos on MTV. “I used to be totally obsessed with MTV 2 and VH1 Classics and Kerrang! and Q. When I was a bit of a goth back in the day... I used to think it was the most incredible thing.” But while all this rapid, due-time ascendency is surrounding the band, the brains behind the project claim to not know a damned thing. “I’m pretty clueless about what it all means when it comes to charts and the music industry”, he says, pausing to reflect on what he’s just said. He doesn’t cite YouTube or Facebook once. Maybe he isn’t fibbing. But if three years working day-in day-out on the same project hasn’t lent Jack industry knowhow, he and the rest of his band are fast-becoming surrounded by the rewards they warrant. There’s still the small matter of a debut album - “it sounds so simple but it’s so hard to actually make one” - a half a dozen festival slots and goodness knows how many more videos. But Clean Bandit are on their way to being an everyday staple; a representation of the excitement and talent that’s moulding itself a space in the charts and beyond. ( Jamie Milton) 29 neu mixtape N o t c o n t en t w i t h g i v i n g y o u a f r ee m a g a z i ne , we ’ v e p u t t o g e t h e r a f r ee m i x t a p e f u ll o f o u r fav o u r i t e new b ands ; d o wnl o ad f r o m t h i s i s f a k ed i y. c o . u k / m i x t a p e neumixtape London trio Benin City flip convention like it’s a grubby habit. On ‘My Love’ wordsmith Josh Idehen, tongue-firmlyin-cheek, speaks of every muscle flexing for his lover, and to distract you from the snarling, lustful lyrics you’ve a jazz-like bed of instrumentation that breaks into brilliant crescendo. Oslo’s Cashmere Cat is probably responsible for one of 2013’s standout moments with this monumental remix of Miguel’s ode to illicit substances. If you haven’t yet heard this blow up in a club you’re probably not going out enough. Derry’s Ryan Vail is a project between its titled maker and Katie Cosgrove. If ever you thought The xx had sewn up the soft-backdrop-whispered-vocals complex, these guys are here to shake things up a bit. Benin City My Love Ironically, it’s not in this London group’s best interests to hide away from the spotlight. Everything about ‘Deadly Sin’, Shy Nature’s debut track, screams festival anthem. You practically find yourself waving a proverbial flag. A fuzzy cut from their early demos, ‘Digsaw’ gives us just enough of an insight into Brighton-residing fuzz-based force The Wytches. Their new single finds a fitting source of refuge via Hate Hate Hate Records. Cheshire’s Weirds recorded their debut track ‘Crocodile’ with MJ from Hookworms, and these newcomers are up there with the Leeds-based troubadours in wielding progression out of those grizzly guitars of theirs. ‘Yolk’ is an enrapturing introduction. Shy Nature Deadly Sin Miguel Do You (Cashmere Cat Remix) The Wytches Digsaw Ryan Vail Fade Weirds Yolk The repeated refrain that opens Brighton group Us Baby It should be within everyone’s interests to give each citizen Bear Bones’ ‘You’ is deceptively simple. What follows is across the country a free 7 day holiday on a tropical island. quite remarkable, a ferocious entangling of jumped-up Send them along with a couple of instruments and a 4-track lyrics, gentle chimes and thumping percussion. Busied and tape. If half of the holiday-goers came up with something as excitable, it’s hard to know which aspect of the song to focus good as Wishyunu’s ‘Sprayy’, the world would be a happier on, they’re all so enticing. place. The mixtape sees in the scuzz right about now, California student Yoodoo Park bringing every source of life and sunkissed energy to the studio for a track on his superb ‘Empire’ debut, out via Carpark Records. Us Baby Bear Bones You Wishyunu Sprayy GRMLN Teenage Rhythm Bristol’s Oliver Wilde doesn’t half know how to send his listener into a sleepy, comforting lull. He’s got two fulllengths up his sleeve, apparently, but it’ll be a tough act topping the six-minute breeze of ‘Curve (Good Grief )’. Think an even-more-mellowed-out Gruff Rhys. Oliver Wilde Curve (Good Grief ) 30 thisisfakediy.co.uk sounds from my cit y: NEU Manchester In Sounds From My City, Neu asks some of music’s creative talents to tell us all about the most exciting bands on their doorstep. Back in January Neu teamed up with The Old Blue Last, London, presenting four shows chock-full of future talent. ‘Hello 2013’ paid welcoming dues to the likes of Wolf Alice, Syron and Superfood. But going giddy for new music shouldn’t be restricted to the opening weeks of the year. So we’ve combined again to bring you the aptly titled four-show series: ‘How June Is Now’. It commences on Tuesday 4th June, with Seattle’s Seapony coming over to headline, backed up by Southend’s Skinny Dream and Issy Wood. The following Tuesday (11th June), gadget-addled Neu favourites take to the stage. Kirk Spencer headlines, with two of Brighton’s most exciting bands in yonks - IYES and Gaps - joining proceedings. Nottingham production duo Crvvcks complete the bill. Tuesday 18th sees Casual Sex topping the night. The new Moshi Moshi signings join forces with Brighton’s Sisters and fledging psych outfit Weirds. Our summer escape concludes with arguably the two brightest UK-based prospects around at the moment, South London’s soulful newcomer Moko combining with the unrelentingly inventive LAW. Just as with our previous showcases alongside The Old Blue Last, each night offers a different, dynamic glimpse into the future. Put all of those dates in your diaries. 31 PINS are a four-piece from Manchester signed to Bella Union. Last year they released their ‘LUVU4LYF’ EP. Right now they’re working towards a debut full-length. is a banner-man like entity, drawing together like-minded musicians to create droning lullabies best described by their manifesto: “All is being, all is breathing, all is as all is. Find only truth in selfhood, for the self is purest, uncompromising in it’s harmony with original thought.” Kult Country is another sonic experiment from (amongst many other bands) Temple Songs frontman Jolan Lewis. Writing late into the night he pens catchy pop infused garage songs that pay homage to the likes of The Godz and The Red Krayola. The Pink Teens cover the national 32 thisisfakediy.co.uk Funny S o n gs Funny Songs About Death With an exceptional sixth album and two headline shows at London’s Alexandra Palace, The National are a band who can do no wrong. Wor d s : Dan ny Wr ig h t Photos: Mike Massaro R elaxing in a members’ club in central London on a bright spring day, the sun is falling through the bay window. In his soft Cincinnati twang, The National’s bassist Scott Devendorf is describing the challenge of translating the subtleties of the band’s songs into an arena show. “We were joking, ‘Imagine playing in this big place and we’re playing this fragile ballad’.” A quirk of fate means there’s an antique piano sitting in the corner of the room and, as he’s speaking, bandmate Aaron Dessner wanders over to it and starts almost absentmindedly playing ‘Slipped’, the centrepiece of their startlingly brilliant new album, ‘Trouble Will Find Me’. Hearing the notes float through the room is a reminder that, even in the biggest arena, The National’s music sounds intimate. There’s a warmth and comfort in frontman Matt Berninger’s baritone voice that says however messed up things are, everything will be ok. As Aaron says, “I don’t write the lyrics but I see myself in the things Matt says, and I think the audience does too.” Speaking to Matt an hour later, he suggests it’s this universality that gives the band’s name - something that was chosen specifically because it didn’t mean anything a unique significance. “If it had a meaning at the start the meaning we thought it had was ‘the citizen’, or something like that. I love the band name The Smiths because it was such a generic name.” “I still think we should have come up with something more memorable and maybe that’s why it took us fifteen years to find a fanbase,” he muses, half joking. “If we’d been called Vampire Weekend we would have been popular a lot faster.” Bryce Dessner, sitting next to him, laughs. “We’d still be 26, too.” 33 cover the national 34 thisisfakediy.co.uk t may have taken them longer than some to get here, but The National have finally achieved the acclaim they deserve. On 2005’s breakthrough album ‘Alligator’, Matt sung sardonically about music ‘that only lasts the season / And only heard by bedroom kids who buy for that reason,’ but 2010’s ‘High Violet’ saw the band establish themselves as truly important. With ‘Trouble Will Find Me’ they are set to raise the bar even higher. It’s an album that ebbs and flows beautifully. Different from ‘High Violet’, richer and more intricate, it reveals a band comfortable in the knowledge they have earned their right to sit at music’s top table. “I think there was a self-confidence that dawned on us after ‘High Violet’. We started to trust the chemistry in the band,” Aaron, who with his twin brother Bryce writes the band’s music, explains. I time we knew they were coming and we weathered them.” ‘Insecurities’ and ‘neuroses’ are words which keep cropping up, but Aaron says for this album that changed. “I can honestly say this is the first record where we had no rules, no insecurities or anxieties driving it.” It was the birth of Aaron’s daughter which ignited the spate of songwriting that would form this album, and it was something which forced Bryce to raise his game, too. “Aaron had a child and was spending sleepless nights awake so he generated tons of material and I thought I better write some of mine. I think a year and a half ago there were thirty or forty sketches. Then we sent them to Matt and he started to generate all these melodies.” These ‘sketches’ were eventually whittled down to thirteen tracks, and all the band were unanimous in their agreement that these were the strongest songs for the album. Not that they intended to create a new album after touring ‘High Lyrically this record seemed to Violet’. It seems it’s precisely this come together a lot more easily “This is the lack of a plan that has given them than on previous occasions, too. the freedom to make a record that “From ‘High Violet’ all I cared f i rst r e c o r d is liberated from the shackles of about was melody,” Matt explains, expectation and over-thinking “I would just sing along for the where we that has weighed down on them whole track and then I’d mute it on previously. “We decided to and do another one completely had no not make a record for possibly different, and there’d be twenty four years. Aaron and Bryan had of these. Me just free-associating. babies and I had a two-year-old. Then later I would piece the rules.” We had some perspective which melodies I liked together and made it feel like the band wasn’t words would fall into them. I was the most important thing in our listening to a ton of Roy Orbison lives,” Matt says. “Somehow the pressure of being in stuff and I got really excited about how he would go the band and what sort of album we should follow from one octave and then go up four octaves and the up ‘High Violet’ with; none of those thoughts were song would change completely. Working this way led in the process at all. Songs just started to bloom in me to write better lyrics because they were following their own organic way.” melody and they loosened up some of the neuroses.” For Bryce this meant the band could push their ideas as far as they liked. “In the past we’ve had to make compromises by being late or stressed but in this case we went as far as we could with everything so there are no feelings of regret.” It also meant they were able to deal with the actual process of making an album more easily. “There’s a certain neuroses in our process. It’s always intense, it’s always manic,” he explains. “There’s always certain arguments but this Yet the lyrical themes remain similar. Matt’s preoccupation with re-imagining romance and existential insecurity in vivid ways are just as resonant as always. “Romance and insecurity and social anxiety are in all of our records. This one has plenty of those, and a new thing is a recognition of mortality - but it’s either funny stories about dying or questions of what it means to exist.” 35 cover the national Having a child has also affected his outlook. Discussing album track ‘Heavenfaced’, he explains that he’s “not a believer in heaven or hell, but that we continue to live on through the ripple effect of people you’ve connected with. And having a kid is the most direct ripple effect. There are a lot of songs about death on here but in a very cathartic, almost euphoric, soothing exploration of that. I don’t think about this record as being a dark or sad record at all.” It does feel like a looser and more inventive album, both lighter and heavier at the same time, more complex but also poppier. The focus may still be on death and anxiety but, as Matt says, this is fun. Just take the lyrics to ‘Humiliation’: ‘As the freefall advances, I’m the moron who dances.’ There are moments of stunning intimacy, while the heavier ‘Sea Of Love’, as Bryce notes, “captures an energy in a way that I haven’t felt since ‘Mr November’.” For Aaron, ‘Slipped’ is the one he’s most proud of. “I’ve always wanted to write a classic song that had a timeless pull to it and I’ve learned from studying other writers’ songs. In this case it was Dylan’s ‘Not Dark Yet’. ‘Slipped’ is more of a pop song but there’s something about the swampy lilt to it that is similar, though it also has a lot of half bars and quick turnarounds. A lot of the songs have these sneaky complexities on there. Matt doesn’t think musically, he just kind of responds but I think that was what was working with this album - if the ideas had an emotional tug he didn’t worry about whether they were complex, he just latched on to them.” The record was also augmented by an amazing array of regular collaborators, including Sharon Van Etten and Sufjan Stevens, who are The National’s extended family. “These people add a quality to the band,” Scott says, “Sometimes we get stuck in our ways and someone like Sufjan came in and did a bunch of awesome stuff and we used a few things from it. We’re lucky that we know these guys and they’re friends.” For Aaron these collaborations are one of the most exciting and fun parts of making a record. “I love the idea of the 60s / 70s with the Grateful Dead and Jerry Garcia playing on all these people’s records, 36 thisisfakediy.co.uk and I feel like there’s a version of that happening today.” Aaron shares a story of when another friend of the band, Win Butler from Arcade Fire, came into the studio to listen to the record. “It It seems that 2004’s was funny cos he was talking ‘Cherry Tree’ EP was the “The band wasn’t about ‘I Should Live In pivotal recording in the Salt’. If a festival audience is band realising what they t h e m o st i m p o rt a n t clapping along to the quarter could achieve. “We were all note, they will get it wrong. hanging out in Matt’s loft thing in our lives.” So he did it and said [adopts drinking beer and we weren’t goofy voice] ‘This is awesome’ serious about it - we all had and went off the note.” jobs and it was just for fun,” Yet the position they find themselves Aaron says. “With ‘Cherry Tree’ I Hanging out with Arcade Fire and in is in stark contrast to when they remember there being a tangible playing in huge arenas must feel released their first two records - the sense of, the foundations of these different from their early days when eponymous debut and ‘Sad Songs things has to be figured out. And they were playing to empty rooms For Dirty Lovers’. These albums are that started the process that has and self-releasing their albums. sometimes unfairly dismissed but continued through each record, Do they still feel like the same they’re part of the intricate makethat each song was this journey. But people? The band say resolutely yes. “Our music has evolved considerably but as people we haven’t changed dramatically,” explains Aaron. “No one has any rock star delusions.” up of the band. As Aaron says, “We made those records ourselves, started a record label, put them out and booked shows and fell on our face for a couple of years. It taught us a lot.” 37 cover the national without those first two records we would never have got to ‘Alligator’.” Now they’re headlining festivals and playing huge shows, including two dates at Alexandra Palace in November. Yet despite their burgeoning confidence there remains a lingering feeling that they always need to prove themselves, especially live. “We’ve toured so much and we’ve always had to prove ourselves a tt e m p ts at every stage so it’s probably the same There is one change that has been again,” Aaron says. “It’s like jumping enforced by the growing size of the to take into cold water - we might fall on our venues though - Matt’s infamous face or we might succeed. And I think charge through the crowd during ‘Mr m y p a n ts watching Matt lose his mind a little and November’. “There’s less of that now,” o ff . ” watching us struggle, and hopefully get he admits. “I was doing that in some to a great point in the show, is part of pretty big places and the crowds would the reason why people like to see the crush around me. And especially in the band.” Matt agrees. “We were never fish in water when UK, there have been some attempts to take my pants off. onstage, it’s definitely flopping around, but we’ve learnt It’s hard to sing a song when you’re desperately trying how to flop around gracefully up there.” to keep from having your belt undone by some drunk dudes.” Yet whatever anxieties the band feel playing these bigger The National’s new album ‘Trouble Will Find Me’ is out now venues, to Bryce what’s at the core of the band is the via 4AD. bond between them and the connection that their fifteen year history has created. “We spent so many years playing to so few people that we developed a survival instinct and that’s where the core of the band was formed. We’re very lucky - some bands find it difficult translating to that setting “There but we can enjoy it. It’s not like we’re have a different band when we’re playing Glastonbury or playing our own small been some club show.” 38 thisisfakediy.co.uk noveMbeR 13 & 14 2013 lonDon alexanDRa PalaCe SO LD OU T noveMbeR 11 & 12 2013 ManCHeSteR o2 aPollo SO LD OU T SO LD OU T PluS gueStS buy online at tiCketMaSteR.Co.uk SeetiCketS.CoM new albuM “tRouble will finD Me” out now aMeRiCanMaRy .CoM 4aD.CoM a live nation , SJM ConCeRtS anD PaRallel lineS PReSentation 39 interview Waxahatchee W i t h h e r s e c o n d a l b u m , Wa x a h at c h e e i s c r e at i n g q u i t e a s t o r m . W o r d s : J a k e M ay. Bl S k i u e es A h ead 40 thisisfakediy.co.uk 41 interview Waxahatchee T o most of the UK the music of recent Wichitasigning Waxahatchee will be entirely brand new – the forthcoming ‘Cerulean Salt’ record the introduction to her world of angsty, folk-ish songs about love, loss, and nostalgia. For Katie Crutchfield, the 24-year-old Alabaman behind the project, music is something she’s been making for ten years already – with ‘Cerulean Salt’ merely the latest in a long series of releases with a number of different bands and under various guises, and her second as Waxahatchee. As impressive as her previous output is, the new Waxahatchee album certainly feels like a coming of age. “In the past I was a little impulsive and hasty,” Katie explains over the phone from her bedroom in Philadelphia. ”Sort of like, ‘Oh, I have this idea, let's make this record right now!’ The first [Waxahatchee] record [‘American Weekend’] was just kind of like a lightning strike. [‘Cerulean Salt’] was more drawn out and more contrived. Like, this is how we want it to sound and we're going to take our time.” ‘American Weekend’, released in 2012 through Don Giovanni Records in the US, was entirely written and self-recorded in a week. It’s an incredible album made up of punk-influenced acoustic folk; Katie sharing tales of heartbreak and love-loss in a delicate, intimate and beautiful setting. Initially ‘Cerulean Salt’ was recorded in a similar acoustic and lo-fi vein before Katie decided to scrap the recordings and start over. “The songs just didn't transfer,” she reasons. So, with the help of her boyfriend Keith, Katie re-recorded the entire album with her friend and housemate Kyle Gilbride (she lives in a house of eight people, all “musicians and songwriters”). It’s an instrumentally-fuller record with a much cleaner sound. “I feel really proud of it,” she says. “I hope that that speaks to the future of my song-writing. I'm going to take my time and make a quality record.” It’s a technique that pays off. The increasingly patient recording method hears a more considered, more consistent, more accomplished sound, yet loses none of the intimacy or beauty which made her debut so special. No surprise, then, that her music has spread like wildfire over the US and Europe, pricking up the ears of Wichita in the process. And even more impressively: it’s largely down to word of mouth. “ G ood m e m o r i e s . “My US 'PR guy' is my friend at this point,” Katie explains. “I would never sign some crazy record deal or go with some crazy PR company or anything like that. I never wanted to gain popularity for anything other than people liking my music that I made, that I wrote, that I recorded, and that 42 thisisfakediy.co.uk “ I ’ m m y go i n g t o ta k e a t i m e a n d m a k e q u a l i t y r e c o r d . ” enough privacy in big cities,” she says of her time spent living in New York. “You can always feel a person in the next room or in the next apartment or outside your window. There's always somebody. And I kind of need a sharp focus in order to write for Waxahatchee a lot of the time, so I have to be completely by myself. More often than not I am not in the mind-set to write like that. I just have to listen to my brain. I haven't even written any new songs for Waxahatchee [since ‘Cerulean Salt’] but I'm confident that moment will come, when I'm ready,” she says. Critical acclaim, worldwide attention, and a forthcoming release on one of the UK’s most respected independent labels understandably might leave Katie at a loss for some of the sadness that has inspired a lot of her past recordings. And these aren’t the only reasons Katie has to be pleased with how Waxahatchee is going right now. In June she’s set to tour Europe with Tegan And Sara, stopping off in London for a sold out headline date at the Shacklewell Arms. “It’s very strange, especially considering I have never gone further than Canada,” Katie muses. “It's really exciting. I've never been [to the UK] before so it's pretty crazy. In America, whether I like it or not, I sort of know what's going on. Touring here all the time is fun but it can get kinda old and monotonous. But over there I don't know at all. When I get there I'm not going to know how the shows are gonna go or anything like that. It's basically taking something that I loved to do but that has sort of started to get old and making it new again. So I'm really excited.” Touring with Tegan And Sara undoubtedly won't be the only time Katie gets to experience performing in front of thousands of adoring fans in cities she’s never visited. With a voice and a talent for songwriting like hers, she has the potential to become a genuine great – be it with Waxahatchee or whatever ridiculously good venture she comes up with next. Waxahatchee's new album 'Cerulean Salt' will be released on 1st July via Wichita. 43 came directly from me. I'm not one of those people that would compromise or do anything that would make me feel stupid or silly in order to get something somewhere.” In terms of creative inspiration, Katie tends to draw from personal experiences. Her lyrics are autobiographical, affecting, and powerful. “I feel like when you write about something that's completely across the board – like about getting your heart broken – you say that in a couple of different ways and then that’s it,” she says. “It's not real enough to me. I feel like if I can write something that's real for me, hopefully other people can relate.” Katie finds she needs quite particular circumstances to be able to get in this lyrically creative place. “There isn’t I lov e t h i s pl ac e . ” interview gold panda 44 thisisfakediy.co.uk t quickly becomes apparent, in conversation with Gold Panda, that we taught English in Japan at the same time. In fact, we were living in nearly exactly the same place, a ten minute train ride from the mania of central Tokyo. “I was always interested in this idea of Tokyo when I was a kid and I never got to see it because it was over before I got there; the bubble had burst,” he explains. “I’d heard crazy stories about people having gold flakes on their ramen noodles and eating sushi off naked women. Crazy shit like that really interested me – a weird hedonism where people were spending money so they didn’t have pay a huge tax bill.” This fascination has come through in his music, perhaps most clearly on ‘Junk City II’, the opening track on his new album ‘Half Of Where You Live’, which he explains reflects recent trips to Japan and was conceived as a hypothetical soundtrack to 90s anime. Yet Japan isn’t the only source of geographical inspiration for the nomadic Gold Panda, who currently calls Berlin home but is often found at all corners of the globe playing music. ‘Half Of Where You Live’ is inspired by his travels doing this exact thing. He describes the record as a “city album” and it’s easy to see why. There’s a feeling of driving through huge metropolises, their overwhelming noise and clutter, their beauty, their harshness. Though it flows with organic vibrancy that was so to the fore on his debut, here there are harsher edges and a keen sense of both space and congestion. On the first track released, ‘Brazil’, he tried to capture the journey from the airport to the hotel. “There are other songs that try to do that, try to capture the kind of overpopulated, smoggy atmosphere of big cities, like driving through Shanghai.” If there is a theme then, it is that of travelling, of creating a sense of place. “I guess from touring and travelling I didn’t have anything else to name music about so I just ended up naming tracks after places I’d been or things I was interested in, whether those places were imaginary or real. So there are a few themes in there because you’re away from home, in other places. You just get a snapshot of a place whenever you play a show. You fly in and maybe you have time to see something – for example in Pisa I saw the Leaning Tower of Pisa for about five minutes and that was it.” I A T ale O f M an y C it i es F r o m T o k y o t o B e r l i n : D a n n y W r i g h t a n d G o l d P a n d a t a k e a t r i p d o w n m e m o r y l a n e . 45 interview gold panda Yet despite taking inspiration from the places he visits, he finds it hard to write on the road. “I’d rather do it at home with a big selection of old records and a sampler and a cup of tea and be in the zone, and I can’t do that on the road. So I just remember stuff really, memories, and then try and make songs that conjure certain emotions.” ‘Enoshima’ is one such track on this album, inspired by a peaceful idyll close to Tokyo. “I went there just before I wrote the track and had a really good time with my friends and my cousin. There are a lot of songs on here, like ‘My Father In Hong Kong’, ‘Junk City II’ and ‘Enoshima’, that rely quite heavily on Asian scales and sounds. I actually wanted to avoid that because I didn’t want that to be my gimmick – but then I also like music that’s stereotypically a Westerner’s view of Asian music. ‘Enoshima’ just sounded like that place, that little retreat from Tokyo.” He pauses and thinks. “I mean I can talk about it as much as I want but at the end of the day it’s just electronic music with vocals; I could just say whatever and people would go, ‘Oh yeah.’” This is a snapshot of how honest, self-deprecating and disarming he is; playing down what he achieved in creating the brilliant ‘Lucky Shiner’, which won rave reviews and saw him triumph in the Guardian First Album award. It struck a chord with many, a strikingly rich record of samples and loops, which sounded not only ambitious but also warm and human. This time, however, he was determined not to repeat himself. “I didn’t want to make ‘Lucky Shiner Part 2’. I also wanted to go back to a way of making music that I was doing originally without a laptop and just have fun. I thought ‘Do whatever you want or you’ll just be annoyed.’” then they became really expensive. You hear the Roland 808 in loads of stuff now and it’s always referred to in songs and stuff but it’s never the real sound of an 808 in those songs. You’re more likely to hear the real sound of it in house music or something. So I just wanted to use the machine in the way I think it was originally intended to be used and not put it through a hundred compressors.” With this album, he’s trying to push against the generic. “I like electronic music that isn’t trying to be too clever and kind of basic I guess. That’s the stuff I find interesting musically and not sounding like over-polished software demo music, a lot of dance and electronic music sounds like that. I wanted this album to have a bit of grit.” Not a natural performer he’s also found a way to change his live set, inspired both by boredom and the desire to put on more of a show. “I’ve been trying to stop using a laptop because I’ve been to a few shows and seen people on stage in hoodies and I looked at them and thought, ‘Is that me? Is that what I’m doing?’ “I think my main thing is that I never intended to play live and I don’t really go out and see live music, especially electronic music. I don’t go clubbing very often so I feel like I’m cheating e v e r y o n e . Sometimes I have really good shows and I realise why I’m doing it, and other times I’ll be rubbish and I’ll think electronic music is the worst thing ever. I think there are two ways that electronic music can come across in a live sense. The first one is not doing much but it sounds brilliant and you’re really into it; or the person’s doing loads and maybe the quality suffers. I opted to do loads and maybe make loads of mistakes. I get bored just standing up there.” And he’ll be taking this live show to festivals throughout the summer including Beacons, Lovebox, Sonar and Glastonbury. Not that he’s too bothered by the latter. “It’s just not really my thing, just a big field with thousands of people. I’m 32, I should be at home drinking tea and eating biscuits with the telly on.” Yet despite his disregard for Worthy Farm, his passion for making music and being inspired by the places he visits comes shining through. Which brings us back to the subject of Japan. Would he consider living there? “I’d love to. I could see myself living in Kyoto. Sometimes I think I should be buying property and settling down but there are so many places that I want to go for maybe three months or six months, and I’ve got the opportunity to do it with this job which is basically playing music for people. I don’t know. We’ll see how this album does!” Gold Panda’s new album ‘Half Of Where You Live’ will be released on 10th June via Wichita. ”l'll never be happy.” When asked if he’s happy with the album he answers in typical fashion. “I’ll never be happy. I feel happier than I did when I finished ‘Lucky Shiner’ which is probably good for me but I don’t know if it’s good for the fans cos it’s quite different. Basically after the last album I tried to make more tracks like ‘You’ but I couldn’t. Once I realised that the reason I couldn’t was because I didn’t have any interest in making the same tracks again everything was fine, but it took a while to forget about pressure and expectations. ‘Lucky Shiner’ just happened – I didn’t think about it, I just made it and put it out. I thought about this one too much. The actual process of making the album didn’t take too long but I took a lot of time not really doing it, doing shows and still doing ‘Lucky Shiner’. I suppose I could still book another year of shows off the back of ‘Lucky Shiner’, but it was kind of getting on my nerves.” Creating a new way of working and a new sound meant using different tools, and there was one he particularly had his eye on – the Roland 808. “I’ve always wanted one and 46 thisisfakediy.co.uk 47 interview Jagwar Ma T hey say the Australian way of life is all about relaxing; savouring an ice cold bevvy on a sun-soaked beach. After a few Skyping hiccups, an introduction to Jimmy the dog and a quick discussion apologising for the state of his hair, this idea proves itself to be spot on when we chat with one third of psych-pop outfit Jagwar Ma. Casually sipping a beer in his Sydney-based beach house, Gabriel Winterfield looks to be the epitome of relaxed, and why shouldn’t he be? After all his band has just gained international recognition, finished recording their debut album and bagged an entire summer of festival slots. “I went to the beach today - I’m actually an hour North in a part of New South Wales called the Central Coast and it’s really lush here,” he muses as we jealously ponder moving to the other side of the world to escape the drizzle of rural England. Not only is the weather currently more appealing, Australia’s music scene has been somewhat taking off of late, what with Tame Impala’s ‘Lonerism’ landing high on many an album of the year list in 2012, and smaller bands such as Splashh and Au.Ra gaining recognition as their music seeps across borders. Sydney’s Jagwar Ma are the latest additions to this Aussie movement; the physical distance proving irrelevant to UK crowds. “It’s so cool that the UK get it; there’s something about the UK and Western Europe. We didn’t even expect anything; when we first did ‘Come Save Me’ it was just a cool song to play on my iPhone and listen back to - we didn’t think other people would respond so warmly.” Forming in late 2011 and consisting of musicianproducer Jono Ma, singer-songwriter Gabriel Winterfield and Jack Freeman who plays live, Jagwar Ma first came to our attention a year or so ago, with their blend of nostalgic 60s Beach Boys shimmer-pop, coated with lashings of Tame Impala-esque psychedelia. “All three of us actually used to play in different bands that all toured around Australia together. Some time went by and Jono was producing and I had some demos that I was working on so I showed him some songs and he thought it was really rad. Then he showed me some stuff where he needed someone to sing, so we formed a sort of deal where he produced my stuff and I sang on his. His stuff was quite electronic and the band I was doing was quite 60s so we went back and forth and as we were working on both - and I guess probably influencing each other 48 thisisfakediy.co.uk U n d e r A u s t r a l i a c u r r e n t l y f o r n e w a h o t i s b e d m u s i c a l T h e i r e x p o r t ? t a l e n t . l a t e s t Land D ow n J a gw a r M a . W o r d s : L a u r a E l e y . both ways - it started sounding like the same band.” Hence the birth of Jagwar Ma - a band name formed partly from Jono’s surname (Ma), partly from a “painting of a Jaguar which a friend of ours found on the side of the road. He kinda gave it to us and it became this sort of omen. I took a photo of it and had it as the background on my phone, it was a weird thing.” Having already toured with the likes of Foals and The xx, Jagwar Ma have sprung into the limelight with a slot at the legendary Glastonbury festival, and an LP release on the horizon - the recording of which invoked much beardgrowing and campfire singing. “We recorded the album in rural France; Jono and I recorded most of it by ourselves obviously with a few cameos here and there like Stella from Warpaint and Ewan Pearson who did a few synths and stuff. The idea was just to go away and focus. Sydney is nowhere near as big as London but there’s sure enough people there to distract you and there’s always things happening so you get really wrapped up. In France we could ditch our retail jobs and there was nothing to do at night apart from sit around campfires and write music so that’s what we did.” Back on home turf then, the band are getting ready to swap French countryside for festival fields and sweatbox venues with stops at T In The Park, Glastonbury and winding up at Ibiza Rocks with previous tour mates Foals – and they’re pretty excited about it. “They’re a really solid band, I think they’re really good - Yannis is a good songwriter and it was fun to play with them before.” It’s not just the songwriting Gab’s impressed by though, as he contemplates mimicking some Yannis-inspired stage antics. “The band I was in before was very shoegazey almost, and Jono’s was kind of dark and techno, and the thought of jumping into a crowd in a band like that - it’s just not gonna happen. I remember actually saying when we did Big Day Out festival I’m so fucking glad I’m in a band now where I can actually crowd surf.” It may have taken a while to find the right band and the right sound, what with Gab being a previous member of Ghostwood and Jono having played guitar for Lost Valentinos, but Jagwar Ma are in the right place at the right time - even if that’s the other side of the world. Their sound is as relevant, fresh and endearing as ever - like Gab says, maybe the UK just “gets it”. Jagwar Ma’s debut album ‘Howlin’’ will be released on 10th June via Marathon Artists. “I’m so fucking glad I’m in a b a n d n ow where I can a c t u a l ly c r owd s ur f. ” 49 interview empire of the sun 50 thisisfakediy.co.uk “ E v e r y o ne Empire Of The Sun’s Nick Littlemore W an t s T o Be In T h e B i g g es t o n t h e f l a m b o ya n t A u s s i e d u o ’ s n e w a l b u m , h i s r o l e i n C i r q u e d u So l e i l , and a fetish for retro synthesisers. Band In T h e Wo r d s : D a v i d Z a m m i t t . W o r ld ” 51 interview empire of the sun F ive years ago, Sydneysiders Nick Littlemore and Luke Steele dropped their debut album as Empire Of The Sun. Since then, ‘Walking On A Dream’ has shifted over a million copies globally, racked up a pair of BRIT nominations and seen them garnered with a host of accolades in their native Australia. The LP’s eponymous lead single and its follow-up, ‘We Are The People’, dominated the world’s airwaves as the summer of 2008 wound down. Since then, however, things have gone eerily quiet on Empire Of The Sun’s surrealistic planet. Steele toured as a solo act, while Littlemore ran off to join Cirque du Soleil. Now they’re back with a new album, ‘Ice On The Dune’, that looks set to soundtrack the summer once again. But why has it taken so long? “A lot of things have happened,” says Littlemore. “Right around the time that we were finishing ‘Walking On A Dream’, I met Sir Elton John and he basically changed my life, as he tends to do with people. He said, ‘You have to move to London. I’m going to manage you.’ And then Empire just kind of blew up.” He isn’t just name-dropping, however. The artist formerly known as Reginald Dwight imbued him with a confidence that he hadn’t experienced before. “Subsequently Elton championed me and introduced me to Cirque du Soleil and I went on and joined the circus rather than going on tour with Luke. I lived with the circus for about two years and followed them around the world. I also made an album of Elton’s material which went number 1 in the UK”. He laughs. “Never done that before.” With both parties engaged in their respective, converging 52 thisisfakediy.co.uk careers, the re-emergence of the synergy that spawned hits at the turn of the last decade was a gradual one, the pair cautious not to rush into things. “Luke and I met up about 18 months ago in New York and started writing. We hadn’t seen each other in quite some time. We talked to each other here and there, but then we started hanging out and building the bridge.” After the hiatus, things finally clicked and you get the sense that even Littlemore didn’t realise how big ‘Walking On A Dream’ actually was. “It just felt right. Most bands could live and die in five years but we felt like this band – it just keeps growing and people keep getting exposed to it. People, all the time, are discovering this record. I go into cafes and they’re playing the record and it’s so cool. It feels young still. I feel that this project will never die; it has so much life to it.” Nick has been a notable absentee from the live Empire Of The Sun show, the direction of which has been piloted solely by Steele. Fans hoping to see the duo united on stage, however, will be disappointed. “I know it’s going to be incredible but I’m not on the road this time because I’ve just signed on to do another circus in China and I’m doing an album with Ladyhawke.” That’s not to say it will be a pared down affair; Luke Steele isn’t quite a shrinking violet. “I understand from the snippets and few bits of video that I’ve been sent that it’s going to be quite remarkable, but I wouldn’t expect anything else from Luke anyway.” confines of indie? He’s bullish in his affirmation. “Everyone in a band wants to be in the biggest band in the world, and anyone that denies that is a liar. The other thing is that I’m very interested in music, full stop. I pretty much work with people who ask me to work with them - which is not that many people - but every time they do, I do it. Whether it is Mika who’s sold 12 million records or whatever it is - it doesn’t really matter to me. I love making music.” While he’s at pains to point out just how out of his depth he found himself at the beginning, Nick is coming round to the idea that he may have at least a flicker of talent. “My girlfriend always says, ‘You should stop telling people you have no talent, because they might start believing it,’ but it’s just my self-deprecating nature. I always imagine that really I’m shit and I can’t imagine why anyone would see anything in me. You can actually do anything all the time; you just have to stop yourself from stopping yourself, if you know what I mean. The negativity that inhabits us is shit, and you want to take it away from you because it’s useless. We thrive on positivity and I think any type of creation thrives on that. It thrives on magnetism.” It’s that uninhibited positivity that drives the group and when we enquire as to the Cirque’s influence on Empire Of The Sun, we’re greeted with an infectious gusto for creativity in general, strung together deluge of ampersands as he describes the tenets that underpin While it remains to be seen whether Empire Of his musical manifesto. “It would so easy for me to The Sun will ever become a fully-functioning sit here and write depressing music. I could do live act, the reasons for Littlemore’s truancy it until the cows come home and it’s very are more than valid. He’s been far from natural and very simple for any musician “ T h i s resting on his artistic laurels, and he’s to write sad songs. It’s much harder effusive when speaking about his to write happier songs because p r oj e c t time with the circus. “What they can come off sounding w i l l n e v e r attracted me to it was that twee and fake and like I was so out of my depth it they’re a band for hire or d i e ; i t h a s s o wasn’t even worth laughing something. But when you m u c h l i f e about. But I met the director create something positive in and the producer. François Girard, the world, that truly comes from a t o i t . ” the academy award-winning director real place, people can’t fault that and – and I’d always been interested in film you go along with it and it makes you and theatre and other things like that. They feel good. I think that we were put here wanted me to try.” He pauses and reflects on to do positive things and what we want from a piece of advice that was handed down from his the audience is for them to feel good and to feel father. “You’re nothing if you don’t challenge yourself.” that anything is possible, especially in these times – they’re messed up times. We really feel like we need to In addition to his work with the Cirque, Littlemore has make aspirational records. We want to empower them to also been occupying himself by lending his production make great things and have wonderful lives, you know?” skills to mainstream pop artists such as Robbie Williams, Ellie Goulding and Mika. Is it important for him, then, to Empire Of The Sun’s new album ‘Ice On The reach an audience that extends beyond the chin-stroking Dune’ will be released on 17th June via Virgin. 53 interview disclosure S e t t l e D ow n , Boy s F rom t h e O ld B l u e L ast to B r i x to n A c ademy : D i s c los u re ’ s r i se h as bee n sw i ft . W o rd s : Coral W i ll i amso n Photos: Mike M assaro 54 thisisfakediy.co.uk I t’s really hard to interview brothers. When you’re trying to write things up, it’s near impossible to separate the voices, as Guy and Howard Lawrence warn us at the start of our chat. Considering some of the things we say to them over the course of our time together - accusing them of having accountants’ names, pointing out that having a song called ‘Grab Her!’ is a bit… questionable - they’re incredibly friendly, and, for a duo whose debut album hasn’t even come out yet, already seem old hat at the whole press thing. “We’ve got a whole week of promo, basically doing this non-stop. There’s worse things in life,” admits Guy. He’s the older of the two, and talks slightly more, but it’s obvious they get on brilliantly. “We get on pretty well, we’re just like friends really. We’re not very brotherly, like we don’t fight about stupid things. Sometimes we fight about food, like where we’re going to eat. Or ‘Why are you nicking my food, mate?’” That sounds pretty brotherly, really. And it’s a good thing too; their work schedule lately has been pretty hectic. What with touring America, Europe and the UK, you can imagine how disastrous a falling-out could be. “It’s nice,” Guys says. “We had last week off, kind of, we had a couple of DJ sets and that’s about it. But that’s it for the foreseeable future. We want to work hard, we want to put the effort in. We worked hard for this album, so we want to make it happen.” It’s strange how laid-back the two seem, considering how hard they say they work. But the evidence is there, and it’s all because they love what they do. “We like writing songs for our friends and for our family,” Guy explains, “and if they like it then we’re happy. It’s great that so many other people are feeling the same way, y’know? That’s really awesome. We never intended to make chart music or get into the charts, we just make music, the way we’ve always made it: because we love it. And it’s just amazing that we’ve had so much success - and a bit of luck, and good timing. It’s all falling into place really nicely.” Falling into place is definitely one way to describe Disclosure’s recent run of fortune. After the success of ‘White Noise’ earlier this year, newest single ‘You & Me’ has also hit the Top 10. But considering their age – Guy is 22, and Howard still a teenager – they’re not as cocky about it all as you might think. There’s certainly no danger of Bieber-sized fame tantrums, as they explain where the name of their album, ‘Settle’, came from. “It comes from a private joke that we had with our management, where everyone in the team that worked with us was just getting way too excited about everything,” explains Howard. “When we first started getting hype, every email was ‘Oh my god, this is amazing!’ and it got to the point where we all started telling each other to settle, like settle down. And now it’s just become a really rude thing that we all do to each 55 interview disclosure other when anyone says anything remotely positive. We just tell them to settle.” “It’s great that people like it so much that they’re excited about it,” he adds, “we’re not telling them to stop that. It’s just that all we’re really interested in is making the music.” This notion of making music for music’s sake comes up a few times, and they sound earnest every time they say it. Having crafted an excellent debut album, they’ve also taken to developing other aspects of Disclosure, rounding out their live show because, as Guy notes: “We want to make an impact this summer with the show, we want to make people remember it.” That’s the great thing about Disclosure. They want to do everything. They don’t care about being cool, or being the next big thing. When asked about the face graffiti that adorns their artwork, they explain their decision: “At the start we didn’t know if we wanted to do the whole mysterious, anonymous thing, or if we wanted to say, ‘Hi, we’re Guy and Howard, how’s it going?’ so we just used this. Howard enthusiastically explains how their live shows have “developed massively in the last few months. We’ve got a light show now, which we didn’t have before, and we’ve kind of changed the stage m u s i c . ” plot so that we’ve got two Speaking of next big work stations, one each.” things, you’d be forgiven Guy adds: “The music’s for thinking the brothers the same - we’re playing a are secret geniuses for their lot of the newer stuff, but collaboration picks. AlunaGeorge and London the way it’s presented has got a lot better, it’s a lot Grammar are just two of the names du jour that pop up different.” on ‘Settle’, with Jessie Ware and Jamie Woon being a couple of the more well-known appearances. But they He mentions that they’re playing 39 festivals this don’t choose based on who’s cool. “It’s mostly from summer, but they don’t seem particularly concerned chatting and friendships, people knowing people,” about such a high number. Mostly they seem explains Guy. “With AlunaGeorge, they supported us preoccupied with making sure their fans have a good on our UK tour so we had that connection and we time – if they can believe they have any. “When we were like, ‘Let’s do something’. did the Australian tour, it was crazy to see how many people came out to see us. It’s so far away, and you just “But other than that, it’s usually just from our think, ‘how could our music have gotten here?’ But it manager sending us videos of people from YouTube had, and it’s great. The only place we haven’t been yet that they’re looking at, because they’re getting a bit of is Asia, but hopefully we’ll be doing that this year as hype or whatever. And then we’ll meet up with them, well. It’ll be very interesting to see the reaction out get them down the studio, and just do something. there,” Guy says. We don’t really mind if someone’s big or small; Sam “And when we made the SoundCloud I started pasting it onto other photos of images that I liked. And blogs started reposting those, and then it just became a logo, and we’ve used it ever since.” Guy continues: “It wasn’t really for us, we had no reason to be anonymous. Also we wanted to do a live show, and I don’t “ W e n e v e r think you can get away with doing a live show and i n t e n d e d t o being anonymous.” “Unless,” Howard chimes in, “you do m a k e c h a r t SBTRKT’s thing and just wear a mask all the time.” 56 thisisfakediy.co.uk 57 interview disclosure 58 thisisfakediy.co.uk Smith, when we got him to do ‘Latch’, he hadn’t had a single song out. All we care about is if they can sing, and if they’re good. That’s it.” Talking about ‘Latch’ gives us a nice little segue into more talk about ‘Settle’; it was their first single from the album, released late last year. “We’ve been writing the album for about a year,” says Howard, “but one or two of the songs are older than that, we’ve just sort of come back to them more recently.” With three singles already released from the album, it feels like Disclosure have been around for a while now – or does it? “Because people tell us it’s fast, all the time, it feels fast, but when you think about it, every little step has been a bit more in the right direction,” Guy muses. “It has been slow, we played our first show in Old Blue Last in Shoreditch and now we’re headlining Academies. That feels like a long process. It’s all relative; if you compare our success to, I don’t know, Kings Of Leon, who are on their fifth album, it’s a very short time.” and verses and lyrics, and instrumental club songs. But under the name Disclosure, it’s basically all just influenced by house and garage. You can call it whatever you want, flippin’ future-two-step-lovemoombahton-core, I don’t give a fuck. It’s just pop songs, club songs, influenced by house music and garage music from the 90s.” The brothers have done their research; they know what they’re doing, and they know exactly what kinds of sounds they’re making. Well, most of the time. A couple of the songs on ‘Settle’ actually use Howard’s vocals instead of collaborators or samples, but that wasn’t how it was originally planned. “It was kind of an accident,” he explains. “I wrote this song, that’s on the album, called ‘F For “ D a n c e m u s i c You’. And I essentially wrote it so it could be re-sung, so i s v e r y I recorded my own vocals, just as a guide so I could remember it. Then I came f a s t - m o v i n g , back a week later and Guy had just finished the song. I a n d v e r y didn’t mean for it to happen but now it has.” He adds: “It d i s p o s a b l e . ” stands for ‘fool’.” When we admit to having assumed the ‘F’ potentially stood for something else, Guy joins in. “it’s quite an angry song, so it’s a bit ‘fuck you’.” There’s a lot of brotherly banter here, as Howard retorts: “That’s actually about me having a cold, so really there’s no deep meanings in it.” They both laugh, as Guy instructs us and future listeners to “Take from it what you will!” That’s Disclosure. Two young brothers having fun and making music that they want to make. Take from them what you will. Disclosure’s debut album ‘Settle’ will be released on 3rd June via PMR Records. We laugh, considering Disclosure making an album similar to Kings Of Leon’s sound, but Guy has clearly thought about the direction they’re going in. “Dance music is very fast-moving, and very disposable. But that doesn’t mean we’re always going to make dance music. I grew up listening to hip hop, and Howard would like to make an R&B, I know that for a fact. So who knows? I’d like to think that we could just have a career in music in some way, and just move with the scene.” When pressed for a description of Disclosure’s sound, Guy doesn’t have a clear answer: “We write a mixture between pop structured songs, with choruses 59 review queens of the stone age 9 Queens of the Stone Age …Like Clockwork (Matador) It starts with the sound of broken glass. An inauspicious beginning to any new undertaking, you’d imagine; but when it’s the first noise on the new Queens Of The Stone Age record, breaking the silence and bridging the chasm between 2007’s ‘Era Vulgaris’ and 2013, which gives us their sixth studio album, it takes on a different significance – and a cold wave of something between compulsion and apprehension creeps over you. What do Josh Homme and co. have in store for us? Opener ‘Keep Your Eyes Peeled’, a menacing, detuned, bass-driven dirge with Homme’s voice flickering between dangerously seductive and choirboy angelic, sets the scene of a darkening dusk in QOTSA’s world and battening 60 thisisfakediy.co.uk down the hatches for the horrors of the night to come. ‘The Vampyre Of Time And Memory’, a simple keys-led melody punctuated with synth, vaguely recalling the deft touch of Radiohead’s ‘Talk Show Host’, begins to plumb the depths of heartbreak with a vengeance. But at least he isn’t dealing with it alone. ‘Kalopsia’ is a deceptively mellow ballad with a plinky piano line played by Trent Reznor – before the drums and electrics kick in and it shifts into a wonderful chaotic, crashing, breakdown of a chorus; in opposition to its title, it’s actually far more beautiful than it first seems. It’s ‘Fairweather Friends’ however that features the biggest roster of friends and notable names from the world of rock, a thumping, pianoled number that still can’t escape from the matter at hand. Mark Lanegan’s iconic sneer rises above the crowd every now and then, and Queens make good use of having a real queen for once with Elton John: his baroque ‘n’ roll piano hammering is suitably bombastic and embellished with a Middle Eastern flourish. In case it sounds like it’s nothing but oppressive and suffocating sadness, it is put on pause now and then. A rare moment of levity comes in ‘Smooth TRACKLISTING Keep Your Eyes Peeled I Sat By The Ocean Sailing’, a filthy-sounding sex-funk jam in the sleaze-rock mould of Eagles of Death Metal, with the lyrics to match (“I blow my load over the status quo”); it almost sounds like a twisted duet between Homme and Eagles’ frontman Jesse Hughes. The pounding, anxiety-laden hook of ‘My God Is The Sun’ is pretty well established in everyone’s consciousness now. And even though it’s a heartbreak confession, ‘I Sat By The Ocean’, coated in a sunshine glaze, is a sure-fire radio smash. But ‘… Like Clockwork’ is at its core a dark masterpiece, and nowhere is the realisation of this more complete than on ‘I Appear Missing’. Devastating in its breadth and range, and possibly the best thing the band have ever done, it’s a sonic vision of night terrors of the soul made flesh, set to a pendulum-swinging rhythm, hypnotic and euphoric in its misery. It should go without saying but it needs to said: this is an intricate, jarring and complicated piece of work and is The Vampyre Of Time And Memory If I Had A Tail Kalopsia My God Is The Sun Fairweather Friends Smooth Sailing I Appear Missing ...Like Clockwork undeniably brilliant. Josh Homme’s evident growth as a songwriter is clear from the lyrical profundity on offer, not to mention the range of emotional response his vocals are capable of drawing. So while the brawling, teeth-gnashing, hip-swinging, cocksure swagger of their muscular brand of desert-rock has no doubt been interrupted by storm clouds rolling in on the horizon and unleashing a downpour no one saw coming – make no mistake: Queens are as brutal a force to be reckoned with as ever. It’s enough to make you fall to your knees and weep. (Shefali Srivastava) 61 reviews albums 8 Boards of Canada Tomorrow’s Harvest (Warp) They’re an act who haven’t released an album in ten years, basically never play live and whose last release was in 2006, yet Boards Of Canada’s ‘Tomorrow’s Harvest’ is one of the most anticipated albums of 2013. And it’s a record that feels, at times, harsh, arid and almost confrontational. There’s still that humanity to their music, and there are elements of the lushness, out of focus 70s effects that became their trademark, but here they are creating a sound that’s more jarring, more eastern bloc, more industrial. You can take what you like from these 17 tracks, but what’s clear is that however dark this album feels it still feels like progress. Boards Of Canada have created a fascinating vision, one that will reveal more and more gifts over time. (Danny Wright) 8 Howlin’(Marathon Artists) ‘Howlin’ is both a product of its time and of its influences, the Australian duo having created a stomping hybrid of contemporary dance and Sixties pop for their debut. Running the risk of being baffling, it comes off sounding rather brilliant. Highlights ‘Come Save Me’ and ‘That Loneliness’ show off the pair’s penchant for pop, while ‘The Throw’ tails off to hypnotic repetition. There are points where this begins to grate a little, the loops may make more sense in a live setting, but if anyone were wondering what Tame Impala might sound like had they spent a little more time on the nightclub dancefloor, ‘Howlin’ provides the answer. ( Jack Parker) Jagwar Ma 6 Beady Eye BE (Columbia) Ever get the feeling you’ve been duped? News that one Dave Sitek would be at the helm for Beady Eye’s second album raised more than a few eyebrows; a suspicion that continued with the brassy, pounding drums of ‘Flick Of The Finger’ and amplified yet more after the massive, percussion-tastic first single proper, ‘Second Bite Of The Apple’. What was this, we thought, has Liam Gallagher finally done something – dare we suggest – inventive? In short, no. Just five minutes in to ‘BE’ and the groansome lyrics return (“you’re the apple of my eye / spread your wings and fly”) and there’s still plenty of 60s pastiche to be endured. Business as usual, then, just recorded in a slightly nicer way. (Emma Swann) 5 jimmy eat world Damage (RCA) 7 Mount Kimbie Cold Spring Fault Less Youth (Warp) ‘Damage’ comes with a degree of promise attached - single ‘I Will Steal You Back’ is a wistful, lovelorn tune with enough anthemic stuff happening between verses to raise the hopes. Jim Adkins’ voice, the key in the lock to so many hearts and minds from previous exploits, is still as velvety and distinct as it ever was, providing more or less everything the band do with the gravitas of familiarity. But if the form has remained the same then the quality of content across the album as a whole is certainly a little suspect. When taken as a body of work ‘Damage’ is mid-paced and feels it. We’ll always have ‘Sweetness’ lads, but right now it might just be memories we’re clinging on to. (Tom Doyle) Mount Kimbie have struck gold. ‘Cold Spring Fault Less Youth’ may wobble in places and lose focus occasionally, but otherwise it’s a joyous record; different, but not unrecognisable. They’ve lost none of their charm and gained plenty of confidence; the luscious and echo-ridden beats of opener ‘Home Recording’ mixed with its soothing vocals is one just fine example of the beautiful shoegazey electronics Dominic and Kai are able to form. Fans of old will find solace in the understated ‘Sullen Ground’ and ‘Lie Near’, but it’s in ‘Made To Stray’ that they really find their stride. In short, one of the most engaging dance albums you’re likely to hear this year. ( Jack McKenna) 62 thisisfakediy.co.uk 21st Century disco anthem, but with opener ‘Give Life Back To Music’, they’re more like a time-machine: in fact, that, the melancholy slow-paced follower ‘The Game Of Love’, and then Moroder’s monologue-comedeconstruction of disco, mean that by the time the ‘sad robot’ utters “I am lost, I can’t even remember my name” over Gonzales’ wistful piano, a plot has formed. OK, so it’s hardly a conspiracy theory. The album’s title refers to computer memory. Our ‘sad robot’ is surrounded by the sounds of the 70s; he can’t remember who he is. It’s all gone a bit ‘Life On Mars’, and through both Casablancas’ 2001-channeling self, and Pharrell’s early-00s dancefloor hegemony we’re taken back ourselves. ‘Touch’, Random Access Memories (Columbia) only serves to confirm it. Our largest note “Sad robot”. These are the latest words here is “BATSHIT”, and it’s hard to know frantically scrawled on the notepad in front of where to begin. A re-birth, perhaps. Filmic me as I’m listening to the most-hyped album sound effects surround what first builds to in recent (ahem) memory. It’s at this point a full-on musical theatre interpretation of the fact ‘Random Access Memories’ is not disco before breaking down completely amid going to be an ordinary album becomes very space-age effects and ominous strings. If Daft evident. In the run-up to any real information, Punk have spoken of their boredom with we heard a lot about collaboration. And here, electronics and created a full-band record as Daft Punk have almost fused completely with ‘Random Access Memories’ is, could this be their co-protagonists. Within about three their Pinocchio moment? Because if it’s not seconds of ‘Lose Yourself To Dance’ – by the the epic drums on the DJ Falcon-featuring time the first handclap appears – you know closer ‘Contact’, it’s the woodwind making it’s the work of Pharrell. ‘Instant Crush’ an appearance on ‘Motherboard’, or the jazz sounds like a Strokes song fed through a breakdown in ‘Giorgio By Moroder’. In fact vocoder, and not just because we’re overit’s the vocoder vocals – Panda Bear’s ‘Doin’ It familiar with Julian Casablancas’ vocals. And Right’ case in point, with its refrain “if you’re while ‘Giorgio By Moroder’ gives the game doing it right / everybody will be dancing” away in its title, there’s no mistaking the - which feel strange, not the analogue. synth patterns on show. And then there’s Confused? You should be. (Emma Swann) Nile. His licks may have made ‘Get Lucky’ a Daft Punk 9 TRACKLISTING Give Life Back To Music The Game Of Love Giorgio By Moroder Within Instant Crush Lose Yourself To Dance Touch Get Lucky Beyond Motherboard Fragments of Time Doin’ It Right Contact 63 reviews albums 9 The National Trouble Will Find Me (4AD) It’s testament to The National that during a recent exhibition they played the song ‘Sorrow’ for six hours straight and people turned out. Not only that: many stayed for the whole thing. band’s appeal. The formula isn’t flipped. 64 thisisfakediy.co.ukheavy. ( Jamie Milton) TRACKLISTING I Should Live In Salt Demons Don’t Swallow The Cap Fireproof Sea of Love Heavenfaced This Is The Last Time Graceless Slipped I Need My Girl Humiliation Pink Rabbits Hard To Find 7 Rave (Zirkulo/PIAS/Atlantic) ‘Cave Rave’ largely builds on the lighter, brighter moments of Crystal Fighters’ debut, Star Of Love’; as soon as ‘Wave’ kicks off, it’s about ten degrees warmer outside. Lyrically, however, it’s pretty head-in-hands; it takes a lot to not switch off after “let me tell you about a love natural / love that you just can’t help feeling / when feelings with meanings keep appearing” in ‘Love Actual’. But it’s outlandish, silly, summery and as brilliant as its title. Crystal Fighters have somehow managed to continue in making their seemingly unattainable mix of traditional instrumentation and ideas and dubby electronics work without disaster. (Will Richards) Crystal Fighters Cave 6 Frankie & The Heartstrings The Days Run Away (Wichita) Frankie Francis first showed his face in 2011, Heartstrings in tow with debut album ‘Hunger’, the catchier-than-youwant-it-to-be title track proving the highlight. It was a nice slice of indie pop, and ‘The Days Run Away’ is almost a straightforward sequel to this. Musically, it’s a competent performance. But bar almost embarrassing ‘slowie’ ‘Losing A Friend’, the guitars all blend in to each other throughout, making the lyrics the most distinguishable part. This doesn’t work to Frankie & The Heartstrings’ advantage; they’re far from profound. A simple, pleasant, indie pop album, but nothing spectacular. (Will Richards) 17/6/13 austra Olympia empire of the sun Ice On The Dune lemuria The Distance Is So Big Sigur ros Kveikur Surfer blood Pythons The electric soft parade IDIOTS Tripwires Spacehopper UP 7 Majical Cloudz Impersonator (Matador) Although by no means the first musician to do so, with his 2012 ‘Turns Turns Turns’ EP Majical Cloudz was smart enough to remove himself from hazy, shrouded production, instead opting for a direct confessional approach, with vocals at the top of the mix. It just so happens that Devon Welsh possesses one hell of a voice. Each note on ‘Impersonator’ is pronounced, bellowed from the proverbial hills. And at first it’s uncomfortable, upfront to the point of no return. But in ‘Impersonator’ there’s beauty, in the melting production that accompanies Devon’s pronouncements, and in the stories he tells. ( Jamie Milton) Big Deal’s 2011 debut ‘Lights Out’ was loved for its intimacy; ‘June Gloom’ will be loved for how big it sounds. Fleshed out with a full band to accompany duo Alice Costelloe and Kacey Underwood, tracks like single ‘In Your Car’ sound dramatic and full-bodied, but still in possession of the emotional intricacies that made us enjoy Big Deal in the first place. Costelloe is at the forefront of the vocals for much of this, but Underwood is still audible under all the noise. ‘Dream Machines’, with its pounding percussion, is very cleverly layered. It makes you wonder why they didn’t expand beyond a duo before, proving that Big Deal really are a big deal. (Coral Williamson) 8 Big Deal June Gloom (Mute) cominG 24/6/13 bosnian rainbows Bosnian Rainbows Deap Vally Sistrionix ooooo Without Your Love Smith Westerns Soft Will 1/7/13 about group Between The Walls editors The Weight Of Your Love Goldheart Assembley Long Distance Song Effects Waxahatchee Cerulean Salt 8/7/13 maps Vicissitude 15/7/13 AlunaGeorge Body Music 65 reviews albums and closing the album with the sound of the future. It’s a debut that tells a narrative, of everything that Disclosure have achieved up to now, and everything they’re capable of amounting to in years to come. They lend their own vocals to ‘F For You’, which beyond standouts ‘Latch’ and ‘White Noise’ - which were never going to be topped, let’s be honest - is the sweatiest, sexiest cut on the album by a long stretch. Sasha Keable announces herself as a future star in ‘Voices’, but the maddening ‘Grab Her’ and a Jamie Woon-featuring ‘January’ both lack sheen and immediacy, and they’re lumped in towards the end of the record. ‘Latch’’s offbeat pulse isn’t replicated Settle (PMR) across the board. In fact the rhythm is rarely Out of intention or otherwise, ‘Settle’ opens raised, with a good third of the tracks opting with an aptly titled song: ‘When A Fire Starts for a 4/4 beat and customary drops which, To Burn’. That’s how it felt when Disclosure’s as the album progresses, become less and stock began to rise in 2012, when European less startling. Nothing gets close to ‘White festival dates to crowds in the thousands Noise’ in terms of sheer frenzied hysteria, became commonplace. It wasn’t just brothers and tracks like ‘You & Me’ go borderline Guy and Howard Lawrence’s name that formulaic. It’s down to London Grammar to spread like wildfire, it was this big, fat house offer something out of the ordinary, closer revival that came to light too. Because ‘Settle’ ‘Help Me Lose My Mind’ providing an is more than just the disc it’s contained within. emotive comedown to an otherwise endless It’s a movement, the emergence of a revival party atmosphere. None of the gripes really scene that’s disgusted stalwart house lovers matter when you consider ‘Settle’’s endpoint. as much as it’s swept the club movement up The reach of this record is remarkable, almost into its palms. For all its star-studded cast, infinite. Guy and Howard make few slip-ups, it’s just the laying of the foundations for ensuring the fire burns, and will continue to something bigger. ‘Settle’ isn’t by any means do so until this house revival is less a sudden magnificent, but it’s good enough to be resurrection, more a fad of the past. The fire associated as the defining album of the current will simmer out, and one day this record will revival. The emphasis is on documentation, sound ridiculously dated, but for the time being drafting in Jessie Ware post-’Running’ remix, it is everything 2013 requires. ( Jamie Milton) Disclosure 8 TRACKLISTING Intro When A Fire Starts To Burn Latch F For You White Noise Defeated No More Stimulation Voices Second Chance Grab Her! You & Me January Confess To Me Help Me Lose My Mind 66 thisisfakediy.co.uk 8 These New Puritans (Infectious) ‘Field Of Reeds’ isn’t eclecticism for eclecticism’s sake. But when you read the list of guests on These New Puritans’ third album, you might scoff: Michel van der Aa - a man responsible for 3D-video-operas; Elisa Rodrigues, a Portuguese blues singer; synergy vocals; a children’s choir; violins; french horns. Is it all strictly necessarily or is it just like a veteran tourist showing off the fruits of their travels? You wonder as much until you play the record. Though on the surface you’re most led towards Jack’s own, monotoned vocals, what eventually plays out on ‘Field Of Reeds’ is quite remarkable. You’ve something like ‘V (Island Song)’ that, during its 9 minutes stay, swings from electronic throbs to de-tuned piano, right up to the all-important basso profondo. If it sounds ridiculous, it is. Ambition often manifests itself into self-indulgence, but this is an exceptional case, where its makers hit the jackpot, where imagination runs riot and gets away with every daring feat, each one more foolish than the previous. ( Jamie Milton) Field Of Reeds 7 Sob Story (Wichita) Spectrals have always had an ear for melody. On debut ‘Bad Penny’, though, it was hidden behind the lo-fi recording approach like a fog-obscured view of the Yorkshire Dales. So what do they do for the follow-up? Bring in buddy Chet “JR” White on production duties, of course. The remarkable difference he can make is plain to see. Take lead single, ‘Milky Way’, it may prance along with some hearty scoops of garage rock and soul, but it’s the slick mix of defiant vocals and warped noise that make all the difference: ‘Sob Story’ is as much a follow-up to ‘Father, Son, Holy Ghost’ as ‘Bad Penny’. But don’t underestimate Louis’ new-found confidence. (Samuel Cornforth) Spectrals 8 Desire Lines (4AD) Three years after ‘My Maudlin Career’ troubled the Top 40, Camera Obscura return with their own brand of literate, swooning pop music in the shape of new long-player ‘Desire Lines’. It’s a record that feels honed and constantly improved, yet retains an aura of warm contentment throughout. On slower, reflective moments such as the lilting ‘This Is Love (Feels Alright)’ it feels equally at home in your living room at night and a hazy afternoon in the sun. It oozes an elegant stream of sophistication and songwriting nous throughout, backed up by rich, well-thought out and measured production. Assured, confident and cohesive – Camera Obscura have come up trumps. (Gareth Ware) Camera Obscura 7 Chapel Club ‘Good Together’ has two distinct settings: sometimes they flick the psychedelic, repetitive dance switch, and at others it’s the shimmering, falsettofuelled one. The vibes throughout, though, are most definitely high. Chapel Club’s new-found optimism has resulted in a far more accessible collection of songs than on 2011’s ‘Palace’. By no means have they ‘gone pop’, but they have given in to their strong pop sensibilities which were previously cloaked in reverb and melancholy. Lewis Bowman delivers his vocals in a far more playful manner; there’s both more scope and more character to his voice, and he has a new-found love of falsetto. Ridiculous maybe, but it works wonders. ( Jack Parker) Good Together (Ignition) 7 City AND Colour (Cooking Vinyl) As easy as it may be to pick ‘The Hurry And The Harm’ apart in regards to Alexisonfire’s split, this is a striking album that deserves to be seen fairly in its own light. Namely, one that marks a noticeable progression for City And Colour as it takes on the bigger exploits of a full band affair. Now his sole project, Dallas Green has used the extra time to experiment with more dynamic arrangements, picking up where ‘Little Hell’ left off. It’s by no means revolutionary, but after a decade of dividing between his priorities, this is Dallas finally taking the step out on his own. And it suits him extremely well. (Hannah Phillips) The Hurry And The Harm 67 reviews albums 9 Laura Marling Once I Was An Eagle (Virgin) Laura Marling is often portrayed as a timid little figure with white-blonde hair and pretty folksy guitar melodies. If you ask some of the popular music streaming services for their two-pence worth, they’ll compare her to Mumford And Sons, with their banjos and token blade of wheat in the corner of their mouths. They’ll suggest ‘golden oldies’ Bob Dylan and Neil Young, too, which perhaps come closer. On ‘Once I Was An Eagle’, Marling proves that while she might remind people of Joni Mitchell, John Mayall, or anyone else you can shake an acoustic guitar at, she is not simply an imitative by-product. There’s that perhaps deliberate allusion to Bill Callahan’s album ‘Sometimes I Wish We Were an Eagle’ in the titling, and in ‘Master Hunter’, there’s a cheeky nod to Dylan; “You want a woman who will call your name? It 68 thisisfakediy.co.uk ain’t me, babe”. In truth, though, Laura Marling’s main influence is drawn directly from her own heart and soul, and she soars like an eagle on the viewless wings of poesy. The narrative drawn by her throughout is at times heart-stopping, segues and recurrent motifs creating effortless enjambment. There’s unity and cohesiveness that derails romance through careful parenthesis - “When we were in love (if we were)”. Aged just 23, Laura Marling’s output to date is quite remarkable; she has quite literally never produced anything remotely chaffy, and the jewel in the splendour of ‘Once I Was An Eagle’ comes in the mythology of ‘Undine’, as she stands on the seashore listening to the tempting call of the water nymph luring her farther into the pouring ocean. “Undine so sweet and pure, make me more naïve,” she yearns at first, with intricately picked guitar that lurches uneasily across the fretboards. Alas, though, Laura Marling cannot swim, Undine “cannot,” therefore, “love me”. She stands alone and steadfast on the shore, with the lapping sea snatching fruitlessly at her feet. Was there ever a more apt image for an artist with a beautifully decisive and singular vision? Laura Marling seems to be an unshakeable creature, whose art firmly belongs to herself. Compare her to Bob Dylan all you like, but to issue a bold statement, Marling here proves herself, not as a product, but as an equal. Further down the line, it seems likely that on the emergence of another deceptively quiet young songstress with lyrics that stab and capture minds, the words on everyone’s lips will be ‘this sounds like Laura Marling’ instead. (El Hunt) TRACKLIST 7 TRACKS Portugal. The Man editors A Ton Of Love This is the biggest and fullest Editors have ever sounded, and opens up a world of possibilities for forthcoming album ‘The Weight Of Your Love’. Tom Smith’s instantly recognisable voice is the only thing that makes this still Editors, touring with R.E.M. seems to have had an effect on the Birmingham lot; you can almost hear Michael Stipe in Tom Smith’s wailing of “desiiiiiire”. What we have here hints at very promising things to come. (Will Richards) THE BEST OF Evil Friends (Atlantic) Baggy, psychedelic vocals make up a large amount of ‘Evil Friends’, overset by layers of acoustic guitar, aggressive piano and fuzzy guitar solos that belong in another decade, yet intertwine themselves into this wonderfully crafted sound that Portugal. The Man produce. ‘Modern Jesus’ provides the crux of the record, with its MGMT-like layered vocals; another little something is added with every subsequent chorus. The song proves a real trip of three minutes before ending abruptly to enter the guitarheavy ‘Hip Hop Kids’. For creating something as fresh and strong as this at album number eight, Portugal. The Man deserve to be applauded. (Will Richards) money Bluebell Fields Ambitious without being bombastic, the Manchester band take woozy psychedelia, 80s avant-garde pop, Sigur Rós and meld them together to create the euphoric sound of flying. In its four minutes there’s dreamy reverb, voices flowing in and out of the background, guitars entwining; all the elements seeming to melt together in the sunlight. As frontman Jamie Lee sings of the “bluebell fields in your soul” it’s easy to get lost in the majesty of it all. (Danny Wright) ‘Jerk Ribs’, the first track premiered from Kelis’ sixth album, couldn’t possibly be more different from her infamous dancefloor anthems. It’s the sound of Kelis rediscovering her soul. The defining feature is some rousing bursts of brass, there is a brilliant sense of filmic chutzpah at work, a grand statement announcing Kelis’ return. This is a summer anthem for city streets and their sultry night time sprawl. (Martyn Young) kelis Jerk Ribs 7 Wild Nothing Wild Nothing’s, or rather the genre-defying one-man whizz behind it, Jack Tatum’s, seven-track. A laid-back, well-considered and joyous effort to swing you through the summer months. (Anna Byrne) Empty Estate (Bella Union) The xx’s contribution to The Great Gatsby OST is all delicate notes, soft and simple, hidden behind hushed vocals, atop haunting, pulsating drums and bass: a sentence regular followers of The xx will be used to reading. It’s perfectly atmospheric, dark and stirring with the understated sex appeal The xx do so well, and the finale is brooding and beautiful leaving the mind to boggle over what scene it could be set to. (Hugh Morris) 69 the xx Together live liverpool sound city photos: Hannah Cordingley L iverpool Sound City festival opens for the sixth consecutive year, and DIY is proud to have our own stage at The Shipping Forecast slap bang in the heart of the city’s happening arts quarter. One of the biggest performances of the night there comes from unstoppable Manchester band PINS. They seem to exert a strange power over the crowd; their raw and mesmerising sound takes you in a stranglehold, and you’re no longer certain if it’s the half-primal beat of the drum and bass you’re hearing in songs like hit ‘Eleventh Hour’ and ‘LuvU4Lyf ’ or just your quickening pulse pounding in your ears. Siblings Eoin and Rory Loveless of Drenge also grace the DIY stage with their unique version of seething, punked-up rock tinged with a little blues. For their final song, ‘Let’s Pretend’, Eoin clambers up onto the drum kit, recklessly edging closer and closer to his brother until their smirking faces are inches apart and he finally loses his footing , collapsing forward, taking Rory with him in a riot of shoving and elbows while the crowd bays and the guitar screeches at the upheaval. Having already released their debut EP single about the keen pang of encountering your ex, ‘I Get A Taste’, in March this year, hot newcomers Loom explode into a performance of the song with an aggressive array of frenzied guitar, drums and sweaty fringes. They pace about like captive beasts until our humble stage can no longer contain them and they spill into the audience, self-assured lead man Tarek Badwan (yes, as in Faris) hurling himself into the crowd in an ecstasy of anger. The people below seem painfully tense and wary as he does so – to be fair, he has already casually lashed lager into their faces by this point – but their unease only seems to egg him on and he jostles through them, collapsing to the floor as he stabs his lyrics into the mic. Noah And The Whale draw a huge crowd as their foot-stomping tunes echo around the colossal heights of Liverpool’s Anglican Cathedral. It’s sort of a shame no taster footage from the band’s upcoming film is played in the background during the performance as the venue would be perfect for it. This, however, proves the only slight disappointment in an otherwise brilliant set with some tantalising new tracks thrown in. It’s been a mad one, and what’s most striking about Sound City is the huge mishmash of styles and talent it’s brought together that pretty much sums up the broiling vibrancy of the city itself. (Matthew Bridson) 70 thisisfakediy.co.uk 60 Seconds With d r en g e Y ou tour a lot. Do you prefer to headline or support? We just finished a co-headline tour with our friends Blood Sport & Temples, and that was great. Great atmosphere, great party feeling. Loads of tiny weird Northern towns. Any stand-out venues? The Chameleon in Nottingham is really funny, it’s like someone’s living room. Speakers everywhere. It’s the weirdest place we’ve played, brilliant. When’s the album out - is it done, finished, mastered? It’s coming out in August. Not mastered, still needs a layer of varnish. But yes, done. And more videos? Definitely - we like making them even when they’re not for singles. And is the record influenced more by current music or past? I have no idea what our influences are. We grew up listening to our dad’s record collection. Jazz, world music, prog rock. Early Beatles, standard stuff. And whenever Seven Nation Army came on the radio we’d both be in the back of our parents’ car going crazy. Looking forward to playing the show? Very much so. And we can’t wait to see Pins. When we saw the poster, we thought ‘no way, they should be headlining’. We’ve been into them from the start, they’re great. Who else do you want see at Liverpool Sound City? Tomorrow’s line up is amazing, we want to see everyone but we can’t see anyone. Splashh, Unknown Mortal Orchestra, Bo Ningen. It sucks. Such is life. 71 reviews live T Vampire Weekend t r o x y, Lo n do n photo: carolina faruolo his is the first chance, bar a handful of TV and radio appearances, for most of the audience to hear much of new record ‘Modern Vampires Of The City’. So, while set opener ‘Cousins’ is greeted by screams and accompanied by full-scale singalong, it’s when ‘Diane Young’, the album’s lead single, kicks in that Vampire Weekend step up. On record, ‘Modern Vampires Of The City’ is more mature and less frivolous than its predecessors; references to college campuses and parties are switched for constant references to growing up. Live, it’s even more pronounced: the new songs are beefier, fuller in sound. Vampire Weekend’s metaphorical balls have dropped. ‘Diane Young’ is already this summer’s festival anthem, and frontman Ezra Koenig appears to know so; the crowd’s subsequent applause met with a distinctly Elvis-like “thank you very much”, a nod to the song’s vocal theatrics. ‘Unbelievers’ gets a clapalong from the outset as the band deftly segue from ‘Holiday’ without pause. ‘Step’ is more soulful than even its recorded version, ‘Everlasting Arms’ sounds massive, ‘Obvious Bicycle’, saved for the encore has people pogo-ing to the sound of (we think) a pogo stick, and – undoubtedly the finest track on the new record – ‘Ya Hey’ – has more than a few singing along with the chorus the first time many have heard it. There are, of course, time for the oldies – ‘A-Punk’ is unsurprisingly the one that has the floor shaking, ‘Oxford Comma’ almost as much. ‘One (Blake’s Got A New Face)’, saved for the encore, makes the entire room look like a giant party, such as the whole room’s dancing, gleefully. As Vampire Weekend mix up the hits, they give a glimpse of just how big the rest of 2013 could be for the New Yorkers. (Emma Swann) 72 thisisfakediy.co.uk photo: emma swann i ’ l l b e yo u r m i r r o r c u r a t e d b y y e a h y e a h y e a h s A l e x a n d r a p a l a c e , Lo n do n at p W hen a band curate an ATP event sometimes you’re left trying to put the pieces together. With Yeah Yeah Yeahs at Alexandra Palace however, the process seems completely natural. From their art house leanings, the garage rock that underpinned their first EP and album through to the extravagant dressing and fashion; it’s all there: both Prince Rama and King Khan have a theatrical side, Dirty Beaches screams with intensity creating a sound that is strikingly similar to Suicide, and Black Lips bring their garage rock to the Great Hall. It was quite a coup to get The Locust to reform for this event – and they deliver a set of unremitting and uncompromising magnificence. After The Jon Spencer Blues Explosion it’s finally time for Yeah Yeah Yeahs. Karen O is, we can all agree, everything you want from a rock star. Even just shouting the letters ‘ATP’ she sounds cooler than at least ten other lead singers combined. It seems many of the crowd have just come to see the band and they won���t have been disappointed. They start with ‘Sacrilege’ and ‘Mosquito’, Karen dressed in that shiny silver suit with black feather wings attached. Tonight’s set sees them cherry pick from their collection of behemoths. ‘Zero’ is huge, and sees the crowd become a heaving mass of dancing bodies while ‘Y Control’ is frenzied art punk. For the encore they deliver a stunning and heart-snapping ‘Maps’ and finish with ‘Date With The Night’. Karen puts the mic in her mouth, unleashes a guttural scream and then they hold a pose, creating a dramatic effect before unleashing another sonic assault, Karen swinging the mic and smashing it down over and over. It’s been one hell of a day. (Danny Wright) 73 reviews live A s summer lazily creeps across the land, Live At Leeds shines like a beacon for music, beginning with Danish electro popster MØ who showcases an impressive array of energetic dance moves, insistent beats and a seductive swoon through brilliant tracks such as ‘Maiden’ and ‘Pilgrim’. With a sheen and intensity that only adds to the Lana Del Rey-meets-The Knife cocktail, she more than hints at a huge future for herself. Savages meanwhile don’t need much invitation to confrontation and they are ably provoked as the sound technician causes the first couple of songs’ vocals to be heard no louder than a whisper. It’s a breathless and rip-roaring set from the chaotic ending of second song ‘I Am Here’ to the wild shouts of “Husbands! Husbands! Husbands!” in the set’s closer. Finally, The Walkmen’s grace and friendliness puts them in between a new Rat Pack and a barbershop quartet with the fortune of being fronted by one of the best singers in the game. Whether he’s applying it to the vulnerable croon of ‘Line By Line’ or the raw throat-shredding growl of powerful indie anthem ‘The Rat’, Hamilton Leithauser holds the crowd in a unified sway, only breaking when he falls head first into the audience. The charming bounce of the organ or the resolute intricacy of the guitars, Leithauser makes the most of any backdrop. No matter how big the festivals are this summer, they may find it difficult to match the consistency of quality on display at this special little one. (Matthew Davies) live at leeds photos: Leah Henson 74 thisisfakediy.co.uk photo: Fraser Stephen unknown mortal orchestra daughter T K i n g t u t ’ s , g l a s gow D t h e o l d f i r e s tat i o n , bournemouth he UMO live experience is more visceral and raw than on record; there’s less of the primitive swirl in favour of a heightened intensity that keeps these elastic grooves together. The three-piece are outstanding - as well as the magnetic presence of front man Ruban Nielson, bassist Jake Portrait and drummer Riley Geare provide the perfect accompaniment as they twist their psychedelic jams into something quite special. One of those rare bands who could play continuously for hours at a time and few would lose interest, over the course of 90 minutes in Glasgow tonight they deliver a mini masterclass in psych pop of the highest order. (Martyn Young) aughter’s debut album ‘If You Leave’ has received a world of praise since its release a month ago, yet when they open tonight with its closing track ‘Shallows’, it’s evident that the trio are a significant amount less delicate live than on record, Elena Tonra’s vocals riding over waves of almost Sigur Rós-y ambience and piercing bowed guitars. A cinematic sheen blankets the entire performance, and is only broken by the upbeat, poppy ‘Human’ and Elena’s beautifully awkward stage chat. The singer couldn’t be less comfortable between songs, but as soon as the first note rings out of the next track, it’s clear she wants to be nowhere else more. The majority of ‘If You Leave’ is aired tonight, and although it’s broken up by older tracks ‘Candles’, ‘Love’ and ‘Home’, it’s clear that the more electronic, dark, space-y stuff is the direction they’re heading, and the Daughter that they are comfortable with continuing to become. (Will Richards) 75 reviews fashion fashion Festivals Whether it’s keeping dry, warm, looking after your hearing or capturing the summer’s best moments, here’s a selection of things to make your festivals that lit tle bit bet ter. 1 76 thisisfakediy.co.uk 2 2 4 3 5 7 8 6 1 FUJIfilm x100s camera £999.95 fujifilm.eu // 2 WeSC Retro Super Future sunglasses £115 wesc. com // 3 Adidas Originals 3 pocket backpack in Cardinal £35.00 jdsports.co.uk // 4 Moto Acid Wash Denim Hotpants £30 topshop.com // 5 H127 Music Safe Pro earplugs £23.99 actiononhearingloss.org. uk // 6 Deap Vally t-shirt £15 // 7 Rocketdog Buddy boot £59.99 rocketdog.co.uk // 8 MusucBag Classic wearable sleeping bag in Black £99.99 musucbag.com 77 film Ado About Nothing 8 Much Before post-production on The Avengers, Joss Whedon assembled his actor buddies in his California home to shoot a black and white, contemporary but faithfully scripted spin on Shakespeare’s Much Ado About Nothing. The very first romcom has been transformed into a witty, elegant and utterly charming comedy of manners, with Amy Acker and Alexis Denisof adorable as the squabbling friends who are meant to be together. As the wine flows during a family get-together, Whedon’s grasp of the comedy and treachery is superb, and the cast - including Clark Gregg, Nathan Fillion, Fran Kranz, Reed Diamond, Sean Maher and Tom Lenk - deliver the whipsmart, sophisticated dialogue with consummate ease, making this an incredibly accessible and clever adaptation. Delicious and summery, it’s a gorgeous, rich farce with intensely likeable actors. (Becky Reed) Released: 14/06/13 This month will see Michael Shannon as General Zod in Superman reboot Man Of Steel, but before then, catch the imposing actor as a natural born killer in the true story of mob hitman Richard Kuklinski. Winona Ryder co-stars as the oblivious wife of the seemingly normal family man, who for decades carried out ruthless gangland killings before his arrest in 1986. Ariel Vromen’s basic film charts events with disinterest, never delving too deep. The biggest crime here is not giving Shannon enough to really get his teeth into. (Becky Reed) 78 thisisfakediy.co.uk 6 The Iceman Released: 07/06/13 Midnight 9 Before The outstanding third film in Richard Linklater’s ‘Before’ series is fulfilling, heartbreaking and often funny. Nine years on from Before Sunset’s Parisian events, Celine ( Julie Delpy) and Jesse (Ethan Hawke) are in Greece, staying at a respected author’s house. Celine begins to pull the thread of the once beautiful romantic notion, and threatens to crush everyone in the revelation that dreams shatter. It’s exactly what you expect and yet so much more. A perfect trilogy capped sublimely with a great deal of humanity. (Andrew Jones) Released: 21/06/13 Mat Whitecross’ nostalgic drama is set in 1990, a few days before The Stone Roses played their infamous Spike Island show, centering around an aspiring fictional band desperate to score tickets. A sweet love triangle and some sadly unexplored themes of domestic abuse and terminal illness lend the film an uneven air: is it coming of age comedy or rites of passage drama? However there is much to enjoy, and it really feels like that long lost summer when the whole nation was baggy - and the soundtrack is second to none. (Christa Ktorides) 6 Spike Island Released: 21/06/13 JossWhedon T h e Av e n g e r s d i r e c t o r tal ks c o r p s i n g , q u i m s an d fa i r y ta l e c a s t i n g . A few hours after the Oscars finished broadcasting at 5am this year, journalists are cured of fatigue by the slightly awe-inspiring presence of one Joss Whedon, in town early to promote Much Ado About Nothing. Normal media cynicism is out the door, hushed reverence is in, as the softly-spoken, dry-humoured hero to geeks and feminists alike welcomes us into a London hotel room. Jet-lagged but friendly, Whedon jokingly pre-empts questions about why he decided to shoot a black and white adaptation of the Shakespeare comedy in the twelve days between filming The Avengers and heading into the editing room. “I am a fan of the dumbest things to be fans of - wow, I love Shakespeare! I love Dickens! How obscure,” he laughs. “It’s just something that excites me, and I’ve always wanted to film a play. When Amy [Acker] and Alexis [Denisof ] read it in my home, I thought, well, it’s Much Ado!” Alongside Whedon regulars Acker, Denisof, Nathan Fillion and more is newcomer Jillian Morgese as Much Ado’s young bride Hero. And when we say newcomer, we mean it - the fashion merchandising graduate’s previous experience was as an extra on The Avengers (as a waitress when New York is under attack). I ask about her casting, as it’s a fairy tale come true. “It kind of is, and I’m not unaware of that. I noticed her when I was forming the idea, and she actually introduced herself in the Marvel office when they were casting for extras. She’s not unmemorable, but she was just one of the waitresses, and Ashley Johnson who plays Margaret was another. I just kept throwing more and more stuff at her, but a lot of the waitress stuff got cut. She ended up doing well on The Avengers, getting a stunt bump because we kept blowing up things around her - she could really bring it. She has extraordinary poise. I felt like she, more than anyone else, would be Amy Acker’s cousin. They both have this regal strength, and they’re both tall, gorgeous brunettes with great noses. People underestimate the importance of a good nose.” Did the fact that the cast consists of Whedon’s friends, and was filmed at Whedon’s own home, make for some serious corpsing during shooting? “It happened once. It was a terrible day sound-wise, so I was tearing my hair out. It was the scene where Borachio confesses on the front lawn, and then I’m shooting and we’re finishing and everyone is just laughing their asses off. I’m like, guys? What the fuck is wrong with you? Nathan [Fillion] and Tom [Lenk] were doing the ‘we lost our keys’ bit, which they had just come up with, which I didn’t know anything about. They’re all looking that way and absolutely losing it. I was like, ‘Well, I’m really pissed at you guys - and we have to put it in the movie!” Bolstered by the champagne consumed during Argo’s Oscar win in the small hours, I shake Whedon’s hand and personally thank him for the great “mewling quim” moment in The Avengers. “I can’t believe we got that by the UK censors,” he laughs, adding: “I want to get quim back in the vernacular - in a nice way, of course!” (Becky Reed) 79 reviews games games Deadfall Adventures (Nordic Games) – Xbox 360, PC Release Date: 30/07/13 R e t ro Game Of The Month The makers of Painkiller: Hell & Damnation deliver an Indiana Jonesesque adventure that involves Egyptian temple complexes, ancient artefacts and occult-loving Nazis. Hoping to mix Saturday matinee pulp aesthetics with cinematic blockbuster action, Deadfall Adventures leaps, tumbles, swings and rolls under a door this August. Werewolves Of London In celebration of TellTale Games’ The Wolf Among Us, the forthcoming prequel to the comic book series FABLES, we had a look back at one of our most fondly remembered lycanthropic adventures – Werewolves Of London. The aim is to hunt down and kill members of an aristocratic family who have cursed you to a life of nightly transformations from a shoe-less fella into a hulking shoe-less man-beast. Despite featuring only one werewolf, it stays true to its London roots having a right old knees up as you clamber around the famous London Underground and Hyde Park looking for victims. Everyone looks the same, so those you’re meant to kill are indicated by crosses that flash up in the game’s confusing HUD. But feel free to feast on anyone to regain health, just like you shouldn’t do in real life. In fact, the macabre nature of stalking the streets as a nocturnal man-eater gives a ghoulish atmosphere that really works. Unfortunately, controlling the game is a nightmare of another sort, and you’ll often find yourself arrested and thrown in a jail cell waiting to transform back into a human. At which point they just let you go because, hey, we all make mistakes, right? Like changing into a wolf-freak and eating some Londoners. Don’t pretend you haven’t, we’ve all been there at a work’s night out. Surely this is begging for a remake. (Mastertronic, 1987) – Commodore 64 The Bureau: XCOM Declassified (2K Games) – Xbox 360, PS3, PC Release Date: 23/08/13 The first-person shooter version of alieninvasion saga X-Com has been in the works since 2006, way before Firaxis’ reboot last year. But, it’s finally coming out as a 60s-based prequel in which the FBI first encounter the extra-terrestrial scourge. Hoping to mix tactical gameplay with up-close action, only time will tell if the two will co-exist harmoniously. The Wolf Among Us (TellTale Games) – Xbox 360, PS3, PC, Mac Release Date: TBC out now and coming soon TellTale tackle Bill Willingham’s FABLES comic book series. This prequel follows Bigby Wolf, formerly the Big Bad Wolf, tasked with keeping a village of fairy-tale based creatures undetected. The Wolf Among Us will deliver moral choices that have a direct impact on the storyline, including whether or not Bigby gives into his dark wolfy side. The Evil Within (Bethesda) – Xbox 360, PS3, PS4, PC Release Date: 2014 Survival horror legend Shinji Mikami (Resident Evil) unleashes a new terror in which a police detective and his partner descend into a world of demons and madness at the hands of a mysterious, powerful force that transports them to a land where evil creatures roam. No, not Hull. 80 thisisfakediy.co.uk Activision and Infinity Ward have announced the latest title in the war-based shoot- man shooter-fest of shooting as Call Of Duty: Ghosts. The tenth instalment in the ultra-popular series is set for release on 5th November and the studio claim this will be an all-new story, with all-new characters and an all-new experience. So, that’s all-new then? But, let’s be honest, how all-new can it possibly be? If the Xbox One Reveal conference is anything to go by, they’ve brought in Stephen Gaghan, writer of Traffic, to pen the story and introduced a scarryheaded dog as a pal. Splitting the workload between two studios for Activision’s endurance test of a yearly release sees the series, ultimately, playing it safe every time. That’s not necessarily ‘a bad thing’. It can make bad business Call Of Duty: Ghosts sense to rock the boat, and we still lap up the series for its frenetic action and heart-stopping multiplayer modes. But, there’s a danger of complacency here if we continue to throw money at what is, essentially, the same game repackaged. Forty quid a year! We could join a gym. We won’t. Sadly, this is a time for triple-A game blandness, where the ill consequences of risks are punished by bankruptcy. Ghosts’ release will also sit uncomfortably on the transition of console generations. This is a CoD game that doesn’t quite know where to punch. Just trepidation, of course, we can’t be sure of anything until November. But Activision have acknowledged they expect the sales to be lower, so are we just looking at something half-arsed they’re releasing to satiate our pixel-lust and make some easy bucks? SHOCK NEWS: Publisher tries to make money from a popular game series. Microsoft have finally unveiled the next step in the evolution of the Xbox with the big, boxy VHS-esque Xbox One. Acting kind of like an all-seeing, all-knowing regulator of electronics in your living room, the new console is less about games and more about becoming a universal entertainment system that may destroy human life (not guaranteed). With an updated and integrated Kinect sensor, Xbox One allows you to seamlessly switch between gaming, TV, movies, music and the web like a digital wizard. A CPU of eight x86-64 cores and 8GB of RAM means it’ll run like a dream, but it seems like Microsoft may be forgetting its market – gamers. The Xbox Reveal event showcased EA Sports titles, a Halo TV series headed by Steven Spielberg and the only new IP, Quantum Break, had a live-action teaser trailer. Microsoft promise the console will arrive by the end of the year amid rumours of its inability to play pre-owned games without purchasing a code to electronically lock the disc to your console and its expected lack of backwards compatibility. More details will arrive at this year’s E3 Conference in L.A. 81 Xbox One 82 thisisfakediy.co.uk DIY available in the app store now WEEKLY thisisfakediy.co.uk 83 The Guardian Independent - Album of the Week Metro aaaaa aaaaa aaaaa aaaa aaaa aaaa The Times Daily Mirror MOJO Sunday Times -Album of the Week DIY - 9/10 Clash - 9/10 NME - 8/10 Uncut - 8/10 NEW ALBUM OUT NOW 84 thisisfakediy.co.uk 4a d. com a me r ica n ma r y . com | http://issuu.com/thisisfakediy/docs/june-2013 | CC-MAIN-2014-52 | refinedweb | 29,336 | 67.28 |
this programming shows you the example of floating point rounded off error. this error usually happen when you calculate numbers which has long decimal places or so on.
Expand | Embed | Plain Text
- /*
- Give an example of a floating-point roundoff error.
- Would the same expample work corrextly if you used int and awitched to a fuggiciebtly small unit, such as cents insted of dollars, so that the value don't have a fractional part?
-
- */
-
- public class floatingPoint
- {
-
- public double number1;
- public double number2;
-
- public floatingPoint()
- {
- number1 = 23.30;
- number2 = 13.21;
-
- }
- {
- floatingPoint sample = new floatingPoint();
- double amount = ((sample.number1 + (sample.number2*0.30))/45);
- }
- }
Report this snippet
Tweet | http://snipplr.com/view/46788/ | CC-MAIN-2018-17 | refinedweb | 108 | 58.89 |
Draft Downgrade
The
To downgrade objects use the
Draft
User documentation
Next: WireToBSpline
Description
The
Draft Downgrade command downgrades selected objects. The result depends on the number of selected objects and their type. The command can for example deconstruct a 3D solid into separate faces and a wire into separate edges. If two face are selected a Part Cut object is created from them. Note that not all objects can be downgraded. This command is the counterpart of the Draft Upgrade command.
Two overlapping faces are downgraded to a Part Cut object, which is downgraded to a face. That face is then downgraded to a closed wire, which is finally downgraded to separate edges.
Usage
- Optionally select one or more objects.
- There are several ways to invoke the command:
- Press the
Draft Downgrade button.
- Select the Modification →
Downgrade option from the menu.
- Use the keyboard shortcut: D then N.
- If you have not yet selected an object: select an object in the 3D view.
Scripting
See also: Autogenerated API documentation and FreeCAD Scripting Basics.
To downgrade objects use the
downgrade method of the Draft module.
downgrade_list = downgrade(objects, delete=False, force=None)
objectscontains the objects to be downgraded. It is either a single object or a list of objects.
- If
deleteis
Truethe source objects are deleted.
forceforces a certain way of downgrading by calling a specific internal function. It can be:
"explode",
"shapify",
"subtr",
"splitFaces",
"cut2",
"getWire",
"splitWires"or
"splitCompounds".
downgrade_listis returned. It is a list containing two lists: a list of new objects and a list of objects to be deleted. If
deleteis
Truethe second list is empty.
Example:
import FreeCAD as App import Draft doc = App.newDocument() circle = Draft.make_circle(1000) rectangle = Draft.make_rectangle(2000, 800) doc.recompute() add_list1, delete_list1 = Draft.upgrade([circle, rectangle], delete=True) compound = add_list1[0] add_list2, delete_list2 = Draft.downgrade(compound, delete=False) face = add_list2[0] add_list3, delete_list3 = Draft.downgrade(face, delete=False) box = doc.addObject("Part::Box", "Box") box.Length = 2300 box.Width = 800 box.Height = 1000 add_list4, delete_list4 = Draft.downgrade(box, delete=True) doc.recompute()
Next: WireToBSpl | https://wiki.freecadweb.org/index.php?title=Draft_Downgrade | CC-MAIN-2021-49 | refinedweb | 344 | 54.18 |
NAME
chroot - change root directory
SYNOPSIS
#include <unistd.h> int chroot(const char *path);
DESCRIPTION
chroot() changes the root directory to that specified in path. This directory will be used for path names beginning with /. The root directory is inherited by all children of the current process. Only a privileged process (Linux: one with the CAP_SYS_CHROOT capability) may call chroot(2). This call changes an ingredient in the pathname resolution process and does nothing else. This call does not change the current working directory, so that after the call ‘.’ can be outside the tree rooted at ‘/’. In particular, the superuser can escape from a ‘chroot jail’ by doing ‘mk(2).).
NOTES
FreeBSD has a stronger jail() system call.
SEE ALSO
chdir(2), path_resolution(2) | http://manpages.ubuntu.com/manpages/dapper/man2/chroot.2.html | CC-MAIN-2014-42 | refinedweb | 124 | 60.61 |
Ease.
So let’s make login easy by taking a look at how to use Ionic Native to integrate Touch ID into an Ionic 2 app for iOS.
Allowing users to log in to your app with Touch ID is one of the coolest and easiest ways to enhance the user experience. This is particularly true for iOS apps, since a very large number of users have upgraded to an iPhone 6 or 6s.
It’s high value, only takes a handful of code, and is pretty cool. Who are you to refuse?
Getting Set Up
To make things easy, I’ve put together a simple project for us to start with that has two pages and all the CSS we need. If you want to follow along, feel free to do the following:
- Download or clone the project from GitHub
- Run
npm installinside the project directory to get all the needed dependencies.
OK, let’s take a look at the project.
The first page is ‘Home’ in
app/pages/home/:
Looks like a pretty standard login form, except that we also have a fingerprint button to allow the user to choose to log in with Touch ID.
The second page is ‘Loggedin’ in
app/pages/loggedin/. The app will transition to this page when the user successfully logs in with touch ID.
That’s all there is to it. Time to wire everything up.
Touch ID is an Ionic Native plugin, so the first step is to add the plugin to our project:
ionic plugin add cordova-plugin-touch-id
Then import the plugin into our
Home component in
app/pages/home/home.ts. While we’re at it, we’ll also import our
LoggedinPage, so that we can transition to it later when the user successfully logs in with Touch ID, as well as
Platform from
ionic-angular to give us access to the Ionic Platform lifecycle events:
import {NavController, Platform} from 'ionic-angular'; import {TouchID} from 'ionic-native'; import {LoggedinPage} from '../loggedin/loggedin';
When the component first loads, we’ll also be checking if TouchID is available on the user’s device, so we’ll declare a
touchIdAvailable variable of type
boolean to store the result of that check. The variable is
private, so that it can only be accessed within this component. We’ll also create an instance of
Platform in our constructor:
private touchIdAvailable: boolean; constructor(public _navCtrl: NavController, private _platform: Platform) {}
Checking for TouchID
Now that we’re set up, the next step is to check if TouchID is available. After all, it would make us look pretty bad if we showed the option to log in with Touch ID, when it isn’t an option on the user’s device.
To do this, we call the static function
TouchID.isAvailable() in the constructor for our component once the Ionic Platform is ready, which is the point in the lifecycle when native functionality can safely be called.
TouchID.isAvailable() returns a promise that resolves if Touch ID is available and rejects if it isn’t:
constructor(public _navCtrl: NavController, private _platform: Platform) { this._platform.ready().then(() => { TouchID.isAvailable().then( res => this.touchIdAvailable = true, err => this.touchIdAvailable = false ); }) }
Next, to make sure the Touch ID button only appears if Touch ID is available, we’ll add an
*ngIf conditional to the button, which removes it from the DOM if
touchIdAvailable evaluates to false:
<button *ngIf="touchIdAvailable" round text-center>
Implementing Touch ID
Time for the cool part! This is all it takes to add Touch ID support to our app:
private startTouchID () { TouchID.verifyFingerprint('Fingerprints are Awesome') .then( res => this._navCtrl.push(LoggedinPage), err => console.error('Error', err) ); }
Here, we’ve declared a
startTouchID() function that calls the static
verifyFingerprint() function from the TouchID plugin. This invokes the native Touch ID functionality in iOS. It also takes a message as an argument that will be displayed in the modal when the user is asked to authenticate with Touch ID.
verifyFingerprint() returns a promise that resolves if the user successfully authenticates with their fingerprint and rejects if they fail. In this case, we navigate to the
LoggedinPage if the user is successful by pushing the
LoggedinPage component on to the Ionic navigation stack:
res => this._navCtrl.push(LoggedinPage)
All we have to do now is update our fingerprint button on our login page to call
startTouchID() when the button is tapped:
<button (click)="startTouchID()" *ngIf="touchIdAvailable" round text-center>
Now, when the user taps the fingerprint icon, they’ll activate Touch ID and be prompted to provide their fingerprint:
Success!
Since Ionic Native plugins don’t work in the browser or emulator, you will need to deploy the app to a device to try it out. If you have a developer device set up,
ionic run ios will do the trick, otherwise try out Ionic View or Ionic Package.
Once you have the app running, tap the fingerprint button, give iOS your fingerprint when prompted, and BOOM:
Pretty sweet reward for all that effort, huh? Unfortunately, she wasn’t very happy about the hat, but small price to pay for enabling advanced biometric authentication with a pretty minimal amount of code. | http://blog.ionic.io/ionic-native-enabling-login-with-touch-id-for-ios/ | CC-MAIN-2017-26 | refinedweb | 865 | 59.03 |
Flash AS3 error codeseasypzmaths Oct 4, 2007 10:42 AM
Does anyone know how I can find the meanings of the Flash AS3 error codes?
This content has been marked as final. Show 19 replies
1. Re: Flash AS3 error codesmgoodes Oct 4, 2007 10:56 AM (in response to easypzmaths)In AS3 help, look inside:
ActionScript 3.0 Language and Components Reference/Appendixes
2. Re: Flash AS3 error codesNewsgroup_User Oct 4, 2007 10:59 AM (in response to easypzmaths)
Look under Appendixes
3. Re: Flash AS3 error codeseasypzmaths Oct 4, 2007 1:03 PM (in response to Newsgroup_User)Thank you for pointing me in the right direction.
Unfortunately, the information there is almost useless . It says "Call to a possibly undefined method _"
This refers to a line in an AS file that starts
package {
With such a lot of possible causes they should aim to give us some examples to cross off.
Where to next I wonder???????????????
4. Re: Flash AS3 error codesmgoodes Oct 4, 2007 6:07 PM (in response to easypzmaths)I just solved a similar problem for myself. If you give us more information maybe we can help.
5. Re: Flash AS3 error codeskglad Oct 4, 2007 9:16 PM (in response to easypzmaths)if there's anything after the left brace on that line you either have a problem or unusual formatting.
6. Re: Flash AS3 error codeseasypzmaths Oct 6, 2007 3:50 AM (in response to mgoodes)Thank you for your response. In the same directory as DrawingShapes2.fla, using strict mode, I have a DrawingShapes2.as file. In publish settings/Flash tab/settings/Document class I have DrawingShapes2. When I click the green tick it says the class was found okay. I have set the classpath to the current directory. The AS file has the matching (, ), {, and } for constructor and listeners. Puzzled!
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class DrawingShapes2 extends Sprite {
var sp:Sprite = new Sprite();
public function DrawingShapes2 ():void {
sp.graphics.lineStyle(2,0x000000);
Later...
function mouseDown(event:MouseEvent):void {
sp.startDrag();
Sprite(event.target).alpha=0.25;
}
}// end of class
}// end of package
7. Re: Flash AS3 error codeseasypzmaths Oct 6, 2007 4:43 AM (in response to easypzmaths)Even this empty code causes "Call to a possibly undefined method _"
package
{
import flash.display.Sprite;
public class DrawingShapes2 extends Sprite {
public function DrawingShapes2 ():void {
}// contructor
}// class
}// package
8. Re: Flash AS3 error codeskglad Oct 6, 2007 4:54 AM (in response to easypzmaths)neither of those code snippets contain a coding error. copy the error message and paste it to this forum.
9. Re: Flash AS3 error codeseasypzmaths Oct 6, 2007 5:17 AM (in response to kglad)kglad and mgoodes, thank you for your time.
I eventually found a solution, but not a reason, at...
Once I removed the name DrawingShapes2 in publish settings/Flash tab/settings/Document class it compiled okay. It seems to be that such a named class has to extend a particular display object (not checked yet).
Many thanks.
10. Re: Flash AS3 error codeskglad Oct 6, 2007 5:19 AM (in response to easypzmaths)it needs to extend the Spite or MovieClip class. that's not the problem.
11. Flash AS3 error codeseasypzmaths Oct 6, 2007 6:31 AM (in response to kglad)The code is from ActionSciprt 3.0 - by Gary Rosenzweig but is has moved from the fla to an AS file. It was working fine. It has been changed and it isn't working now (yet to find out why). If I set DrawingShapes2 as the Document class it won't compile.
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class DrawingShapes2 extends Sprite {
var sp:Sprite = new Sprite();
public function DrawingShapes2 ():void {
sp.graphics.lineStyle(2,0x000000);
sp.graphics.moveTo(100,200);
sp.graphics.lineTo(150,250);
// create a curve and then another line
sp.graphics.curveTo(200,300,250,250);
sp.graphics.lineTo(300,200);
// draw two rectangles
sp.graphics.drawRect(50,50,300,250);
sp.graphics.drawRoundRect(40,40,320,270,25,25);
// circle and ellipse
sp.graphics.drawCircle(150,100,20);
sp.graphics.drawEllipse(180,150,40,70);
// draw a filled circle
sp.graphics.beginFill(0x333333);
sp.graphics.drawCircle(250,100,20);
sp.graphics.endFill();
sp.addEventListener(MouseEvent.MOUSE_DOWN, mouseisDown);
sp.buttonMode = true;
sp.useHandCursor=true;
sp.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
addChild(sp);
}// contructor
function mouseisDown(event:MouseEvent):void {
sp.startDrag();
Sprite(event.target).alpha=0.25;
}
function mouseReleased(event:MouseEvent):void {
sp.stopDrag();
Sprite(event.target).alpha=1;
}
}
}
12. Re: Flash AS3 error codeskglad Oct 6, 2007 6:35 AM (in response to easypzmaths)if that class extended MovieClip, you would have no problem. (don't forget to import the Sprite class.)
13. Re: Flash AS3 error codeseasypzmaths Oct 6, 2007 7:02 AM (in response to kglad)The only code in the fla is on the first frame...
import DrawingShapes2;
var ds:DrawingShapes2 = new DrawingShapes2();
addChild(ds);
This now works but I also need addChild(sp) in the constructor - don't know why.
Also, I am still puzzled as to why the Document Class affects it.
14. Re: Flash AS3 error codeskglad Oct 6, 2007 7:16 AM (in response to easypzmaths)you don't need any code in your fla if DrawingShapes2 is your document class.
15. Flash AS3 error codeseasypzmaths Oct 6, 2007 8:07 AM (in response to kglad)Fascinating!
I set DrawingShapes2 as the document class and removed the 3 lines of code from the fla but I still got the "Call to a possibly undefined method addFrameScript". At this point my fla had an empty actionscript frame. Once I deleted the frame the error went. When I added a new frame and typed a couple of spaces the error returned when I published it. Previously I had some commented out code which also caused the error. I looked at Mooock's Essential Actionscript Document Class description (page 828) and searched for the undocumented addFrameScript function. It seems that the cause is as follows...
"Automatically declare stage instances" creates named variables for library clips on stage that were not declared by the coder. An empty code frame (even though it's only empty space) is considered a MovieClip and gets declared automatically, and then the system tries to call the undocumented addFrameScript() on non existent code. If I extend my AS class from MovieClip rather than Sprite it probably fixes that.
kglad, Thank you for helping me along that interesting journey.
16. Re: Flash AS3 error codeskglad Oct 6, 2007 8:36 AM (in response to easypzmaths)you're welcome. and your last sentence is correct. and, i believe, if you add an extra frame to your movieclip but do not add any code/spaces to the actions panel and there's nothing on-stage in that additional frame, you can still use a sprite class as the document class.
17. Re: Flash AS3 error codesmgoodes Oct 6, 2007 9:28 AM (in response to easypzmaths)Great discussion! There was one point that was left unanswered:
"This now works but I also need addChild(sp) in the constructor - don't know why.
Also, I am still puzzled as to why the Document Class affects it."
It looks like your class DrawingShapes2 is creating a container within a container. In your first statement you have:
var sp:Sprite = new Sprite();
This creates a sprite container within DrawingShapes2 and you do all your drawing to that container. Of course sp then needs to be added to the stage by the addChild(sp) statement because at that point you've only added its parent to the stage (via your frame code).
As an experiment, if you're interested, you could try this in place of the above statement:
var sp:Sprite = this;
Then you'll have to remove the addChild(sp) statement because it is no longer a container within a container.
Or, instead, you could change your frame code from:
addChild(ds);
to:
addChild(ds.sp);
and then you would need to remove the addChild(sp) statement in your constructor.
I've found it's hard to mix frame code if you have a Document Class. There appear to be all kinds of rules and restrictions. It seems to be much easier to have no frame code or to have no Document Class and to use your frame code to instantiate your class the same way we did in older versions of AS.
If you try any of this let us know. These discussions are a great way to learn more.
18. Re: Flash AS3 error codeseasypzmaths Oct 28, 2007 8:43 AM (in response to mgoodes)Timeout!
I replaced sp:Sprite = new Sprite();
with var sp:Sprite = this;
and removed addChild(sp);
as suggested but it didn't work.
I think it's because "this" is referring to the class, not an instantiated object of the class.
This throws some light on the topic but I still haven't got it sorted...
19. Re: Flash AS3 error codeskglad Oct 28, 2007 10:03 AM (in response to easypzmaths)what's the problem? | https://forums.adobe.com/thread/125986 | CC-MAIN-2017-43 | refinedweb | 1,528 | 65.12 |
Hello! It's my very first time asking a question here, I haven't found out how to solve this problem, thank you very much!
I have this class ( in TileControl.cs )
public class Tiles{
public GameObject tileGO;
public float xPos;
public float yPos;
public bool isLight;
}
I have a 2-dimensional array called TilePosition, which is empty, so the script Levels.cs fills it. Here's an example from Levels.cs
if (levelNumber == 0)
{
rows = 3; columns = 4;
TileControl.tilePosition = new int[,] {{ 0, 1, 1, 1 },
{ 1, 1, 1, 0 },
{ 0, 1, 1, 1 }};
}
And if I call BuildMap.GenerateMap( Levels.rows, Levels.columns ) it works as you can see here:
Here is the actual problem: If all the tiles are called ''Cube'', how do I distinguish them? How could I attach the class Tiles to every Cube?
If all the cubes had xPos, yPos and isLight variables, I could easily work with them. For example, I could delete all the cubes whose xPos is 2, or color them red, etc.
( Sorry for my English or if I wasn't clear ) Thank you!
( There are 9 tiles in the picture, but 18 in the Hierarchy, because there will be dark tiles behind light tiles, but that is not important )
Answer by Cherno
·
Mar 21, 2015 at 08:49 PM
How about this:
Add a bool "filled" to your Tiles class. Then instead of a 2-dimensional int array you create a 2-dimensional tiles array and for each Tiles in it, set the filled value to true or false (what was 0 or 1 in the int array). Now you can access each cube by passing the x and y values to the Tiles array.
Thank you for your help Cherno, I'm going to try it and reply later
Great, it works, thank you, but now I've encountered another problem. The tiles are deleted whenever I try to refer to them outside of the void Generate$$anonymous$$ap.
This is my Tiles array:
TileControl.Tiles[,] tilePosition = new TileControl.Tiles[Levels.columns, Levels.rows];
I can give them xPos, yPos and state( 0 or 1 ):
for(int j=0; j<row; j++)
{
for(int i=0; i<col; i++)
{
Debug.Log(i + " " + j);
tilePosition[i, j] = new TileControl.Tiles();
tilePosition[i, j].xPos = i;
tilePosition[i, j].yPos = j;
tilePosition[i, j].state = TileControl.map[j, i];
}
}
I can test whether they are filled or not:
int empty = 0;
int filled = 0;
for(int j=0; j<row; j++)
{
for(int i=0; i<col; i++)
{
if(tilePosition[i, j].state == 1) filled++;
else empty++;
}
}
Debug.Log("Filled: " + filled + " Empty: " + empty);
Debug.Log("Lenght: " + tilePosition.Length);
This means: filled = 9; empty = 3; length = 12;
When I try to get the array's length from somewhere else, it's 0 and boom, ''Array index is out of range'' :(
Problem solved, the last reply was a week ago, so I marked your.
[SOLVED]How to use attributes from array of custom class instances?
1
Answer
Spawning GameObject from class array Javascript
2
Answers
Multiple spawn points using Array...
1
Answer
How to apply more than one trigger on a single gamebject
1
Answer
Checking if a position is occupied in 2D?
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/929476/spawning-gameobjects-with-help-of-classes-attachin.html?sort=oldest | CC-MAIN-2022-40 | refinedweb | 546 | 72.97 |
Literal syntax for Pyrsistent data structures
Project description
Pyrthon is a utility library that substitutes python collection literals with their Pyrsistent counterparts.
Instead of writing this:
from pyrsistent import pvector x = pvector([1, 2, 3]) y = x.set(0, 17)
You can simply write this:
x = [1, 2, 3] y = x.set(0, 17)
The results will be equivalent.
Examples
In foo/main.py:
# Register any modules under 'foo' for pyrsistent substitution before any # imports from 'foo' modules. # # Registration can be done in three ways: # * Exact module name. # register('foo.bar') # * Prefix with wild card. All submodules of the prefix. # register('foo.*') # * Custom matcher function that returns true if substitution should be applied in the module. # register(lambda name: name.startswith('foo') and name.endswith('baz')) from pyrthon import register register('foo.*') from foo.app import run if __name__ == '__main__': run()
In foo/app.py:
# All literal collection declarations in this module will now be mapped to # corresponding pyrsistent collections. def run(): x = [1, 2, 3] # -> pvector([1, 2, 3]) y = {'a': 1} # -> pmap({'a': 1}) z = {'a'} # -> pset(['a']) # It's not possible to declare an empty set in python using a literal. # Therefore some special treatment is required. p = set() # -> pset([]), pyrsistent pset q = set([]) # -> set(), regular python set # To declare regular python lists, dicts and sets just use the function syntax a = list([1, 2, 3]) # -> [1, 2, 3] b = dict(a=1) # -> {'a': 1} c = set(['a']) # -> set(['a']) print('Hello functional world!')
Pyrthon also has basic shell support. Just import pyrthon.console and you’re good to go:
>>> import pyrthon.console Pyrsistent data structures enabled >>> [1, 2, 3] pvector([1, 2, 3]) >>> {'a': 1} pmap({'a': 1}) >>> {'a'} pset(['a'])
It’s also possible to use pyrthon from Jupyter/IPython notebooks. For that an extension must be loaded. This can be done from the console or a cell:
% load_ext pyrthon
Installation
pip install pyrthon
How it works
Pyrthon works by Python AST manipulation and import hooks. All literal lists and list comprehensions, dicts and dict comprehensions, sets and set comprehensions in selected modules are substituted to produce the equivalent Pyrsistent data structure upon module import.
Limitations and quirks
This library is currently in experimental status.
If combined with other frameworks that manipulate the AST or performs other “magic” transformations to your code the result may not be as expected.
Usage in tests executed with pytest requires some additional work since no explicit import of the test files is ever performed. Also the assert used by pytest is heavily manipulated compared to the original assert and prevents direct substitution of literals. Normally this should not matter for the sake of testing though since a pvector compares to a list, a pmap to a dict and a pset to a set but it’s good to know.
Because substitution is performed on import Pyrthon currently requires at least two python files in any application and library. One file, in which no substitutions will take place, will have to register all modules on which transformations should be applied before those modules are imported. The file containing the main entry point for a program/library would be a good point to perform this registration.
Compatibility
Pyrthon is developed and tested on Python 2.7, 3.4 and PyPy (Python 2.7 compatible).
Contributors
Tobias Gustafsson
Todd Iverson (IPython/Jupyter support)
Contributing
If you experience problems please log them on GitHub. If you want to contribute code, please submit a pull request.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyrthon/ | CC-MAIN-2022-27 | refinedweb | 611 | 56.76 |
Previewing Server Manager 3.0 for VS Code
The InterSystems Server Manager extension for Visual Studio Code lets you define connections to your servers, list their namespaces and edit or view code there. You can also launch Portal for a server.
Server Manager 3.0 improves security by becoming a VS Code Authentication Provider. It is my entry for the November 2021 InterSystems Security Contest. Click here to visit the contest page where you may decide to vote for this entry. Please ignore the clickable "Contestant" label on this article header above, as it relates to a different contest for new DC articles. If you want to support me in that contest, simply "like" this post.
Overview
The current Server Manager 2.0 is able to store connection passwords in the native keystore of your workstation's operating system. This is a more secure alternative to you putting them as plaintext in your JSON files. However, the `getServerSpec` function in Server Manager 2.0's API allows any installed extension to obtain these stored passwords without requiring your permission.
VS Code's Authentication Provider API, introduced in version 1.54 (February 2021) is now mature enough for us to use.
Server Manager 3.0 does the following:
1. Implements an authentication provider called 'intersystems-server-credentials'.
2. Uses this authentication provider when accessing servers from its own Server Tree.
3. No longer returns passwords to callers of `getServerSpec`.
The first time you expand a server in the tree VS Code displays a modal dialog asking for your permission:
If you allow this and your server definition in intersystems.servers does not specify a `username` the next step is:
If you proceed, or if this step was skipped because your server definition includes a username, the next step is:
If you click the 'key' button after typing your password it will be saved securely in your workstation keychain, from where the 'InterSystems Server Credentials' authentication provider will be able to retrieve it after you restart VS Code.
If instead you press 'Enter' the password will be available only until you restart VS Code.
Either way, you are now signed in on the specified account.
Trusting Other Extensions
When another extension first asks to use an InterSystems Server Credentials account you must either allow this or deny it. For example, with a pre-release VSIX of the InterSystems ObjectScript extension that uses the new authentication provider you will get this after you click the edit pencil button alongside a namespace in the Server Manager tree:
Managing Signed In Accounts
You can use the menu of VS Code's Accounts icon in the activity bar to manage your signed in accounts:
The 'Manage Trusted Extensions' option lets you remove an extension from the list of those you previously granted access to this InterSystems Server Credentials account:
The 'Sign Out' option lets you sign out this account after confirmation:
When signing out an account for which you previously saved the password will get an option to delete the password, unless you have altered the `intersystemsServerManager.credentialsProvider.deletePasswordOnSignout` setting:
Feedback welcome
Please comment on this post. And if you like the new features please vote for Server Manager 3.0 in the contest. Voting closes at midnight EST on Sunday December 5th. | https://community.intersystems.com/post/previewing-server-manager-30-vs-code | CC-MAIN-2022-21 | refinedweb | 547 | 54.12 |
Build a REST API with ASP.NET Web API
Do you need to build a REST API with ASP.NET Web API? If you’re creating a new API, you should probably create it with .NET Core. But it’s not always possible to use the latest and greatest technologies. If you’re working in an existing ASP.NET 4.x app, or the organization you work for hasn’t approved the use of .NET Core yet, you may need to build an API in .NET Framework 4.x. That is what you will learn here. You’ll also learn how to access your API from another application (for machine-to-machine communication) and prevent unauthorized access to your API.
As you go, I’ll show you how to implement standard design patterns so it will be easy for other developers to understand and work with your API.
There are a couple of things you’ll need to work through this tutorial.
Let’s get started!
Create an ASP.NET Web API 2 Project
In Visual Studio…
- Go to File > New > Project…
- Select the Visual C# project category and then select ASP.NET Web Application (.NET Framework)
- Name your project
AspNetWebApiRestand click OK
- Select the Empty project template and click OK (don’t check any boxes to add core references)
Now you need to get a few NuGet packages. Use these commands in the Package Manager console to install them:
Install-Package Microsoft.AspNet.WebApi Install-Package Microsoft.Owin.Host.SystemWeb Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
If you pasted those in all at once, make sure to hit enter after the last line so the last package will be installed too.
Now right click on your project select Add > Class… and name it
Startup.cs. Copy and paste this into the new file:
using System.Web.Http; using Newtonsoft.Json.Serialization; using Owin; namespace AspNetWebApiRest { public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); app.UseWebApi(config); } } }
The code above creates an OWIN pipeline for hosting your Web API, and configures the routing.
Next add a
Controllers folder to your project. Then right click on the
Controllers folder and select Add > New Item…. On the left select Visual C# > Web > Web API. Then click on Web API Controller Class (v2.1), name it
ListItemsController.cs, and click Add.
Now you should have a controller with methods to get, post, put, and delete list items. Let’s test it.
Press F5 to launch your API. After the browser opens, add
/api/listitems to the end of the URL and hit Enter
You should see some items in the XML output. You actually want your API to use JSON, not XML, so let’s fix that.
In
Startup.cs add these lines in the
Configuration() method, right above
app.UseWebApi(config);
config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
This code removes the
XmlFormatter (which was the default output formatter), and configures the
JsonFormatter to camel-case property names and to use UTC time for dates.
Now run your project again, navigate to
/api/listitems, and verify that it spits out a JSON list now.
Create a Resource and the ASP.NET Web API Actions
Now let’s make this API actually do something useful. In this section, you’ll create a list item resource and wire up all of the controller actions so you can create, read, update, and delete items.
Go ahead and create a
Models folder in your project and add a
CustomListItem.cs class. It should look like this:
namespace AspNetWebApiRest.Models { public class CustomListItem { public int Id { get; set; } public string Text { get; set; } } }
Normally you would want to store your items in some kind of database, but since the focus of this tutorial is on building a REST API, you will just use a static list in memory to store our items.
Back in your
ListItemsController class, add a private static property to store your list items in memory. Add the private property inside the class declaration.
private static List<CustomListItem> _listItems { get; set; } = new List<CustomListItem>();
You will also need to add a using statement to the top of the controller.
using AspNetWebApiRest.Models;
Now change the first
Get() method in the controller to return this list (note the change in the return type):
public IEnumerable<CustomListItem> Get() { return _listItems; }
If you run the API again, you’ll see that
/api/listitems returns an empty list.
Let’s modify the
Post() method so you can add new items to the list.
public HttpResponseMessage Post([FromBody]CustomListItem model) { if(string.IsNullOrEmpty(model?.Text)) { return Request.CreateResponse(HttpStatusCode.BadRequest); } var maxId = 0; if (_listItems.Count > 0) { maxId = _listItems.Max(x => x.Id); } model.Id = maxId + 1; _listItems.Add(model); return Request.CreateResponse(HttpStatusCode.Created, model); }
This is what the
Post() method does:
- Returns a Bad Request response if the list item
Textproperty is missing or blank
- Calculates the next available ID
- Assigns the ID and adds the item to the list
- Returns the whole item (including the new id) in the response body, along with a Created status code
Note that for ideal security, you would create a separate EditModel that didn’t include the
Id property, and receive that as the method parameter in order to prevent any possibility of the user specifying their own ID. The code above is safe, but if another developer came along and modified it, they might accidentally introduce a vulnerability.
Now let’s test your
Post() method with Postman:
In Postman…
- Create a new request
- Change the method to POST
- Enter the URL for your API::{yourPortNumber}/api/listitems
- Click on the Body tab, select raw
- Notice the dropdown menu that appears in that row. Click on it and change it to JSON (application/json) (this will add a
Content-Typeheader with the value of
application/jsonto the request)
- Put the object your want to create into the body:
{ "text": "Test item" }
- Click Send
If you get an error, make sure your API is running. You can see the API is returning a 201 Created status code and the new object in the response body.
After you add a few items, you can make a GET request to the same URL to see your list of items. It should look something like this:
[{"id":1,"text":"Test item"},{"id":2,"text":"Test item 2"}]
Now let’s implement the method to get a specific item from the list:
public HttpResponseMessage Get(int id) { var item = _listItems.FirstOrDefault(x => x.Id == id); if (item != null) { return Request.CreateResponse(HttpStatusCode.OK, item); } return Request.CreateResponse(HttpStatusCode.NotFound); }
Here you find the item and return it with a status code of 200 (OK). If the item to was not found, the API returns a 404 (Not Found) status code.
The
Delete() method is similar:
public HttpResponseMessage Delete(int id) { var item = _listItems.FirstOrDefault(x => x.Id == id); if (item != null) { _listItems.Remove(item); return Request.CreateResponse(HttpStatusCode.OK, item); } return Request.CreateResponse(HttpStatusCode.NotFound); }
You can either return a copy of the item you deleted along with a status code of 200 (OK) to indicate that everything went well as in the example above, or you can use the status code 204 (No Content) to indicate success without returning the item.
For updates, you can use either the PUT or PATCH method. Use the PUT method if you need to replace the existing item with a new one. If you just need to update one property, you would still need to include all of the other properties as well when you update the item. Use the PATCH method if you just want to update select properties and leave all other properties of the item alone.
Some APIs just use the POST method for updates. For this example, you’ll use the PUT method. Replace the
Put() method with this code:
public HttpResponseMessage Put(int id, [FromBody]CustomListItem model) { if (string.IsNullOrEmpty(model?.Text)) { return Request.CreateResponse(HttpStatusCode.BadRequest); } var item = _listItems.FirstOrDefault(x => x.Id == id); if (item != null) { // Update *all* of the item's properties item.Text = model.Text; return Request.CreateResponse(HttpStatusCode.OK, item); } return Request.CreateResponse(HttpStatusCode.NotFound); }
The code above is similar to the other methods you have implemented. Note that if you were updating a resource that had a uniqueness constraint, you would need to make sure the update did not violate that constraint. If a conflict was detected, you would use the status code 409 (Conflict) to inform the caller that the update failed.
Secure Your RESTful ASP.NET Web API
What is the best way to secure this API if you need to access it from another program or service?
You could hard-code a username and password in the API and then pass those credentials in an authorization header, but that wouldn’t be ideal. Whenever you needed to change the credentials you would need to update the clients and the API. Also, there wouldn’t be a good way to revoke access for just one client, leaving access for other clients in place.
The OAuth 2.0 Client Credentials flow solves these problems by outsourcing the management and validation of client credentials to an authorization server.
Here’s how it works:
- The client application requests an access token from the authorization server. To get this access token, the client presents a username and password.
- When the client makes a request to your API, it sends along the access token in the authorization header.
- Your API validates the token. If the token is valid and contains the right permissions, your API allows the request to complete.
(If this is all new to you, you can learn more about OAuth here.)
You probably don’t want to build an OAuth 2.0 authorization server yourself, so for this tutorial, you will sign up for a forever-free Okta developer account (or sign in to
{yourOktaDomain} if you already have an account).
Register the Client Application for Your REST API
Once you’re signed in to Okta, register your client application.
- In the top menu, click on Applications
- Click on Add Application
- Select Service and click Next
- Enter
Postmanfor the Name and click Done
Note the Client ID and the Client Secret. This is the username and password that our client application (Postman in our case) need to send to the authorization server to request an access token. You can make note these credentials now or you can come back and get them later when you need them.
Create a Custom Scope
Now you need to set up the authorization server:
- Go to API > Authorization Servers
- Click the link for the default authorization server
- Select the Scopes tab
- Add a scope named
manage:listsand click Create (you can leave everything except for the Name field blank)
Your client application will request access to this scope.
You are all done configuring your authorization server!
Add Authentication to Your REST API
Now you will configure your API to require an access token. First, use these commands in the Package Manager console to add the NuGet packages you will need:
Install-Package Microsoft.Owin.Security.Jwt Install-Package Microsoft.IdentityModel.Protocols.OpenIdConnect
Now we need to make a few changes to
Startup.cs. First you will add some code that will contact your authorization server to get configuration information. Specifically, the API needs a public signing key so the API can validate the signature of access tokens (this makes it impossible for the bad guys to forge a valid access token).
After that, you will add the JWT Bearer Authentication middleware to the OWIN pipeline. This middleware will automatically validate any access token sent to the API and use it to create an identity with claims.
Open
Startup.cs, and add these
using statements at the top of the file:
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Jwt; using System.Threading.Tasks;
Now add this code at the top of the
Configuration() method: edit the first line to set your
authority to the Issuer URI of your authorization server. To find this, go to your Okta dashboard and navigate to API > Authorization Servers. Find the row for the default authorization server, copy the value in the Issuer URI column, and paste it into the line where you set the
authority variable. (If you’re building something for production, be sure to store this value in a configuration setting rather than hard-coding it here.)
Note that the
ValidAudience in the code above must also match the your authorization server’s audience (in this case
api://default) and the token must not be expired for the validation to succeed.
Now go to your
ListsController.cs and add an
[Authorize] attribute right above the class definition.
[Authorize] public class ListsController : ApiController {
Now your API will require a valid access token to be sent via the Authorization header of every request.
Let’s verify that access is denied if we don’t provide an access token.
Run the API. Then in Postman, send a POST request to
/api/listitems, like you did earlier. Now you should see a
401 Unauthorized status returned, and a message in the body:
{ "message": "Authorization has been denied for this request." }
Great.
Now you need an access token.
Here is how to get it in Postman:
Click on the Authorization tab of your request, select OAuth 2.0 from the TYPE drop-down list, and click Get New Access Token
Now fill in the form. Token Name can be something recognizable like
AspNetWebApiRest. Grant Type must be Client Credentials.
Access Token URL will be in this format:
https://{yourOktaDomain}/oauth2/default/v1/token. To find this in your Okta dashboard go to API > Authorization Servers, copy the Issuer URI for the authorization server that you created earlier, and append
/v1/token to the end.
To find your Client ID and Client Secret, in your Okta dashboard:
- Navigate to Applications
- Click on Postman (the client application you add earlier)
- Use the Copy to clipboard icon beside each field to copy the values and then paste them into Postman
Now fill in the last two fields left in the form. For Scope enter
manage:lists. For Client Authentication make sure Send as Basic Auth header is selected.
Now you can click Request Token. If you get an error, double check every value in the Get New Access Token form.
When you get the access token, scroll down and click Use Token. If you miss this step, you can find the token in the Available Tokens drop-down list the Postman authorization tab.
Now you’re all set. Click on Send in Postman to send the request (with the access token attached).
If you’ve done everything correctly so far, you’ll get a success message back from the API.
If you made a mistake somewhere, you’ll see that authorization has been denied, and you’ll want to cry because you have no idea where you made a mistake. Here are some things you can check:
- Does the
authorityin
Startup.csmatch the Issuer URI of your authorization server?
- Does the
ValidAudiencein
Startup.csmatch the Audience of your authorization server exactly?
- If it has been more than an hour since you requested an access token, remember to request a new access token (they are set to expire after 1 hour)
Note that in this tutorial you are running your local API over an insecure http connection. For production, you should serve your API via https so that your access token cannot be stolen in transit. If you host this API in IIS, you will also need to configure IIS to allow the PUT and DELETE verbs, which are not allowed by default.
That wasn’t too difficult, was it?
Although this setup is slightly more complicated than simply hardcoding a username and password in your API, it gives you a lot more control over how you manage access to your API. I think you’ll agree that it is a better approach.
Learn More About REST APIs and ASP.NET Web API
Interested in learning more about API access management or building secure applications with Okta? Check out our Product Documentation or any of these great resources: | https://developer.okta.com/blog/2019/03/13/build-rest-api-with-aspnet-web-api | CC-MAIN-2019-22 | refinedweb | 2,764 | 56.35 |
05 May 2011 05:55 [Source: ICIS news]
SINGAPORE (ICIS)--Purified terephthalic acid (PTA) futures on the Zhengzhou Commodity Exchange (CZCE) fell 3.2% on Thursday morning following a 5.2% plunge in cotton futures on the same platform, brokers said.
PTA futures have been tracing cotton futures due to their similar application in the textile industry, the brokers added.
The most actively traded September PTA futures contracts were priced at yuan (CNY) 9,890/tonne ($1,524/tonne), 3.2% or CNY328/tonne lower from Wednesday’s settlement price of CNY10,144/tonne.
Meanwhile, September cotton futures contracts tumbled by 5.2% or CNY1,365/tonne from Wednesday’s settlement to CNY24,820/tonne on Thursday morning, according to CZCE data.
Such large plunge was last seen on 1 April when PTA futures dropped 3.6% during the day, four days before ?xml:namespace>
“Investors are taking “sell” positions on the futures market to lock in their profits because they are worried that the Government may impose further tightening monetary policies soon,” said a PTA analyst with
Weaker PTA futures weighed heavily on the spot market, traders said.
Buying indications for Taiwan-origin PTA declined to $1,300/tonne CFR China Main Port (CMP) on Thursday morning, $25-30/tonne lower from Wednesday, according to ICIS.
($1 = CNY6.49) | http://www.icis.com/Articles/2011/05/05/9457007/china-pta-futures-fall-3.2-following-a-plunge-in-cotton.html | CC-MAIN-2014-49 | refinedweb | 220 | 55.13 |
First, the obvious.
A SQL table is a list of rows. A row is a dictionary that maps a column name to a column value. A SQL table has a defined type for a named column; Python doesn't pre-define the type of each column.
Some folks like to think of a table as a rigidly-defined class, which is partly true. It can be rigidly-defined. However, the extra meta-data doesn't help much.
Indexing
As a practical matter, most databases go beyond the minimalist definition of a relationship as a collection of rows. An index extends the structure in one of two ways.
A unique-key index transforms the SQL table into a dictionary that maps a key to a row.
class UniqueKeyTable( object ):
def __init__( self ):
self.rows = {}
def insert( self, aRow ):
self.rows[aRow.key()]= [aRow]
The non-unique key index transforms the SQL table into a dictionary that maps a key to a list of rows.
SQL OperationsSQL Operationsclass KeyedTable( object ):
def __init__( self ):
self.rows = collections.defaultdict(list)
def insert( self, aRow ):
self.rows[aRow.key()].append( aRow )
The single-table SELECT algorithm has a WHERE clause that gets broken into two parts: key filtering and everything else.
The basic SELECT looks something like this.
for k in table.rows[key]:
for r in table.rows[k]:
if other_where_clause( r ):
select_group_by( r )
That's the essential feature of a basic select -- it expresses a number of design patterns. There's a key-to-list map, a filter, and the "select-group-by" map to results.
In theory, the SELECT operation is the more general "filter" algorithm, where every row passes through the a general
where_clause_filterprocess.
The Join Algorithms
We have a number of alternative join algorithms. In some cases, we have two dictionaries with the same keys. This leads to a highly optimized query where one key locates rows on both sides of the join.
In other cases, we have a kind of nested-loops join. We find a row in one table, and use this row's attributes to locate a row in another table.
The "Which is Better?" Question
We always have two alternatives for every algorithm: the SQL version and the Python version. This is an essential issue in resolving the Object-Relational Impedance mismatch issue. We can implement our algorithm on either side: Python objects or SQL relations.
Note that there's no simple "Use SQL for this" or "Use Python for that" decision process. The two structures -- objects and relations -- are completely isomorphic. There's no specific set of features that dominate either representation.
The literal question that I got was "Should I use a complex data structure in a programming language or should I use SQL ?"
Ideally, the answer is "SQL does [X] better", leading to an easy decision. But this kind of answer doesn't exist.
The two structures are isomorphic; the correct answer is hard to determine. You want the RDBMS to filter rows and return the smallest relevant set of data to the object representation. While locating the fewest rows seems simple, a few things make even this hard to determine.
While it seems that the RDBMS can be the best way to handle join algorithms, this doesn't always work. When we're doing a join involving small tables, the RDBMS may be less effective than an in-memory dictionary. It sometimes occurs that SQL is best for filtering very large tables only.
Indeed, the only way to chose among two isomorphic representations (objects vs. relations) is to benchmark each implementation. | http://slott-softwarearchitect.blogspot.com/2009/05/data-structures-in-python-and-sql.html | CC-MAIN-2018-26 | refinedweb | 599 | 67.35 |
0
So here's my assignment: Define a class Quiz that implements the Measurable interface. A quiz has a score and a letter grade (such as B+). Use the implementation of the DataSet class in Section 9.1 to process a collection of quizzes. Display the average score and the quiz with the highest score (both letter grade and score).
I think I've almost got it, but I get a type mismatch error in the tester class on line 18: Quiz max = quizData.getMaximum();
What am I missing here? I don't understand... any help is GREATLY appreciated.
public class Quiz implements Measurable { private double score; private String grade; public Quiz(double aScore, String aGrade) { score = aScore; grade = aGrade; } @Override public double getMeasure() { return score; } public void setMeasure(double s) { score = s; } public String getGrade() { return grade; } public double getScore() { return score; } }
public class DataSet { private double sum; private Measurable maximum; private int count; public DataSet() { sum = 0; count = 0; maximum = null; } /** * Adds a data value to the data set * * @param x * a data value */ public void add(Measurable x) { sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure() < x.getMeasure()) maximum = x; count++; } /** * Gets the largest of the added data. * * @return the maximum or 0 if no data has been added */ public Measurable getMaximum() { return maximum; } public double getAverage() { if (count == 0) return 0; else return sum / count; } }
This is the tester class that was provided by the Instructor.
/** This program tests the Quiz and DataSet classes. */ public class QuizTester { public static void main(String[] args) { DataSet quizData = new DataSet(); Quiz q1 = new Quiz(89, "B+"); Quiz q2 = new Quiz(90, "A-"); Quiz q3 = new Quiz(73, "C"); quizData.add(q1); quizData.add(q2); quizData.add(q3); double avg = quizData.getAverage(); Quiz max = quizData.getMaximum(); System.out.println("Average score: " + avg); System.out.println("Expected: 84"); System.out.println("Highest score: " + max.getScore()); System.out.println("Expected: 90"); System.out.println("Highest grade: " + max.getGrade()); System.out.println("Expected: A-"); } } | https://www.daniweb.com/programming/software-development/threads/357829/need-help-creating-a-quiz-class-implementing-measurable-and-using-dataset | CC-MAIN-2018-05 | refinedweb | 332 | 58.18 |
- 자습서
- 2D Roguelike tutorial
- Adding UI & Level Transitions
Adding UI & Level Transitions 12 of 14 of the 2D Roguelike tutorial in which we create the UI and add code to the GameManager script to manage the level changes.
Adding UI & Level Transitions:04
In this video we're going to add some
- 00:04 - 00:07
user interface elements to our game
- 00:07 - 00:11
including title cards for when we start and change levels
- 00:11 - 00:14
and some text to reflect player's score.
- 00:15 - 00:18
To do this we're going to use Unity's UI system.
- 00:19 - 00:24
We're going to go to Game Object - UI - Canvas.
- 00:27 - 00:29
The canvas is going to hold all of our
- 00:29 - 00:31
user interface elements.
- 00:33 - 00:35
The first element that we're going to create is
- 00:35 - 00:37
going to be an image which we're going to use
- 00:37 - 00:39
as a background for our title cards.
- 00:40 - 00:43
Let's go to Game Object - UI - Image.
- 00:46 - 00:48
Notice that it's created as a child of the canvas
- 00:49 - 00:51
and the first thing that we're going to do
- 00:51 - 00:53
is switch over to our scene view and zoom out.
- 00:56 - 00:58
And we're going to use the anchor presets here
- 00:58 - 01:02
to stretch this to fit by option-clicking.
- 01:07 - 01:09
We're also going to set the colour to black.
- 01:15 - 01:18
We'll call this Level Image.
- 01:21 - 01:23
Next we're going to create a text object
- 01:23 - 01:25
that is going to display what level
- 01:25 - 01:27
the player is currently on
- 01:27 - 01:29
as we start and change levels.
- 01:30 - 01:32
Let's highlight our level image
- 01:32 - 01:37
Game Object - UI - Text.
- 01:37 - 01:38
We'll call this Level Text.
- 01:38 - 01:40
The first thing that we're going to do is anchor it to
- 01:40 - 01:43
the centre of the screen, we'll click on our anchor presets
- 01:44 - 01:47
and option or alt click the centre preset.
- 01:50 - 01:52
Next we'll set the colour of our text
- 01:52 - 01:54
to white by clicking on Colour
- 01:55 - 01:57
and then dragging it to white.
- 01:58 - 02:01
We'll set out font size to 32.
- 02:02 - 02:06
Notice that went we do this the text disappears.
- 02:06 - 02:08
That's because the text has become too
- 02:08 - 02:10
big to fit within the width and
- 02:10 - 02:12
hight dimensions specified in the rect transform.
- 02:13 - 02:15
Because we're going to have text that's going to vary
- 02:15 - 02:19
in size displaying both our level number and our game over message
- 02:19 - 02:21
we're going to use the horizontal and vertical
- 02:21 - 02:24
overflows to allow the text to overflow.
- 02:24 - 02:28
We're going to set horizontal overflow to overflow
- 02:28 - 02:31
and vertical overflow to overflow as well.
- 02:31 - 02:35
Now our text reappears, we're also going to centre
- 02:35 - 02:37
and middle align it.
- 02:40 - 02:43
Let's set the font by clicking on the asset picker.
- 02:44 - 02:46
And selecting Press Start
- 02:46 - 02:47
to play a regular.
- 02:47 - 02:49
This font ships with the project.
- 02:52 - 02:55
Finally we'll set our text default, which is going to be Day 1.
- 02:56 - 02:58
And so that should be good for the level text.
- 02:58 - 03:01
We're going to make a it child of our level image
- 03:01 - 03:03
so that when we deactivate the image
- 03:03 - 03:05
the level text will be deactivated as well.
- 03:08 - 03:11
Next we're going to create our food text display.
- 03:13 - 03:15
Highlight the canvas,
- 03:15 - 03:18
choose Game Object - UI - text.
- 03:18 - 03:20
This text we're going to align to the bottom
- 03:20 - 03:22
of the screen in the centre.
- 03:23 - 03:25
Let's click on our anchor presets
- 03:25 - 03:28
and click the bottom centre preset
- 03:28 - 03:30
while holding down the option or alt keys.
- 03:35 - 03:37
Again we'll set the colour to white.
- 03:37 - 03:40
Click Colour, drag to white.
- 03:42 - 03:44
We're going to set the size to 24.
- 03:49 - 03:51
Centre and middle align
- 03:52 - 03:55
and we'll set our text to Food 100.
- 04:01 - 04:03
We'll set our font
- 04:04 - 04:06
to PressStart2P-Regular
- 04:07 - 04:09
Notice again that the text is being cut off.
- 04:10 - 04:12
We'll set our horizontal
- 04:12 - 04:15
and vertical overflows to Overflow.
- 04:16 - 04:19
Let's label our text FoodText
- 04:19 - 04:21
and what we can see here is that the food text
- 04:21 - 04:25
is being displayed in front of our title card image.
- 04:26 - 04:27
We don't want this to happen so what we're going to do
- 04:27 - 04:30
is move FoodText up in the hierarchy
- 04:30 - 04:32
so it's directly under the canvas.
- 04:32 - 04:35
This means the it will be rendered behind
- 04:35 - 04:38
the LevelImage and it's child LevelText.
- 04:38 - 04:40
The last thing that we want to do is
- 04:41 - 04:43
let's temporarily deactivate the LevelImage
- 04:44 - 04:46
and we're going to move our FoodText up
- 04:46 - 04:47
just a little bit from the bottom.
- 04:47 - 04:50
We're going to do this by setting the anchors.
- 04:50 - 04:54
We're going to set the Y anchor to 0.05.
- 04:55 - 04:57
We can see that it moves in the UI
- 04:57 - 05:01
and we're going to set the Max to 0.05 as well.
- 05:01 - 05:04
Notice that the text hasn't moved when we've done this.
- 05:04 - 05:09
But a -13 pixel offset has been incurred in the rect transform.
- 05:09 - 05:12
Let's now set the position Y to 0
- 05:12 - 05:14
and we'll see our text move up.
- 05:16 - 05:18
Let's reactivate our LevelImage
- 05:18 - 05:20
and then we can get in to some scripting
- 05:20 - 05:22
to control these UI elements.
- 05:28 - 05:30
Let's go to our Scripts folder
- 05:31 - 05:33
and open our Game Manager in Monodevelop.
- 05:35 - 05:37
Next we're going to add the code that we need
- 05:37 - 05:39
to our Game MAnager to manage our UI
- 05:39 - 05:42
and also to handle transitions between levels.
- 05:42 - 05:45
Let's reset our private integer level to 1
- 05:45 - 05:47
so that we start on level 1 now.
- 05:47 - 05:50
The first thing that we're going to add to our Game Manager script
- 05:50 - 05:53
is the namespace declaration using UnityEngine.UI.
- 05:53 - 05:56
Next we're going to add a public float
- 05:56 - 05:58
variable called levelStartDelay.
- 05:58 - 06:00
This is going to be the time to wait before
- 06:00 - 06:03
starting levels, in seconds.
- 06:03 - 06:05
Next we're going to add a private variable
- 06:05 - 06:08
of the type Text called levelText.
- 06:08 - 06:11
This is going to be the text that is going to display
- 06:11 - 06:14
the current level number which we've currently got set
- 06:14 - 06:16
to day 1 in the editor.
- 06:16 - 06:18
We're also going to declare a private variable
- 06:18 - 06:21
of the type GameObject called levelImage.
- 06:22 - 06:25
We're going to use this to store a reference to our level image
- 06:25 - 06:27
so that we can activate it and deactivate it
- 06:27 - 06:29
as we want to show and hide it.
- 06:29 - 06:31
We're also going to add a private boolean
- 06:31 - 06:35
called doingSetup which we're going to use to
- 06:35 - 06:37
check if we're setting up the board and prevent
- 06:37 - 06:39
the player from moving during setup.
- 06:39 - 06:41
After awake we're going to add
- 06:41 - 06:44
a new private function that returns void
- 06:44 - 06:47
called OnLevelWasLoaded which takes an integer
- 06:47 - 06:49
parameter called index.
- 06:49 - 06:52
OnLevelWasLoaded is part of the Unity API
- 06:53 - 06:56
and it's called every time a scene is loaded.
- 06:56 - 06:59
We're going to use this to add to our level number
- 06:59 - 07:01
and to call our InitGame function
- 07:01 - 07:03
after a new level has been loaded.
- 07:04 - 07:06
We're going to use InitGame to manage
- 07:06 - 07:09
our UI elements and setup each level.
- 07:10 - 07:12
We're going to start by setting our doingSetup boolean to true.
- 07:13 - 07:15
This means the player won't be able to move while
- 07:15 - 07:17
the title card is up.
- 07:17 - 07:19
Next we're going to get a reference
- 07:19 - 07:21
to our LevelImage object
- 07:21 - 07:23
using GameObject.Find.
- 07:23 - 07:25
Here we're finding by name so you want
- 07:25 - 07:27
to make sure that your game object name
- 07:27 - 07:29
in the editor matches the string that we're using
- 07:29 - 07:31
with GameObject.Find.
- 07:31 - 07:33
We're going to do the same thing for our LevelText
- 07:33 - 07:35
but we're also going to get a component reference
- 07:35 - 07:37
to the text component.
- 07:37 - 07:39
Next we're going to set the text of
- 07:39 - 07:41
our LevelText to our current level number.
- 07:42 - 07:44
The text that we're setting is going to be a string so
- 07:44 - 07:46
we're going to provide Day with a
- 07:46 - 07:48
space and then we're going to append
- 07:49 - 07:52
our level integer at the end,
- 07:52 - 07:55
so in this case it'll read 'Day 1'.
- 07:56 - 07:58
We're going to activate our LevelImage
- 07:58 - 08:01
game object using SetActive.
- 08:01 - 08:03
Next we're going to declare a private function
- 08:03 - 08:06
that returns void called HideLevelImage.
- 08:07 - 08:09
We're going to use this to turn off our LevelImage
- 08:09 - 08:11
when we're ready to start the level and we're going to
- 08:11 - 08:13
invoke it from within InitGame.
- 08:14 - 08:16
Inside HideLevelImage we're going to turn off
- 08:16 - 08:18
our LevelImage.
- 08:18 - 08:21
And we're also going to set DoingSetup
- 08:21 - 08:23
to false so that the player can now move.
- 08:23 - 08:25
Back in InitGame we're going to
- 08:25 - 08:27
invoke HideLevelImage
- 08:28 - 08:31
parsing in LevelStartDelay as our delay time.
- 08:32 - 08:35
This means that once we've displayed our title card
- 08:35 - 08:38
we're going to wait 2 seconds before turning it off.
- 08:38 - 08:40
In update we're going to add a
- 08:40 - 08:44
check for DoingSetup to our If statement.
- 08:44 - 08:46
This is what's going to prevent the player from moving
- 08:46 - 08:48
if DoingSetup is true.
- 08:49 - 08:52
In GameOver we're going to show a message to the player
- 08:52 - 08:54
saying how many days they've survived for.
- 08:54 - 08:56
The message is going to read
- 08:56 - 09:00
'After level number of days you starved'.
- 09:01 - 09:04
We're also going to enable our black background.
- 09:07 - 09:10
Lets save our script and return to the editor.
- 09:12 - 09:14
The next thing that we need to do is add a few
- 09:14 - 09:16
lines of code to our Player
- 09:16 - 09:19
so that our player can update the FoodText
- 09:19 - 09:20
as the value changes.
- 09:20 - 09:22
Let's open our Player in Monodevelop
- 09:23 - 09:26
In Player we're also going to add the namespace
- 09:26 - 09:29
declaration using UnityEngine.UI.
- 09:29 - 09:32
Next we're going to add a public variable
- 09:32 - 09:34
of the type Text called foodText.
- 09:35 - 09:37
In start we're going to set the value
- 09:37 - 09:40
of foodText to the current Food score.
- 09:41 - 09:43
In AttemptMove we're going to do the same thing
- 09:43 - 09:47
after we've subtracted from the player's food points score.
- 09:47 - 09:49
We're also going to display a message
- 09:49 - 09:52
when the player picks up a food object
- 09:52 - 09:54
or a soda object.
- 10:00 - 10:03
So when the player picks up a food object
- 10:03 - 10:06
we're going to display + pointsPerFood
- 10:07 - 10:09
along with their current food points.
- 10:09 - 10:11
We're going to do the same thing for soda.
- 10:12 - 10:14
In loseFood we're going to display a similar
- 10:14 - 10:16
message showing how many food points
- 10:16 - 10:19
the player lost when they were attacked.
- 10:23 - 10:26
Let's save our script and return to the editor.
- 10:29 - 10:31
In the editor we need to assign a reference
- 10:31 - 10:33
to our FoodText object to our player.
- 10:35 - 10:37
Let's choose Player
- 10:37 - 10:39
and then we're going to drag in FoodText
- 10:41 - 10:43
to our FoodText variable slot.
- 10:45 - 10:47
Let's play our scene and give it a try.
- 10:48 - 10:50
So we see our title card displays, that's working.
- 10:51 - 10:53
When we move our Food text updates.
- 10:56 - 10:59
We get our delay before moving to a new level.
- 10:59 - 11:01
Title card displays with the updated level number.
- 11:01 - 11:03
When we're attacked by our enemy
- 11:03 - 11:05
we see our -10 message.
- 11:06 - 11:08
And so it looks like everything is working.
- 11:09 - 11:12
Now that we've got our UI elements working
- 11:12 - 11:14
In the next video we're going to add
- 11:14 - 11:17
some sound effects and music
- 11:17 - 11:19
along with the scripts that we need to control them.
Please note that this lesson has been updated to reflect changes to Unity's API. Please refer to the upgrade guide PDF in your asset package download or available directly here.
GameManager
Code snippet
using UnityEngine; using System.Collections; using System.Collections.Generic; //Allows us to use Lists. using UnityEngine.UI; //Allows us to use UI. public class GameManager : MonoBehaviour { public float levelStartDelay = 2f; //Time to wait before starting level, in seconds. public float turnDelay = 0.1f; //Delay between each Player turn. public int playerFoodPoints = 100; //Starting value for Player food points. public static GameManager instance = null; //Static instance of GameManager which allows it to be accessed by any other script. [HideInInspector] public bool playersTurn = true; //Boolean to check if it's players turn, hidden in inspector but public. private Text levelText; //Text to display current level number. private GameObject levelImage; //Image to block out level as levels are being set up, background for levelText. private BoardManager boardScript; //Store a reference to our BoardManager which will set up the level. private int level = 1; //Current level number, expressed in game as "Day 1". private List<Enemy> enemies; //List of all Enemy units, used to issue them move commands. private bool enemiesMoving; //Boolean to check if enemies are moving. private bool doingSetup = true; //Boolean to check if we're setting up board, prevent Player from moving during setup. /); //Assign enemies to a new List of Enemy objects. enemies = new List<Enemy>(); //Get a component reference to the attached BoardManager script boardScript = GetComponent<BoardManager>(); //Call the InitGame function to initialize the first level InitGame(); } //This is called each time a scene is loaded. void OnLevelWasLoaded(int index) { //Add one to our level number. level++; //Call InitGame to initialize our level. InitGame(); } //Initializes the game for each level. void InitGame() { //While doingSetup is true the player can't move, prevent player from moving while title card is up. doingSetup = true; //Get a reference to our image LevelImage by finding it by name. levelImage = GameObject.Find("LevelImage"); //Get a reference to our text LevelText's text component by finding it by name and calling GetComponent. levelText = GameObject.Find("LevelText").GetComponent<Text>(); //Set the text of levelText to the string "Day" and append the current level number. levelText.text = "Day " + level; //Set levelImage to active blocking player's view of the game board during setup. levelImage.SetActive(true); //Call the HideLevelImage function with a delay in seconds of levelStartDelay. Invoke("HideLevelImage", levelStartDelay); //Clear any Enemy objects in our List to prepare for next level. enemies.Clear(); //Call the SetupScene function of the BoardManager script, pass it current level number. boardScript.SetupScene(level); } //Hides black image used between levels void HideLevelImage() { //Disable the levelImage gameObject. levelImage.SetActive(false); //Set doingSetup to false allowing player to move again. doingSetup = false; } //Update is called every frame. void Update() { //Check that playersTurn or enemiesMoving or doingSetup are not currently true. if(playersTurn || enemiesMoving || doingSetup) //If any of these are true, return and do not start MoveEnemies. return; //Start moving enemies. StartCoroutine (MoveEnemies ()); } //Call this to add the passed in Enemy to the List of Enemy objects. public void AddEnemyToList(Enemy script) { //Add Enemy to List enemies. enemies.Add(script); } //GameOver is called when the player reaches 0 food points public void GameOver() { //Set levelText to display number of levels passed and game over message levelText.text = "After " + level + " days, you starved."; //Enable black background image gameObject. levelImage.SetActive(true); //Disable this GameManager. enabled = false; } //Coroutine to move enemies in sequence. IEnumerator MoveEnemies() { //While enemiesMoving is true player is unable to move. enemiesMoving = true; //Wait for turnDelay seconds, defaults to .1 (100 ms). yield return new WaitForSeconds(turnDelay); //If there are no enemies spawned (IE in first level): if (enemies.Count == 0) { //Wait for turnDelay seconds between moves, replaces delay caused by enemies moving when there are none. yield return new WaitForSeconds(turnDelay); } //Loop through List of Enemy objects. for (int i = 0; i < enemies.Count; i++) { //Call the MoveEnemy function of Enemy at index i in the enemies List. enemies[i].MoveEnemy (); //Wait for Enemy's moveTime before moving next Enemy, yield return new WaitForSeconds(enemies[i].moveTime); } //Once Enemies are done moving, set playersTurn to true so player can move. playersTurn = true; //Enemies are done moving, set enemiesMoving to false. enemiesMoving = false; } }
관련 자습서
- The new UI (강좌)
- UI Text (강좌) | https://unity3d.com/kr/learn/tutorials/projects/2d-roguelike-tutorial/adding-ui-level-transitions | CC-MAIN-2019-35 | refinedweb | 3,395 | 70.94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.