Oppdatering: Jeg har skrevet en engelsk versjon av dette som er mer gjennomtenkt. I have written an English version of this post which I have had more time to think through.
Det var meningen f rst ha dette som en kladd, for senere g igjennom og skrive mer, men WordPress krangler og jeg orker ikke finne ut av det. Derfor publiserer jeg dette n . Jeg har lenge nsket sette opp en ny bloggmotor men har aldri kommet meg til gj re det og dette er definitivt ikke tidspunktet, s jeg gjenoppliver min gamle, engelskspr klige blogg.
Andre har skrevet sine fortellinger om hva som skjedde p Ut ya. Jeg ville gjerne skrive ned min ogs , f den ut. Jeg vil dels skrive det ned fordi jeg ikke vet om jeg vil huske alle disse detaljene senere. P en m te h per jeg ikke det. Dels ogs for at jeg skal slippe m tte beskrive dette hele tiden for alle som sp r.
Gro Harlem Brundtland hadde nylig forlatt leiren. Jeg hadde tatt opp en videohilsen fra henne, og var i kontoret til mediegruppen for redigere filen til noe vi kunne laste opp p YouTube. En av de som var i rommet skvatt til og fortalte at Twitter var fullt av meldinger om en eksplosjon i Oslo. Etterhvert som pressen kunne fortelle om hvor angrepet hadde skjedd, ble det mer og mer tydelig at et informasjonsm te var p sin plass. Det ble enighet om at det m tet skulle avholdes etter at bolken med innledninger var ferdig.
Informasjonsm tet ble avholdt, og jeg tok p meg som den lokale nerd-in-chief sette opp en laptop som kunne vise NRK Nett-TV s folk kunne f sett hva som skjedde. Det tr dl se nettverket gikk nesten umiddelbart ned, s vi ble enige om at det skulle settes et passord p det. I p vente av at noen andre gjorde det, gikk jeg p do.
Idet jeg satt der, h rte jeg f rst agitert roping, s skriking, s skudd. Det h rtes mer ut som en lekepistol enn noe annet og jeg antok at dette bare var en eller annen som kom med en totalt smakl s vits. Med dette i tankene, kom jeg n rmest stormende ut av b sen men idet jeg vrengte opp d ren s jeg to mennesker som signaliserte at jeg skulle komme meg inn igjen. Ansiktsuttrykkene deres levnet overhodet ingen tvil om at dette var alvor. At de var der reddet utvilsomt livet mitt. Jeg var mest av alt forvirret. Jeg antok der og da det var en AUFer som hadde gjort dette, g tt amok. Jeg tittet ut igjen. De to var der fremdeles. Denne gangen s jeg en person som l der p gulvet, i en blodp l. Jeg hadde yekontakt med ham, og han signaliserte tydelig etter hjelp.
Jeg tenkte umiddelbart at de d rene ikke ville st imot noen som helst type kuler, s jeg tenkte kun p forflytte meg vekk fra b sen. Min f rste tanke var komme meg utend rs. Jeg l p ut korridoren, og akkurat da kom en fra kaf gjengen mot meg. Hun pnet ansatt-toalettet, og jeg, hun, og en annen kastet seg inn. Det er bare en av de mange tilfeldighetene som jeg i etterkant m innse at jeg antar reddet livet mitt.
Vi satt der, i halvannen time. Klare til l pe, klare for egentlig hva som helst. Det ble til en eiendommelig dynamikk mellom oss tre, en slags perpleks galgenhumor. Jeg, ettersom det var helt realistisk at v r gruppe var den eneste som visste om likene i bygget, pr vde umiddelbart f varslet om det. 112 fungerte ikke. 110 fungerte ikke. Til slutt kom jeg igjennom p 113, og de kunne opplyse om at politiet var klar over situasjonen og var p vei. Det skulle ta halvannen time, og da vi ble evakuert l han der d d.
Det ekte politiet ankom omsider. Vi gikk ut. Jeg tok veien rundt lillesalen, noe jeg i etterkant angrer p ; det jeg s der vil nok bli med meg en stund. Det l en haug med folk jeg husker ingen ansikter, bare et stort, amorft sammensurium av kropper i en fryktelig stor blodp l noen av dem, jeg mener huske to, var fremdeles bevisste. Vi ble f rst flyttet til Planet Ut ya-kontoret leiravisa hvor det var en jente som hadde blitt skutt. Vi rev opp noen poser med gensere fra lageret og dekket til henne. Der satt vi en stund jeg hadde forlengst mistet tidsbegrepet jeg mener det m ha v rt tolv av oss.
En av ungdommene ble trass i protester fra de i gruppa som kjente og gikk god for ham p f rt h ndjern. Jeg forstod ikke helt hvorfor. Senere ble vi forklart at det var fordi han hadde kommet fra et omr de politiet ikke hadde oversikt over. Jeg s ikke n r de h ndjernene ble l snet, men jeg husker ihvertfall at det slo meg som uverdig behandling. Politimannen som hadde vakt p posten der vi var, var veldig dyktig til forklare oss situasjonen. Vi ble flyttet ut til hovedkorridoren, hvor omkring 50 av oss var. F rst idet jeg s og omfavnet de som antakeligvis reddet livet mitt, knakk jeg sammen i gr t. Jeg tok meg fort inn igjen, fikk skjelvingen under kontroll, og etter en del venting ble vi marsjert med hendene p hodet mot fergen. Jeg husker hvor redd jeg var for at noen skulle gli i den bratte, gj rmete bakken og skape en misforst else. Det var flere lik ute. Noen var tildekket p improvisert vis, andre l der bare.
Alle jeg s viste mot, ro og beherskelse p et niv langt over det noen nsker forvente fra folk i de aldersgruppene. Det var et samhold og en m lbevissthet som gjorde et inntrykk.
Vel over fjorden ble vi tilbudt tepper. Jeg ble spurt om jeg var skadet, og bedt om vise mageregionen. Vi ble loset ombord i bussen, og kj rt til Sundvolden hotell. F lelsen, den totalt utrolige lettelsen av se sine n rmeste venner igjen kan jeg virkelig ikke beskrive. Lettelsen ble temperert av usikkerheten rundt de man ikke s . Det dreier seg blant annet om mennesker som jeg i skrivende stund m anta har mistet livet. Blant dem mennesker jeg tidligere hadde hatt stor glede av vissheten om at kom til gj re fantastiske ting i landets og verdens tjeneste n er de revet vekk.
Jeg vet ikke hvor mye mer enn denne litt n kterne rapport av hendelsene jeg klarer komme med akkurat n . Men slik var det ihvertfall jeg opplevde situasjonen jeg kom ut av takket v re en serie tilfeldigheter. Litt kort vil jeg legge til:
Redningstjenestene var en stor hjelp. Vel s stor, om ikke st rre, har muligheten til tilbringe tid sammen med de andre overlevende v rt. Vi holder sammen og tr ster hverandre med v r felles erfaring.
Ett lyspunkt ser jeg her: Mest av alt er jeg s utrolig glad for at han ikke var fremme tyve minutter tidligere, under informasjonsm tet. Da var hele Ut ya samlet som sild i t nne i hovedsalen, og med hans automatv pen ville d dstallene i l pet av noen titalls sekunder blitt det mangedobbelte av det vi endte opp med. At det er en veldig mager tr st for de etterlatte er jeg inderlig klar over. Mine aller dypeste tanker er med dem alle.
Dette var et angrep p hele det norske demokratiet. I forvirrelsen f ler jeg en bitter trass. Vi skal vise hans likesinnede at det er sterkere enn som s . Jeg vil ikke la meg skremme til taushet og passivitet. Jeg nsker minnes de d de, og deretter hedre dem ved fortsette arbeidet de var en del av.
Our adventurous friends Eric and Katie had invited us to join them on a hike in
the Grand Canyon over the 4th of July weekend. As this struck us as something
we'd never have considered doing otherwise, we thought we'd accept their kind
offer. We're so glad we did.
It was quite a bit of traveling just to get there. We flew out of San Jose on
Thursday night, got into Las Vegas, rented a car, and then drove to Peach
Springs, Arizona, where we stayed the night. We didn't get in at the Grand Canyon Caverns Inn until
around midnight, and we had to get up again for a 5:00am departure (I think we
actually got away by more like 5:30am), to drive to the Hualapai Hilltop, where
the trail head was. Zoe handled all of this very well. She didn't end up falling
asleep in the car until about 10:30pm I think, and dealt with the transfer out
of the car at midnight very well and went back to sleep.
The drive to the Hualapai Hilltop, along Indian Road 18, took about an hour. We
had to dodge a bit of livestock on the road. The road itself was sealed and of
good quality. We remarked on the way back out that as soon as you left the
Havasupai Reservation and entered the Hualapai Reservation that there was a
distinct degradation in the quality of the road.
We parked at the Hilltop, and got ourselves organised, and commenced our
descent by about 7:10am.
The first 1.5 miles was very steep. There were a bunch of switchbacks and there
was a fair few people coming up the other way already. There were also a few
mule trains coming in the opposite direction that we had to dodge. The mule
trains have right of way, so we had to stop and get out of the way to let them
pass. Zoe thought they were pretty cool because they invariably had a few dogs
with them as well, and she thinks dogs are awesome.
The remaining 6.5 miles (it was an 8 mile/13 kilometre hike in total) were
fairly easy. There was a lot of variety in terrain. Rocks, sand, dirt. It
wasn't all in the sun, which was made it more comfortable. Heat wise, I think
it was in the high 30's Celsius, with pretty much no humidity, so it didn't
feel too uncomfortable.
Towards the end, as we got near the water, there was a distinct change in the
canyon. There was more greenery, and we started hearing insects and seeing bird
life. When we first saw the water, it was hard not to just jump in, it looked
so inviting.
The total hiking time was about 4 hours 45 minutes, which included a reasonable
stop to give Zoe some breakfast. We arrived in the village at around midday.
Unfortunately the lodge wasn't ready for check ins until 1pm, so we had to
twiddle our thumbs for a little bit.
Zoe handled the hike incredibly well. We used a Macpac
Possum child carrier that Nigel
had passed down to us, and she didn't complain the whole time. She even
took a nap in it. We were very relieved that it wasn't a problem for her.
Sarah carried her, and I carried
everything else. (I'm so glad I didn't see the photo of how I looked until
well afterwards). In hindsight we probably brought too much stuff, but we
didn't really know what to expect down there, so we'd rather have too much than
too little.
The village completely exceeded my expectations. I had this (silly) mental
picture of it being just the lodge and not much else, but somewhere between 450
and 700 people live in the village. It had two general-type stores, a cafe that
was pretty much like a fast food/takeaway place, an elementary school, and some
sort of basic medical clinic. There was also a small general purpose community
centre of some sort. The main store had pretty much everything you'd need in
the food department. The cafe frequently ran out of various different things,
but you weren't going to go hungry.
For the remainder of Friday, we just stayed put in the village and let Zoe
stretch her legs. Eric and Katie and their kids explored the first set of falls
down from the village, unofficially named Rock Falls.
On Saturday, we all hiked down to Havasu Falls. We met a
couple of other families (amusingly both from the Bay Area) along the way, so
we had some interesting conversations. I have no idea how long the hike was.
Havasu Falls was impressive. Quite tall and narrow at the top, and quite loud.
Zoe was impressed. We took her for a bit of a swim in the pools in the bottom.
We had lunch there, and then Zoe and Sarah stayed there (Zoe took a nap in the
KinderKot (also courtesy of Nigel)
in the shade by the falls, and I took the Macpac with a water bladder in it to
refill it at the spring in the campground, which was further down stream, and
to check out Mooney
Falls with Eric and Katie (and their kids), which was further downstream
again from the campground.
Mooney Falls was pretty insane. A lot taller than Havasu Falls, and a lot more
treacherous to get to the bottom of. Parts of it were vertical. Chains and
rickety ladders were involved. Caves were involved. I'm so glad I didn't have
Zoe in the Macpac, because on multiple occasions, the top of it got bashed
into rocks, so without having Sarah with me also to act as a guide, there's no
way I could have safely descended with Zoe in the backpack. My favourite photo
illustrating how crazy this was is this
one that I took of Eric and Katie. This
photo highlights some of the craziness involved to get down.
I pretty much got to the bottom, had a quick look around and left Eric and
Katie to it, because I figured Zoe would have woken up by now, and was probably
bored. Turned out I had all of the sunscreen with me as well. So I climbed back
up, and trekked back to the campground, refilled at the spring, and headed back
up to Havasu Falls.
After we reunited, we then hiked back up to the village, which to be honest,
was the hardest bit of hiking we did. I was carrying Zoe in the Macpac, and it
was hot, and it was mostly loose sand all the way. We were very glad to get
back to the village.
Zoe started showing signs of coming down with a cold and a cough, so we decided
to cut short our stay in the village and leave on Sunday instead of Monday.
We'd been tossing up between getting a helicopter or horses out. We ended up
opting for the helicopter after learning that the horses still took about 3.5
hours, and you basically had no control over the animal. We were dubious as to
how Zoe would go being bounced around on the back of a horse for that long. The
helicopter ride also took all of about 5 minutes.
The tribal members get first dibs on the helicopter, and there had been a death
in the village, and I think a lot of people had come to the village for the
viewing (the casket itself was flown out earlier on Sunday morning for a burial
out of the village), so I suspect there was a higher number of tribal
passengers than usual. We didn't get out until 2pm. Again, Zoe was incredibly
good. She just hung out with us while we waiting for a flight out. There were
plenty of dogs for her to be entertained by, and some other kids. She also took
a pretty decent nap.
So we finally got out, and got back to our car, and then the heavens opened. It
absolutely poured down with rain. Sarah was keen to check out Hoover Dam, so we
decided to stay near Boulder City in Nevada, and got a suite in the Hacienda Hotel and Casino
for cheap.
The next day was the Monday public holiday for Independence Day, and we were
tossing up whether or not to take Zoe to a doctor to get her checked to see if
she had bronchitis (we've been a bit gun-shy about bronchitis since the time
she came down with it when we were in Australia). She ended up falling asleep
in the car while we were hunting around for an Urgent Care facility that was
open, so we decided to let her sleep and drove to Las Vegas.
After she woke up, we took her to see the flamingos at Flamingo
and the lions at MGM Grand. Zoe
absolutely loved all the lights, sights and sounds of Las Vegas.
In the afternoon, we took her to a doctor, and got the "first child, huh?" from
the doctor (she didn't have bronchitis).
After that, we went and briefly checked out Hoover Dam (just walked half
way across the bridge in front of it and walked across the dam itself).
The following day, we packed up and spent the morning on the Las Vegas strip
again. This time we went to the Venetian
(Zoe thought the gondolas were pretty cool) and then we flew out in the
afternoon.
So it was a lovely little family vacation. We ended up spending about as much
time in Las Vegas as we did in the Grand Canyon, but that was okay. I'd really
like to go back to Supai again, but I'm not sure if the stars will align
themselves appropriately. If we did, knowing what I know now, I'd take a lot
less food and put all of the luggage on a horse, and just hike in with the
minimum of stuff. I'd probably be game to hike out as well if the bulk of the
luggage was on a horse.
Photos from the trip are here.
/dev/videoX to the network, and done.
Example:
# Streaming:
cvlc v4l2:///dev/video0 --no-audio --sout "#transcode vcodec=mp2v,vb=3072 :std access=udp,mux=ts,dst=224.0.0.1 "
# Playing, possibly on a remote machine:
vlc udp://@224.0.0.1:1234
Notes:
v4l2 vs. v4l depending on the distribution (sid vs. squeeze).v4l[2]:// part, one for the
device (/dev/video0).uvcvideo module, getting No space left on
device when the second (c)vlc is started.--resolution to request a specific
resolution (the device will fall back to another resolution if the
requested one is unavailable); --frames to specify the number of
frames to capture (lower noise, but possibly higher blurriness).threading module. To
avoid encountering the same bandwidth issue, a tiny lock ensures a
single fswebcam instance runs at a time.videoX-timestamp.jpg and to log rotate them after a while, for
further viewing/reviewing during a given time window.# Only keep a rectangle of width W, height H, starting at the point (X,Y):
convert -crop WxH+X+Y capture.jpg capture.jpg
# Include a timestamp on the top-left corner:
convert -box white -font Fixed -draw "text 2,12 \"$timestamp\"" capture.jpg capture.jpg
videoX-current.jpg symlink for each /dev/videoX
device is trivial.
Sanjog Misra, who
uses Rcpp for
Monte Carlo Markov Chain (MCMC) analyses in quantitative marketing, kindly set me a
short example of Rcpp use.
The example is based on a
blog post by Darren Wilkinson
which itself discusses and compares the suitability of R, Python, Java or C for MCMC analysis, using the
Gibbs sampler as a concrete example. Darren's post is worth checking out: he
stresses the rather pragmatic aspects of how fast and/or easy it is to write the code, rather than just the mere runtime. As such,
he is not too concerned with a speed advantage of Python over R which he sees at a factor of around 2.4, leaving him to continue to prototype in
R. Similarly, with C 'only' being faster than Java by a factor of two, he prefers Java for the numerically more demanding parts.
We do of course advocate the use of Rcpp to combine the best aspects of R and C++,
respectively. This Gibbs sampler example provides a nice backdrop. So working with Darren's example, consider the same Gibbs sampler for
a bivariate distribution (and apologies for the lack of latex typesetting on my blog)
where the conditional distributions aref(x,y) = k x^2 exp( -x y^2 - y^2 + 2y - 4x)
Sanjog then spotted and corrected a small error in the variance expression in Darren's derivation; this is now acknowledged on Darren's website. Full details are in the R script now committed in SVN. The R code for the Gibbs sample can therefore be written as follows below. Note that this uses thinning to minimize serial correlation in the conditional densities--which renders the computation more demanding as 'N times thin' draws have to be generated:f(x y) = (x^2)*exp(-x*(4+y*y)) ## a Gamma density kernel f(y x) = exp(-0.5*2*(x+1)*(y^2 - 2*y/(x+1)) ## a Gaussian kernel
A second variant can be computed using the R bytecode compiler which appeared with the recent release of R 2.13.0 (and which we analysed in this blog post from April). This is as easy as## Here is the actual Gibbs Sampler ## This is Darren Wilkinsons R code (with the corrected variance) ## But we are returning only his columns 2 and 3 as the 1:N sequence ## is never used below Rgibbs <- function(N,thin) mat <- matrix(0,ncol=2,nrow=N) x <- 0 y <- 0 for (i in 1:N) for (j in 1:thin) x <- rgamma(1,3,y*y+4) y <- rnorm(1,1/(x+1),1/sqrt(2*(x+1))) mat[i,] <- c(x,y) mat
Thanks to Rcpp and the inline package, we can also write a C++ variant that can be built and launched from R with ease. The C++ code is assigned to an R text variable## We can also try the R compiler on this R function RCgibbs <- cmpfun(Rgibbs)
gibbscode. (And we used to typeset such
code on the blog as a character string, ie in a faint red color---but have now switched to highlight it as if it were freestanding C++
code. It really is passed as a single string to R which then uses the cxxfunction() to compile, link and load a C++ function
built around the code. See previous posts on the inline package for more.)
It is noteworthy how the code logic is essentially identical between the basic R version, and the C++ version. Two nested loops control draws of x from a Gamma distribution, conditional on y, as well as draws of y from a Normal, conditional on x. Add a small amount of parameter passing to obtain the parameters## Now for the Rcpp version -- Notice how easy it is to code up! gibbscode <- ' using namespace Rcpp; // inline does that for us already // n and thin are SEXPs which the Rcpp::as function maps to C++ vars int N = as<int>(n); int thn = as<int>(thin); int i,j; NumericMatrix mat(N, 2); RNGScope scope; // Initialize Random number generator // The rest of the code follows the R version double x=0, y=0; for (i=0; i<N; i++) for (j=0; j<thn; j++) x = ::Rf_rgamma(3.0,1.0/(y*y+4)); y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2)); mat(i,0) = x; mat(i,1) = y; return mat; // Return to R ' # Compile and Load RcppGibbs <- cxxfunction(signature(n="int", thin = "int"), gibbscode, plugin="Rcpp")
N and thin, allocation of a results matrix and setup of the random number generator state
to remain consistent with R, as well as a return of the matrix---and that is all.
As Darren's code uses the GNU GSL in its C variant, I also became interested in seeing how a C/C++ hybrid variant using our
RcppGSL package would fare. The code is below.
This code is similar to the version using just Rcpp, but we need to allocate space for the GSL random generator object (and later release that memory allocation), and we do of course call the GSL functions. This also necessitates declaring the function using the two header files listed as arguments for thegslgibbsincl <- ' #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> using namespace Rcpp; // just to be explicit ' gslgibbscode <- ' int N = as<int>(ns); int thin = as<int>(thns); int i, j; gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); double x=0, y=0; NumericMatrix mat(N, 2); for (i=0; i<N; i++) for (j=0; j<thin; j++) x = gsl_ran_gamma(r,3.0,1.0/(y*y+4)); y = 1.0/(x+1)+gsl_ran_gaussian(r,1.0/sqrt(2*x+2)); mat(i,0) = x; mat(i,1) = y; gsl_rng_free(r); return mat; // Return to R ' ## Compile and Load GSLGibbs <- cxxfunction(signature(ns="int", thns = "int"), body=gslgibbscode, includes=gslgibbsincl, plugin="RcppGSL")
include argument of
cxxfunction().
So how is the performance?
The script (now committed in Rcpp's SVN repo as
examples/RcppGibbs/RcppGibbs.R, and also part of the next release) creates the output below when running in non-interactive
mode (whereas interactive mode creates a few charts too):
edd@max:~/svn/rcpp/pkg/Rcpp/inst/examples/RcppGibbs$ r RcppGibbs.R
Replication # 1 complete
Replication # 2 complete
Replication # 3 complete
Replication # 4 complete
N=1000 N=5000 N=10000 N=20000
Elasped Time (R) 0.124 2.650 10.511 41.773
Elasped Time (RC) 0.081 1.916 7.594 30.280
Elapsed Time (Rcpp) 0.003 0.076 0.306 1.221
Elapsed Time (Rgsl) 0.002 0.049 0.196 0.784
SpeedUp Rcomp. 1.530 1.380 1.380 1.380
SpeedUp Rcpp 41.330 34.870 34.350 34.210
SpeedUp GSL 62.000 54.080 53.630 53.280
test replications elapsed relative user.self sys.self
4 GSLGibbs(N, thn) 10 7.845 1.000000 7.84 0
3 RcppGibbs(N, thn) 10 12.218 1.557425 12.22 0
2 RCgibbs(N, thn) 10 312.296 39.808286 311.98 0
1 Rgibbs(N, thn) 10 420.953 53.658764 420.59 0
The first block is a hand-computed comparison using four sets of parameters; the second block uses the excellent rbenchmark package to
compare ten runs at twenty-thousand draws.
We see a nominal increase in performance due to the bytecode compiler, saving roughly 38 percent which seems appropriate given that the R
code mostly controls the loops; actual work in undertaken in the already compiled RNG functions. The Rcpp variant is about 34 times faster
than the pure R code. Sanjog reported higher increases on his OS X machines (and Darren's post echos a similar order of
magnitude). However, on my i7 running Linux I always obtained an improvement in the mid- to high thirties. That is certainly already a
rather pleasant result.
What surprised and stunned me at first was that the GSL solution scores an improvement of around 53 times (close to the factor of 60
reported by Darren). A closer look at the code (shown above) makes it clear that there are very few compute-intensive operations outside of
the RNG draws. I validated this further with a second study timing just one million draws each from a Gaussian and Gamma using R via Rcpp,
and using the GSL. It turns out that the R code is about 2.5 times slower for random draws from the Gamma distribution than the GSL. Inspection of the
source code---in files src/nmath/rgamma.c for R and randist/gamma.c for the GSL shows why. R uses a much more complex
(and presumably more precise) algorithm. I may follow up with Martin Maechler to see if we can illustrative the numerical benefits of this
more expensive approach---this blog entry is getting long enough already.
So to sum up: Gibbs sampling is a somewhat resource-heavy Monte Carlo Markov Chain method for investigating multivariate distributions. R excels at
quick and simple explorations, albeit at somewhat slower execution speed. The
Rcpp package can help by providing easy
means to accelerate simulations by a significant factor. The example discussed here is now in SVN repository for
Rcpp and will be part of the next release.
Updated 2011-07-16: Darren has just updated his comparison; fixed two typos here too.
This is a rant. I've made it in various forms in various places
over the years, and I think it's time to put it somewhere so I can
point people at it, and stop repeating myself.
Here's the pebble in my shoe: people keep claiming that strncpy
is a safer alternative to strcpy. It's not. It's a slower function
that is not going to make you significantly safer.
The problem with strcpy is that it's somewhat easy to overflow
the target array:
char src[] = "hello, world";
char dst[5];
strcpy(dst, src); // Oops.
The suggested alternative with strncpy would be this:
strncpy(dst, src, sizeof(dst));
strncpy gets the size of the destination array as a parameter,
and can therefore make sure the string will fit there. Problem solved?
Not so much.
Every time you do any string handling with C's native string
types and functions, you need to make sure you have allocated
enough memory for each string, you need to keep track of
how much memory you've allocated, and you neet to make sure the
zero byte ('NUL', '\0') is put there correctly. This is a lot
of details to keep track of, and it's not surprising things
sometimes go wrong.
If your arrays are allocated statically, which is the simplest,
but least useful case, you need to something like this with
strcpy:
if (strlen(src) + 1 > sizeof(dst))
panic(); // or however you want to handle your errors
strcpy(dst, src);
The +1 after strlen is to make room for the zero byte (NUL,
'\0') that is used in C to indicate the end of a string.
With strncpy, your code is slightly simpler. This
is its attraction.
Problem is, this only works if dst is an array defined within
the scope of the code. If, as is common, you have received dst
as an argument to a function, sizeof(dst) is the size of a
pointer to an element of the array, not the size of the array.
So now you need to track the size explicitly in a second variable:
strncpy(dst, src, dst_size);
Further, strncpy has an unfortunate error handling mode: it merely fills
the destination array and stops. It does not indicate failure in
any way. It does not terminate the target array with a zero
byte. Since all C string processing assume the zero byte is there,
as soon as you try to use dst as a string, you're in trouble.
But luckily you can check for that before you call strncpy:
if (strlen(src) + 1 > dst_size)
panic(); // or whatever
strncpy(dst, src, dst_size);
By this time, the code is equally hard whether you use
strcpy or strncpy. With strncpy you often waste some
extra time, though, filling the unused parts of the target
array with zero bytes: they're almost never necessary.
Alternatively, you can force the zero byte there yourself,
silently truncating a string.
strncpy(dst, src, dst_size);
dst[dst_size - 1] = '\0'; // let's hope dst_size > 0
If your string handling is OK
with strings being randomly shorter than they should be,
possibly you could replace all of them with empty strings,
and save yourself a world of pain.
Instead of strncpy, use snprintf. It has sensible
error behavior, and is much more versatile:
n = snprintf(dst, dst_size, "%s", src);
if (n >= dst_size)
panic();
snprintf still isn't very nice to use. It still requires you
to allocate memory yourself, and keep track of the size of each
array manually. It's also slower for small destination buffers
(but faster for large ones).
The real solution is to abandon C's antiquated string handling,
and use a more sensible helper library instead. There's a bunch
of them around, though none have gained much popularity. I'm
not going to name any of them,
but just imagine how much nicer
it would be to write code like this instead:
Dynstr *src = dynstr_new_from_cstring("hello, world\n");
Dynstr *cat = dynstr_cat_many(src, src, src, src, src, NULL);
Dynstr *dog = dynstr_substr(cat, 15, 5);
Let the library take care of memory allocations and related
tracking, and concentrate on real problem solving instead.
We did this in Kannel, back in 1999,
and it wiped out all the buffer overflow problems (until a
co-worker decided it was "more efficient" to use native C strings
instead, promptly introducing a buffer overflow).
All of this string handling is, of course, way nicer in higher
level languages. In fact, whenever you need to deal with string
handling in C, it is probably a sign that you should consider switching
to a higher level language instead.
But whatever you do, stop claiming that strncpy is safe or
solves any real problems strcpy has.
Update: Fixed "It does terminate" to say "It does not terminate".
Thanks to Matthew Garrett for pointing that out.
Update2: Fixed example call to snprintf.
Update3: Fixed the test for snprintf example.
Thanks, Redditor axylone.
Also pointed out that snprintf is slower than the rest.
[283808.667454] radeon 0000:01:00.0: ffff88021f815c00 unpin not necessaryThe time between going black reduces every time. The system wasn t usable any more in the end. After testing that the screen was going blank on other systems like a live CD of Ubuntu and a not noteworthy proprietary system, it was clear that some hardware component was dying. My first assumption was verified after replacing it: My graphic card, a Radeon HD 4670, died. This was three weeks ago and around 25 month after I bought the graphics card. So I didn t have to worry if replacing the fan voided the guarantee, because the guarantee lasts only 24 month. Conclusion:
[283808.667820] radeon 0000:01:00.0: GPU softreset
[283808.667823] radeon 0000:01:00.0: R_008010_GRBM_STATUS=0xE57024A4
[283808.667825] radeon 0000:01:00.0: R_008014_GRBM_STATUS2=0 00330302
[283808.667826] radeon 0000:01:00.0: R_000E50_SRBM_STATUS=0x200000C0
[283808.667832] radeon 0000:01:00.0: R_008020_GRBM_SOFT_RESET=0x00007FEE
[283808.682844] radeon 0000:01:00.0: R_008020_GRBM_SOFT_RESET=0 00000001
[283808.698840] radeon 0000:01:00.0: R_008010_GRBM_STATUS=0 00003028
[283808.698843] radeon 0000:01:00.0: R_008014_GRBM_STATUS2=0 00000002
[283808.698845] radeon 0000:01:00.0: R_000E50_SRBM_STATUS=0x200000C0
[283808.699845] radeon 0000:01:00.0: GPU reset succeed
[283808.717570] [drm] Clocks initialized !
[283808.765829] [drm] ring test succeeded in 0 usecs
[283808.765838] [drm] ib test succeeded in 1 usecs
[283808.765840] [drm] Enabling audio support
[283812.521265] radeon 0000:01:00.0: GPU lockup CP stall for more than 1000msec
[283812.521269] [ cut here ]
[283812.521294] WARNING: at /build/buildd/linux-2.6.35/drivers/gpu/drm/radeon/radeon_fence.c:235 radeon_fence_wait+0 365/0x3d0 [radeon]()
[283812.521297] Hardware name:
[283812.521299] GPU lockup (waiting for 0x00AE670A last fence id 0x00AE6705)
[283812.521301] Modules linked in: btrfs zlib_deflate crc32c libcrc32c ufs qnx4 hfsplus hfs minix ntfs vfat msdos fat jfs xfs exportfs reiserfs nls_utf8 udf ip6table_filter ip6_tables binfmt_misc ipt_MASQUERADE iptable_nat nf_nat nf_conntrack_ipv4 nf_defrag_ipv4 xt_state nf_conntrack ipt_REJECT xt_tcpudp iptable_filter ip_tables x_tables bridge stp kvm_intel kvm parport_pc ppdev snd_emu10k1_synth snd_emux_synth snd_seq_virmidi snd_seq_midi_emul snd_emu10k1 snd_ac97_codec ac97_bus snd_pcm snd_page_alloc snd_util_mem snd_hwdep snd_seq_midi radeon snd_rawmidi snd_seq_midi_event snd_seq snd_timer snd_seq_device ttm snd pl2303 drm_kms_helper coretemp usbserial joydev psmouse soundcore drm serio_raw intel_agp i2c_algo_bit lp parport hid_cherry usbhid hid firewire_ohci firewire_core usb_storage crc_itu_t e1000e ahci libahci pata_marvell
[283812.521360] Pid: 2194, comm: compiz Tainted: G W 2.6.35-24-generic #42-Ubuntu
[283812.521362] Call Trace:
[283812.521370] [<ffffffff8106089f>] warn_slowpath_common+0x7f/0xc0
[283812.521374] [<ffffffff81060996>] warn_slowpath_fmt+0 46/0 50
[283812.521390] [<ffffffffa01bd775>] radeon_fence_wait+0 365/0x3d0 [radeon]
[283812.521394] [<ffffffff8107f730>] ? autoremove_wake_function+0 0/0 40
[283812.521410] [<ffffffffa01bdf71>] radeon_sync_obj_wait+0 11/0 20 [radeon]
[283812.521418] [<ffffffffa01751a3>] ttm_bo_wait+0 103/0x1c0 [ttm]
[283812.521435] [<ffffffffa01d4e1a>] radeon_gem_wait_idle_ioctl+0x9a/0 150 [radeon]
[283812.521447] [<ffffffffa010f433>] drm_ioctl+0 463/0 520 [drm]
[283812.521465] [<ffffffffa01d4d80>] ? radeon_gem_wait_idle_ioctl+0 0/0 150 [radeon]
[283812.521470] [<ffffffff81162f0d>] vfs_ioctl+0x3d/0xd0
[283812.521473] [<ffffffff811637e1>] do_vfs_ioctl+0 81/0 340
[283812.521477] [<ffffffff811535f1>] ? vfs_read+0 181/0x1a0
[283812.521480] [<ffffffff81163b21>] sys_ioctl+0 81/0xa0
[283812.521484] [<ffffffff8100a0f2>] system_call_fastpath+0 16/0x1b
[283812.521487] [ end trace 6d5e03bab743abfa ]
[283812.521493] [drm] Disabling audio support
[283812.525575] [drm:radeon_ib_schedule] *ERROR* radeon: couldn t schedule IB(10).
[283812.525579] [drm:radeon_cs_ioctl] *ERROR* Faild to schedule IB !
[283812.527021] [drm:radeon_ib_schedule] *ERROR* radeon: couldn t schedule IB(11).
[283812.527024] [drm:radeon_cs_ioctl] *ERROR* Faild to schedule IB !
[283812.527921] [drm:radeon_ib_schedule] *ERROR* radeon: couldn t schedule IB(12).
[283812.527923] [drm:radeon_cs_ioctl] *ERROR* Faild to schedule IB !
Image credit: Lake Shimmer by (nc-sa) cobalt123.
The beautiful photo above is what reflections should look like. If you don't like Google's shimmering +1 buttons, try the convenient AdBlock filter Tom Morris wrote. I also block this image.
I have been reading a lot about Google+. I'm sure a lot of people put a lot of hard work into it. Lots of people seem to enjoy using it and appreciate its features. For my part, right now, when I see Google+ mentioned, the smile vanishes from my face. I just have a few thoughts. It's anti-competitive. If you could ask Google, "How much for a shimmering +1 button next to every search result?" you would be laughed out of the room. But they managed to offer themselves that unique marketing opportunity. I know that (1) most regulators who see this anti-competitive behavior won't see it as an anti-trust violation, and (2) the damage is already done, and no retribution in the future can act fast enough to fix the unfair advantage Google gave itself in the Internet-mediated personal communication (and ad sales) markets. The shimmering is distracting, making my online search experience worse. I know that Google is holding nothing back; they are willing to distract me from my intended use of Google in order to branch out their business. (If you haven't seen the shimmering +1 button, it's next to every web search result, and if you mouse over any part of the result, it does a wavy dance.) The most-touted feature is a clone of Diaspora. This by itself is fine; software should help users by having the best features imaginable. But the enthusiasm I've seen within the free software community (like when I read about Google+ on Slashdot and Planet Debian) should at least recognize that Google "circles" are a clone of Diaspora's Aspects. Centralization on the web feels like a personal attack. Corporations on the web are like unstoppable machines rolling us toward a future of corporate eavesdropping, central points of failure, and end-users sold en masse to advertisers. It enables a future of individual "platform owners" who can change the lived experience of untold hundreds of millions with tweaks that benefit their actual customers (the advertisers). There's not much I can do about that. I happen to take this personally: I am part of a small culture of people who run their own mail and web servers and understand the importance of software freedom. This is a part of my identity. I watch as its traces online vanish, replaced by something more efficient and terrifying. It makes me sad. I'm probably going to end up using it despite all these pain points. That's how I know that I am being steamrolled. The reasons I have given above are not reasons to not use Google+. They're just reasons that I'm going to frown all the way to the address bar. In weeks to months to years, the service will grow an enthusiastic userbase. At that point, personally, I'll have to make a choice between connecting with those people on their terms, or not staying in touch with them. Already, professionally, the idea has already come up on #openhatch that Google+ could help us reach people willing to contribute to open source. Are my gripes worth holding OpenHatch back, or worth isolating myself over? Probably not.
Half a year ago, I experimented with gtk+ and cairo to extract a PDF screenshot out of a progam, i.e. a screenshot of the window that is not a table of colored dots as a regular PNG file would be, but rather a vector graphic that scales perfectly and has selectable text. The main use that I see is documentation: A scalable screenshots looks much better in print, and even in an online-PDF-file, having the full-text-search also find the text in the images is useful.
My experiments back then were successful in a proof-of-concept way, but they were very ugly hacks. With the new version 3 of gtk+, though, things become much easier, as only one cairo context is used, instead of each widget creating its own context to draw on.
By now, the first gtk-3 applications have reached Debian unstable, so I thought it would be time to re-do the experiment. And the result is very pleasing: The pdf screenshot program comes as a gtk module that you can load by setting an environment variable before launching a gtk-3 program. The application will run as usual, but there is an additional PDF screenshot button. If you click it, you get a Save File dialog (with a nice, live-updated preview of the screenshot, as an additional gimmick) that lets you save a PDF file. Its as easy as that. You can check out the resulting PDF file of gucharmap and a screencast of me creating that file, including copy n pasting from the resulting document.
So Christian likes to give out awards for the best bug reporting estimates and also does statistics about developers per capita. I've got at least one area where he's on top:his heart was now overflowing with love, and by loving people without cause he discovered indubitable causes for loving them. How often we sin, how much we deceive, and all for what? All will end in death, all! A pleasant humming and whistling of bullets were often heard. Looking into Napoleon s eyes Prince Andrew thought of the insignificance of greatness, the unimportance of life which no one could understand, and the still greater unimportance of death, the meaning of which no one alive could understand or explain. If there is a God and future life, there is truth and good, and man s highest happiness consists in striving to attain them. We must live, we must love, and we must believe that we live not only today on this scrap of earth, but have lived and shall live forever, there, in the Whole, said Pierre, and he pointed to the sky. Prince Andrew stood leaning on the railing of the raft listening to Pierre, and he gazed with his eyes fixed on the red reflection of the sun gleaming on the blue waters. There was perfect stillness. Pierre became silent. The raft had long since stopped and only the waves of the current beat softly against it below. Prince Andrew felt as if the sound of the waves kept up a refrain to Pierre s words, whispering: It is true, believe it. He sighed, and glanced with a radiant, childlike, tender look at Pierre s face, flushed and rapturous, but yet shy before his superior friend. In Natasha Prince Andrew was conscious of a strange world completely alien to him and brimful of joys unknown to him, a different world, that in the Otradnoe avenue and at the window that moonlight night had already begun to disconcert him. Now this world disconcerted him no longer and was no longer alien to him, but he himself having entered it found in it a new enjoyment. All the kings, except the Chinese, wear military uniforms, and he who kills most people receives the highest rewards. But what is war? What is needed for success in warfare? What are the habits of the military? The aim of war is murder; the methods of war are spying, treachery, and their encouragement, the ruin of a country s inhabitants, robbing them or stealing to provision the army, and fraud and falsehood termed military craft. The habits of the military class are the absence of freedom, that is, discipline, idleness, ignorance, cruelty, debauchery, and drunkenness. And in spite of all this it is the highest class, respected by everyone. From the moment Pierre had witnessed those terrible murders committed by men who did not wish to commit them, it was as if the mainspring of his life, on which everything depended and which made everything appear alive, had suddenly been wrenched out and everything had collapsed into a heap of meaningless rubbish. Though he did not acknowledge it to himself, his faith in the right ordering of the universe, in humanity, in his own soul, and in God, had been destroyed. He had experienced this before, but never so strongly as now. When similar doubts had assailed him before, they had been the result of his own wrongdoing, and at the bottom of his heart he had felt that relief from his despair and from those doubts was to be found within himself. But now he felt that the universe had crumbled before his eyes and only meaningless ruins remained, and this not by any fault of his own. He felt that it was not in his power to regain faith in the meaning of life. When Princess Mary began to cry, he understood that she was crying at the thought that little Nicholas would be left without a father. With a great effort he tried to return to life and to see things from their point of view. Yes, to them it must seem sad! he thought. But how simple it is. The fowls of the air sow not, neither do they reap, yet your Father feedeth them, he said to himself and wished to say to Princess Mary; but no, they will take it their own way, they won t understand! They can t understand that all those feelings they prize so all our feelings, all those ideas that seem so important to us, are unnecessary. We cannot understand one another, and he remained silent. Love hinders death. Love is life. All, everything that I understand, I understand only because I love. Everything is, everything exists, only because I love. Everything is united by it alone. Love is God, and to die means that I, a particle of love, shall return to the general and eternal source. These thoughts seemed to him comforting. People speak of misfortunes and sufferings, remarked Pierre, but if at this moment I were asked: Would you rather be what you were before you were taken prisoner, or go through all this again? then for heaven s sake let me again have captivity and horseflesh! We imagine that when we are thrown out of our usual ruts all is lost, but it is only then that what is new and good begins. While there is life there is happiness. There is much, much before us. I say this to you, he added, turning to Natasha. During that twenty-year period an immense number of fields were left untilled, houses were burned, trade changed its direction, millions of men migrated, were impoverished, or were enriched, and millions of Christian men professing the law of love of their fellows slew one another. What does all this mean? Why did it happen? What made those people burn houses and slay their fellow men? What were the causes of these events? What force made men act so? These are the instinctive, plain, and most legitimate questions humanity asks itself when it encounters the monuments and tradition of that period.
insteadOf trick.
Here s the bottom of ~/.gitconfig:
[url "git://anonscm.debian.org"]
insteadOf = "git://git.debian.org"
[url "ssh://git.debian.org"]
pushInsteadOf = "git://git.debian.org"
And tada! debcheckout picks the appropriate service (anonscm for
anonymous access), and one is still able to push (through ssh)
without having to change the URL in each and every .git/config file
(which would also lead to higher CPU usage when updating afterwards).
long time no post about my RC bug fixing activities. & indeed, I haven't
been very active during the last weeks. here's a quick update; it includes
two NMUs done for the perl 5.12 transition, the rest is just
"normal" maintainance work (interesting to see how much stuff can
break behind our backs ...).
Entered in 6 months of the house's solar power data.
![]() |
Next.