Author Archives: rmacqueen

Lição 1: Introdução à programação

O que é programação:

  • Idioma para falar com o computador
  • Linguagem imperativa: voçê está mandando ordens para o computador
  • A gramática é muito estrita: se voçê cometer um erro, o computador não vai entender

Python

  • Python é a linguagem que a gente vai usar nesse curso
  • É uma linguagem bem popular no mundo, usado no Facebook, Google, NASA, e jogos como Civilization IV

Turtle

  • Turtle é um pacote do Python que é usado para desenhar coisas na tela
  • O turtle tem varios comandos, incluindo: turtle.left()turtle.right()  turtle.forward()
  • Pode combinar esses comandos para desenhar formas, por exemplo:import turtle turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.mainloop()Erros comuns:
    • Falta parêntese: turtle.forward(10
    • Error ortográfico: turtle.farward(100)

Variáveis

  • A gente usa variáveis para guardar informações na memoria
  • Com isso, nossos programas ficam mais flexiveis. Eu posso mudar o valor do variavel num lugar, e ele muda no programa inteiro, por exemplo
import turtle

tamanho = 200
angulo = 90

turtle.forward(tamanho)
turtle.right(angulo)
turtle.forward(tamanho)
turtle.right(angulo)
turtle.forward(tamanho)
turtle.right(angulo)
turtle.forward(tamanho)

turtle.mainloop()
  • É importante usar nomes relevantes com as variaveis, tipo ‘tamanho’ em vez de ‘x’
  • A gente pode deixa o computador calcular o valor de uma variavel:
import turtle

tamanho = 200
lados = 4
angulo = 360 / lados

turtle.forward(tamanho)
turtle.right(angulo)
turtle.forward(tamanho)
turtle.right(angulo)
turtle.forward(tamanho)
turtle.right(angulo)
turtle.forward(tamanho)

turtle.mainloop()

 for loop

  • Um princípio muito importante na programação é D.R.Y (Don’t Repeat Yourself) – Não Se Repita
  • Nesse programa encima, a gente tá repetindo a linha turtle.forward(tamanho) e turtle.right(angulo)
  • Para não ficar repetindo, a gente pode usar o for loop. O for loop diz para o computador: “Repita o seguinte X vezes”. Por exemplo
for i in range(4):
    turtle.forward(100)
    turtle.right(90)
  • Esse significa: Repita 4 vezes os duas linhas em baixo
  • Agora o programa encima vira:
import turtle

tamanho = 100
lados = 4
angulo = 360 / lados

for i in range(lados):
    turtle.forward(tamanho)
    turtle.right(angulo)

turtle.mainloop()
  • Agora a gente pode simplesmente modificar o ‘tamanho’ e o ‘lados’ para criar várias formas diferentes

Functions

  • Se a gente quisesse desenhar várias formas na mesma tela, a gente teria que copiar colar esse for loop e cada vez mudar o valor dos variaveis (tamanho, lados).
  • Como a gente nunca quer se repetir assim, a gente vai usar uma function (função)
  • A function está escrito assim (Preste atenção à sintaxe):
def desenhar_forma (lados, tamanho):
    angulo = 360 / lados
    for i in range(lados):
        turtle.forward(tamanho)
        turtle.right(angulo)
  • Esses codigos aqui é só a declaração da function. Ainda a gente não usou o function mesmo. Para usar, a gente tem que passar os parâmetros no mesmo ordem que eles são declarados:
import turtle

def draw_shape (lados, tamanho):
    angulo = 360 / lados
    for i in range(lados):
        turtle.forward(tamanho)
        turtle.right(angulo)

draw_shape(6, 100)

turtle.mainloop()
  • O uso da function tem que acontecer depois do que a declaração da function
  • No Python os espaços são importantes. Todas as linhas que estão dentro do function tem começar com um ‘tab’
  • Um function pode aceitar qualquer numero de parâmetros. Há outro comando no turtle para mudar o cor. Então a gente vai adicionar mais um parâmetro ao function, se chama ‘cor’. Assim a gente pode criar varias formas com cores diferentes.
import turtle

def draw_shape (lados, tamanho, cor):
    turtle.color(cor)
    angulo = 360 / lados
    for i in range(lados):
        turtle.forward(tamanho)
        turtle.right(angulo)

draw_shape(6, 100, "green")
draw_shape(3, 200, "red")

turtle.mainloop()
  • Lembra que os nomes dos variaveis não são importantes para o computador (eu poderia escolher nomes tipo “x”, “y”, “z” em vez de “lados”, “tamanho”, “angulo”, mais, mesmo assim, é importante escolher nomes relevantes para que outras pessoas possam entender a seu programa.

Mais comandos do turtle

  • Existem muitos mais comandos para o turtle. Para ver uma lista completa desses comandos, visita essa pagina aqui

Qualquer duvida, escreva um comentário aqui em baixo e eu vou responder 🙂 Obrigado!

Letter to Speaker Ryan

I sent the below letter to Speaker Paul Ryan on January 29th, 2017, in response to Trump’s executive order on immigration.

Speaker Ryan,

I am writing to you today as a U.S. citizen to express my strong opposition to Executive Order 13769, issued by Donald Trump on Friday, which would impose a 90 day ban on nationals from seven predominantly Muslim countries (Libya, Iran, Iraq, Somalia, Sudan, Syria, and Yemen) from entering the United States, as well as indefinitely suspending the Syrian Refugee program.

President Trump claims the enactment of this order is driven by a concern for national security. Given that you, Speaker Ryan, have on more than one occasion described yourself as a ‘policy wonk’, I thought you might be interested in some of the numbers pertinent to this issue. According to the Cato Institute, a libertarian think tank, between 1975 and 2015, the United States admitted over 3.25 million refugees, of whom only three ended up committing attacks that killed Americans. During the same period, our country granted protection to over 700,000 asylum seekers, of whom again only three would go on to perpetrate deadly terrorist attacks. Perhaps most importantly, of those combined six people, exactly zero hailed from countries targeted by President Trump’s ban. As justification for the draconian measure, Trump made reference in the text to the attacks on September 11, 2001, but again, none of the perpetrators of that horrific attack were from the countries mentioned above. It therefore beggars belief that this order arose out of a concern for the safety and security of Americans.

The chances of being killed by a foreign born terrorist is approximately 1 in 3.6 million. To put that figure in perspective, the odds of being killed by lightning are four times as high.

I work as a software engineer and I know of at least one tech conference (jsconf.eu) which has had to revise its schedule (and may even have to cancel its program entirely) as a result of this executive order. I suspect more will follow. What this means is less collaboration, less sharing of knowledge, and ultimately a diminished ability to solve the key engineering problems facing our country today. As a strong advocate for entrepreneurship and small business, you must appreciate the adverse effects this poses for economic growth.

Of course, mere economic disruption, though important, pales in comparison the very real distress and panic now visited upon the many many families who have loved ones now abroad and must wonder if and when they will be able to see them again. Allowing such a discriminatory and draconian order to go into effect is therefore not just imprudent but morally repugnant.

I urge you to do everything in your power, both in your capacity as Speaker of the House and as personal confidant of the President, to reverse this order, and replace it with a more sensible and moral immigration policy. Failing that, I ask that you provide a clear justification for your support of this order, since based on my arguments above, national security simply cannot logically be the driving factor.

Thank you for taking the time to read this.

Sincerely,

Rory MacQueen

Underground Trump

Donald Trump’s peculiar way of speaking has amused and alarmed an entire nation since the day he began his campaign. While his supporters see his eccentric rhetoric as a breath of fresh air from the robotic, pre-scripted screeds of experienced politicians, others regard it as at best the ravings of an idiot and at worse offensive and hateful word vomit. Both sides will surely agree that it is different, in a bizarre, surreal way that they can’t quite describe. By the end of a Trump speech you are left wondering what on earth you just listened to, and how such a stream of consciousness could emanate from one person.  Lots and lots of attempts have been made to imitate the Donald’s ramblings, some more successful than others, but no one seems to have been able to capture the circuitous, nigh schizophrenic nature of it, which can almost mesmerize the listener. Until now!

It was only when I started reading some of Trump’s speeches – something I would encourage everyone to do, since by reading you escape the showmanship and the theatrics, and get a distilled version of what is actually going through his head – that I began to have the niggling sensation that his mannerisms were distantly familiar. In particular I was struck by the way he jumps from one topic to another; the way he manages to turn every topic back on himself; the unnecessary repetition of concepts, especially in reaffirming qualities about himself in the absence of any contention; the placing of emphasis on words that don’t seem, contextually, to warrant it; and perhaps most importantly, the way he almost seems to be having a conversation with another person we can’t see. All of this is unsettling, but reminded me of something, or someone, but who? Just yesterday, in regards to Trump’s horrendous Black History month speech, my friend Christian Smith made the excellent observation that Donald Trump sounded like the Underground Man, from Dostoyevsky’s Notes from Underground. Suddenly I realized that this was exactly it. Trump had the same diction as the original existentialist anti-hero. I’m not sure how to feel about this revelation since while I’m very fond of that book, I can’t say the same about our President. In any case, here are some excerpts below, alternating between Trump speeches and The Underground Man, for you to judge for yourself. Enjoy!

I believe my liver is diseased. However, I know nothing at all about my disease, and do not know for certain what ails me. I don’t consult a doctor for it, and never have, though I have a respect for medicine and doctors. Besides, I am extremely superstitious, sufficiently so to respect medicine, anyway (I am well-educated enough not to be superstitious, but I am superstitious). No, I refuse to consult a doctor from spite. That you probably will not understand. Well, I understand it, though. Of course, I can’t explain who it is precisely that I am mortifying in this case by my spite: I am perfectly well aware that I cannot ‘pay out’ the doctors by not consulting them; I know better than anyone that by all this I am only injuring myself and no one else. But still, if I don’t consult a doctor it is from spite. My liver is bad, well—let it get worse!
– The Underground Man

IRS, e-mails.  I get sued all the time, okay.  I run a big business.  You know I’ve always said it’s very, very hard for a person who is very successful.  I have done so many deals.  Almost all of them have been tremendously successful.  You’ll see that when I file my statements.  I mean you will see; you will be very proud of me, okay.  But I’ve always said, and I said it strongly, it’s very hard for somebody that does tremendous numbers of deals to run for politics, run for political office, any office, let alone president.  Because you’ve done so much; you’ve beaten so many people; you’ve created so many–  Look, Obama, what did he do?  No deal.  He never did a deal.  He did one deal.  A house.  And if you did that house you’d be in jail right now, okay.  He got away with murder.  But I can tell you, e-mails.  IRS, the e-mails, thousands of them, they were lost; they were lost.  If you were in my world you would know that e-mails can’t be lost; they can’t be lost.  So why aren’t our politicians finding out where those e-mails are?
– Donald Trump

That is my conviction of forty years. I am forty years old now, and you know forty years is a whole lifetime; you know it is extreme old age. To live longer than forty years is bad manners, is vulgar, immoral. Who does live beyond forty? Answer that, sincerely and honestly I will tell you who do: fools and worthless fellows. I tell all old men that to their face, all these venerable old men, all these silver-haired and reverend seniors! I tell the whole world that to its face! I have a right to say so, for I shall go on living to sixty myself. To seventy! To eighty!
– Underground Man

The world is blowing up, the migration in Syria — they say one of their achievements for the year is bringing peace to Syria, and the whole world’s talking about it. It’s — the level of stupidity is incredible. I’m telling you. I used to use the word incompetent, now I just call them stupid. I went to an Ivy League school, I’m very highly educated. I know words, I had the best words. I have — but there’s no better word than stupid. Right? There is none. There is none. There’s no — there’s no — there’s no word like that. So we are going to turn things around. But — and if we have Hillary — I’ve got to tell you. I just saw where for the last week she’s been hitting me really hard with the women card, OK? Really hard. And I had to say OK, that’s enough, that’s enough. And we did a strong number. She’s not going to win. Any by the way, I love the concept — I love, love, love having a woman president. Can’t be her. She’s horrible. She’s horrible. And you know really don’t — I’ll tell you who does not like — yeah, we’ll get Ivanka. Good. Let’s do Ivanka. But I’ll tell you who doesn’t like Hillary are women. Women don’t like Hillary. I see it all the time. And always so theatrical; Mr. Trump said this and that and this. And you just — I actually — I shouldn’t do it. I just have to turn off the television so many times. She just gives me a headache. But you know — although I think last night I gave her a big headache. I can imagine — I can imagine those discussions. But you have to hit back hard, and you can’t let them push you around.
– Donald Trump

I am told that the Petersburg climate is bad for me, and that with my small means it is very expensive to live in Petersburg. I know all that better than all these sage and experienced counsellors and monitors. … But I am remaining in Petersburg; I am not going away from Petersburg! I am not going away because … ech!
– Underground Man

Last month, we celebrated the life of Reverend Martin Luther King, Jr., whose incredible example is unique in American history. You read all about Dr. Martin Luther King a week ago when somebody said I took the statue out of my office. It turned out that that was fake news. Fake news. The statue is cherished, it’s one of the favorite things in the—and we have some good ones. We have Lincoln, and we have Jefferson, and we have Dr. Martin Luther King. But they said the statue, the bust of Martin Luther King, was taken out of the office. And it was never even touched. So I think it was a disgrace, but that’s the way the press is. Very unfortunate.
– Donald Trump

When petitioners used to come for information to the table at which I sat, I used to grind my teeth at them, and felt intense enjoyment when I succeeded in making anybody unhappy. I almost did succeed. For the most part they were all timid people—of course, they were petitioners. But of the uppish ones there was one officer in particular I could not endure. He simply would not be humble, and clanked his sword in a disgusting way. I carried on a feud with him for eighteen months over that sword. At last I got the better of him. He left off clanking it. That happened in my youth, though.
– Underground Man

So we have to rebuild quickly our infrastructure of this country.  If we don’t–  The other day in Ohio a bridge collapsed.  Bridges are collapsing all over the country.  The reports on bridges and the like are unbelievable, what’s happening with our infrastructure. I go to Saudi Arabia, I go to Dubai; I am doing big jobs in Dubai.  I go to various different places.  I go to China.  They are building a bridge on every corner.  They have bridges that make the George Washington Bridge like small time stuff.  They’re building the most incredible things you have ever seen.  They are building airports in Qatar–which they like to say “cutter” but I’ve always said “qatar” so I’ll keep it “qatar” what the hell.  But they’re building, they’re building an airport and have just completed an airport the likes of which you have never seen, in Dubai an airport the likes of which you have never seen.  And then I come back to LaGuardia where the runways have potholes.  The place is falling apart.  You go into the main terminal and they have a terraza floor that’s so old it’s falling apart.  And they have a hole in it, and they replace it with asphalt.  So you have a white terraza floor and they put asphalt all over the place.  This is inside, not outside.  And I just left Dubai where they have the most incredible thing you’ve ever seen.  In fact my pilot said oh Mr. Trump this is such an honor.  I said it’s not an honor; they’re just smart.  But you look at LAX, and you look at Kennedy Airport, and you look at our airports generally, you look at our roadways where they’re crumbling.
– Donald Trump

Fantastic Bugs And Where To Find Them

Last Friday we encountered a bug in our codebase whose origin was of such a peculiar nature, and whose eventual resolution proved so instructive, that I thought I would record it here.

First, some brief background. EndlessOS is built for two different computer architectures: x86 and ARM. With a few notable exceptions, personal computers generally run x86, while tablets and smartphones run ARM. In an effort to bring down the cost of PCs (ARM chips tend to be cheaper) Endless has released a desktop computer running ARM. Since the chipsets are designed differently, compilation – that is, the process by which we translate source code to machine code – must happen separately for each architecture. Our OS, with all its accompanying apps and tools, must be built twice, and, of course, tested twice. However, application code, living as it does in the cushy land of user space, usually does not exhibit different behaviour when running on ARM versus running on x86. In fact, only if you are doing low-level processor instructions, such as bit manipulation, should you even care what chip architecture you are running on. It was, therefore, to our surprise (and, indeed, horror) when we discovered, late in a release cycle, that a number of our apps had been shown to work on the x86 machines, but not on the ARM machines. The QA team reported that upon opening one of these problematic apps, the user would never be able to access a subset page. Without going into too much detail, suffice it to say that the data in our apps is organized into ‘sets’ and ‘subsets’; clicking on the title of a subset ought to take you to the subset page.

Our apps are built with a homegrown framework we have at Endless called the Knowledge Library. The framework provides a number of components, or ‘Modules’, which you can use to rapidly build complex, data-driven applications. Apps are built in Facebook’s Flux paradigm, complete with a dispatcher, history store, and of course, views in the form of GtkWidgets. I knew (because we had built it) that the module responsible for transitioning between pages in an app was the Pager. Examining the Pager code, we found the line responsible for displaying the subset page:

if (SetMap.get_parent_set(item.model) && this._subset_page) { 

    this._show_page_if_present(this._subset_page);

}

If the subset page wasn’t showing up, it meant that one of the two expressions in the if condition was evaluating to false when it shouldn’t do. The second condition this._subset_page simply checks to see if you have a subset page at all in your app, which I knew we did. The first condition queries the SetMap – an in-memory graph which maps relationships between set models in the database – and asks if the parent set of the model in question is defined. In essence, this is equivalent to asking if model has a parent set – if it does, then we know that the model is a subset, and that therefore it is appropriate to show the subset page. We suspected, then, that something was up with the contents of this SetMap – specifically, we guessed, based on knowing how SetMap was written, that it had no data in it at all, and was just mindlessly returning null for any and all set queries we gave it.

We decided to take a look at where SetMap was getting its data from, and found this function:

initialize_set_map: function (cb) {
    Eknc.Engine.get_default().query(Eknc.QueryObject.new_from_props({
        limit: -1,
        tags_match_all: ['EknSetObject'],
    }), null, (engine, res) => { 
        let results;
        try { 
            results = engine.query_finish(res); 
        } catch (e) { 
            logError(e, 'Failed to load sets from database'); 
            return;
        } 
        SetMap.init_map_with_models(results.models); 
        this._window.make_ready(cb);
    });
}

The relevant context here is that the Engine retrieves data from our database according to the parameters of the query it is given. The query takes the form of a JSON object, and, in this case, is simply:

{
    limit: -1,
    tags_match_all: [‘EknSetObject’],
}

What we’re saying here is fetch me content tagged as ‘EknSetObject’, and don’t impose a limit. Now, if our hypothesis was correct, and the SetMap was empty, that meant that this query was returning nothing. However, we knew that we were seeing sets on the home page, and the query which returned those sets was remarkably similar:

{
    limit: limit,
    tags_match_all: ['EknSetObject'],
    sort: Eknc.QueryObjectSort.SEQUENCE_NUMBER,
}

Both queries were asking for sets, but one was getting some and the other was getting none. What was different between them? Well, one difference we can see here is that the home page query requests its results to be sorted by the SEQUENCE_NUMBER key. Our Xapian backend database allows for sorting by predefined keys, and the SEQUENCE_NUMBER key describes the order in which models were added to the database. Having the results in that order is important when showing them on the home page, but in the case of a SetMap, where data isn’t going to be arranged linearly anyway, sorting is obviously irrelevant, so no sort field is included. In any case, whether data is sorted or not shouldn’t affect the quantity of said data that is returned, so we dismissed that as being the source of the problem.

What about that limit field though? Limits certainly do affect the quantity of things returned, and that -1 numeral seemed particularly suspect. I knew we had been using -1 as a special value to indicate ‘no limit’, but couldn’t quite recall how that worked. Just as a test, we changed the limit to a positive value, 10, and ran the app again. The bug was gone! The limit field was indeed the culprit, but our investigation had now only just begun. We certainly couldn’t leave this value at 10 – remember we wanted all sets returned, not just 10. Furthermore, this discovery seemed only to raise more questions: we had been using -1 to denote ‘no limit’ for many releases now, why were we only seeing that it was problematic now? If -1 was a problem for the query to handle, why was it not throwing an error, why instead return no results? And, perhaps most troublingly still, why were we only seeing this bug on the ARM architecture machines?

We dug more into the use of this limit field. Along with the rest of the query, the limit field eventually gets serialized into a JSON string and sent over an HTTP bridge to the local Xapian database server. Once on the server, which, unlike the app, is written in C, it gets parsed with the following line:

limit = (guint) g_ascii_strtod (str, NULL);

Here we were parsing the limit string as a double (the g_ascii_strtod() function converts strings to doubles) and then casting that double as an unsigned integer. Several things seemed awry at first glance: why were we parsing this limit field as a double, when doubles are meant only for storing floating point numbers? And, having parsed it as a double, why then cast it as an unsigned integer? Moreover, if it is meant to be an unsigned integer, how is -1 a valid input?

We pulled this line of code out into its own source file, ran it to see what happens when str is -1:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <glib.h>
#include <stdint.h>

int 
main (int argc, char *argv[])
{
    unsigned int limit = g_ascii_strtod ("-1", NULL);

    fprintf (stderr, "limit := %u\n", limit);

    return EXIT_SUCCESS;
}

Running on my intel machine this program printed out 4294967296, more commonly known as 232 – the maximum value expressible in a 32 bit integer. Aha! So here is where the -1 made good on its promise to be a ‘special value’ for fetching all sets. By casting it from a double to an unsigned int, we were exploiting the Two’s Complement method of storing integers to ‘transform’ the same binary number (in this case, 32 consecutive 1s) from a ‘-1’ to MAX_UINT. Setting the limit to be such a large value was effectively the same as saying ‘impose no limit’, and that is how we would get all sets returned.

We ran the same code snippet on ARM, and lo and behold, it printed out 0. We knew now that it was this line suffering from architecture dependent behaviour. But why? Why didn’t the ARM machine also exhibit the integer underflow trick? It turns out that, in the C programming language, underflowing an unsigned integer, far from being a clever trick, is in fact undefined behaviour. I had always vaguely been aware of this fact, but had not, until last week, quite appreciated the import of what that term carries. What I had understood about integer underflow, and other undefined behaviours, was that they were inadvisable, bad practice, perhaps even that they would trigger an error in certain cases. The truth is much more sinister than that, for the C spec is written not so much for you, the C programmer, as it is for the compiler. How operations behave and what constitutes valid syntax are built into the compiler. What then, does the C spec say about ‘undefined behaviour’:

Anything at all can happen; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.

This blog post by a CS professor at the University of Utah provides an excellent overview of undefined behaviour in C and C++, but the bottom line is that once you invoke undefined behaviour, all bets are off: the entire program becomes meaningless. As long as it adheres to the explicit rules in the spec, compilers have enormous freedom. We violated those rules the moment we included an integer underflow. At that point the compiler could do whatever it pleases and still claim to be a valid C compiler. It could have refused to compile; it could have compiled and then promptly crashed; it could have compiled and then printed out the complete works of Charles Dickens to stdout. All of these are valid executions of the program because the program has now lost all meaning.

One might be tempted to think: ‘but surely only that single line was invalid. Even if it does do something bizarre when it reaches that line, shouldn’t the rest of the code up to that point function normally?’ This objection (which I myself raised) has both a theoretical and a practical answer. Theoretically, the answer is simply no that’s not how computer languages work – once you include undefined behaviour, the whole program is said to be meaningless. Furthermore, practically speaking, the notion of ‘reaching that line’ itself betrays a misunderstanding of how the compiler works: a compiler is at liberty to rearrange lines of code (which it does indeed do to optimize performance) provided such rearrangements will not have observable side effects on the execution of the program. Of course, a real world compiler probably won’t rearrange things such that that integer underflow line screws up the rest of the program, just as a real world compiler probably won’t print out the complete works of Charles Dickens when you try to divide by zero, but the point is that you can’t assume it won’t do those things, and there are lots of things it could do that lie in between that and normal execution. It could, for example, when it sees an undefined integer operation, choose to assign a zero value to the unsigned int. This is what apparently did happen on our ARM machines, and the reason why might have something to do with the ARM processor’s ability to store memory in both big-endian and little-endian format. In any case, when we consider the infinite domain of options that our illegitimate operation gave the compiler license for, returning zero now actually seems not unreasonable.

As is often the case, once we understood the problem, the patch itself was quite simple. Given that we were already late into the release cycle, the aim was to keep the diff on this patch small, so we simply added a check for the negative value

 /* str may contain a negative value to mean "all matching results"; since
   * casting a negative floating point value into an unsigned integer is
   * undefined behavior, we need to perform some level of validation first
   */
  {
    double val = g_ascii_strtod (str, NULL);

    /* Allow negative values to mean "all results" */
    if (val < 0)
      limit = G_MAXUINT;
    else
      limit = CLAMP (val, 0, G_MAXUINT);
  }

This will ensure that the limit is never cast directly from a negative value to an unsigned int, and that its value always lives between 0 and MAX_UINT.

As any programmer will tell you, all intense debugging sessions always end with the desperate phrase, “but how did this ever work?”. The same was true for us, and what still bothered me was why we had never seen this error before, since that xapian-bridge code hadn’t been changed for several release cycles now. What had changed this time round was that the part of the codebase that actually handled these queries client-side had recently been ported from JavaScript to C. Grepping through that code base for any sign of the ‘limit’ field, we came across this line:

g_autofree gchar *limit_string = g_strdup_printf ("%d", limit);

The limit field had always had a GObject type of unsigned int, yet here we were treating it as a signed int. Back when this codebase was in JavaScript this line didn’t even exist, because why explicitly convert each property in an object to a string when we can just call JSON.stringify() directly? In C that serialization had to be done manually, and in doing so we mischaracterized an unsigned integer as a signed one. That’s why -1 was even getting sent to the xapian server in the first place – it never happened under Javascript because Javascript isn’t as low-level as C and hence never needed to ask us whether this was a signed integer or not – it ‘just knew’.

Patching this code up was a mere one character change (switch %d to %u ). Last, but not least we fixed the original query to request GLib.MAXUINT32 as its limit. Even though our server now gracefully handled the -1 value, it had always been bad practice to rely upon it. The fact that when I first delved into the code I found that line confusing seemed justification enough to clean it up.

So that was it: three separate bugs, working in tandem to produce this baffling, processor dependent result. I found the entire saga illuminating not only as regards to computer architecture but to the power of paired – or in this case quartet – programming. Each step along the way went faster because someone on our team had domain-specific knowledge that could be shared with the rest of the group. Here’s to more collaborative coding!

Reflections on the political crisis in Brazil: Part 2

Eight months ago I wrote a piece about the current turbulent political situation in Brazil. Since then the drama has hardly let up, and even relative to the political rollercoaster that is 2016 it’s been fascinating. I thought I would record some of it again, for those who may be interested in the trials and tribulations of this Latin powerhouse.

We left off with President Dilma Rousseff, the first female president in Brazil’s history and a member of the once very popular Worker’s Party (PT), facing a key impeachment vote before Congress. A small cabal of senators charged Dilma with violating a rather esoteric and obscure budgeting law written into Brazil’s constitution. As far as I can tell no one understands the law, not even the senators, and no one can explain, concisely and completely, how Dilma broke it, but the general gist of the matter is that she manipulated the government books to conceal or at least understate the true size of the nation’s public debt. The accusation claims she did so deliberately in the run up to the 2014 election in order to win more votes. Dilma of course denies all of this and contends, not without good reason, that the entire impeachment has been orchestrated by her right-wing opponents to remove her party from power – something they’ve been unable to do at the ballot box in over 12 years.

In any case, whatever one thinks about the merits of the charge itself, the actual impeachment proceedings, held on April 17th in the Chamber of Deputies, Brazil’s lower legislative house, turned out to be a rather amusing display of pomp and buffoonery. Brazilian politics is already quite a messy, passionate ordeal, but with the stakes this high, it turned into a circus. Deputies were yelling at each other, waving banners, and chanting the entire night. At times scuffles broke out on the floor as people tried to press their way to the lectern to speak. Much to the embarrassment of many Brazilians, the entire 11-hour session was broadcast live on Brazilian TV and is on YouTube for the whole world to watch. Presiding over the whole affair with calm determination was Eduardo Cunha, President of the Chamber of Deputies, and the man labeled Dilma’s “nemesis” for his role in architecting the impeachment. Cunha called each of the deputies up one by one to declare their vote and provide a brief explanation for why they were voting the way they were. Almost invariably the (usually male) deputy would dedicate his vote in favour of impeachment to some combination of ‘God’, ‘my beloved country’, and ‘my family’. Some felt the need to mention each of their family members by name, with one man, Marcelo Álvaro Antônio, listing each of his children, but, rather embarrassingly, forgetting one son. Realizing to his horror the mistake he had made later in the evening, Marcelo hurried back to the lectern, interrupting the deputy whose turn it was, to state : “Just to correct one thing: I didn’t mention my son, Paulo Henrique: Paulo Henrique this is for you my son!”  Others used their time to rail against the vague menace of ‘corruption’. Hardly anyone referenced the “Fiscal Responsibility Law” (Lei de Responsibilidade Fiscal) which Dilma is alleged to have breached, and none noticed the irony in the fact that 150 members of their own chamber (the majority of whom voted for impeachment) were implicated in crimes far more severe than the one they so sanctimoniously charged Dilma with. Of course, there was righteous indignation – a sentiment to which the Portuguese language seems particularly well-suited – on both sides. Glauber Braga, a socialist deputy from Rio, used his time to call Cunha a “gangster”. Jean Wyllys, a left-wing firebrand and rising star in Brazilian politics, went even further and, in what became one of the most cited speeches of the event, proclaimed the entire proceedings to be a “farce” that was being “conducted by a thief”, “urged on by a traitor”, and “supported by cowards”. Draped in his signature red scarf, Wyllys had to speak louder and louder as his speech went on in order to be heard over the rising din. By the end he was practically screaming:

In the name of the rights of the LGBT population, of the black people and those exterminated [by police] in the favelas, of the culture workers, the homeless, the landless, I vote against the coup! And sleep with that, you bastards!

Jean Wylyss, a socialist deputy from Bahia and the second openly gay member of the Chamber of Deputies, speaks against the impeachment of Dilma Rousseff.
Jean Wyllys, a socialist deputy from Bahia and the second openly gay member of the Chamber of Deputies, speaks against the impeachment of Dilma Rousseff.

Perhaps the most shocking and unforgettable moment of the night came when Jair Bolsonaro, a polarizing, right-wing demagogue, took to the stand and dedicated his vote in favour of impeachment to Carlos Brilhante Ustra, a recently deceased colonel who led the notorious Doi-Codi torture unit during Brazil’s military dictatorship. Ustra’s unit was responsible for rounding up and torturing some 500 suspected ‘left-wing terrorists’, including the then young student Dilma Rousseff. In response to Bolsonaro’s ugly move, Jean Wyllys pushed through the crowd and spat on him, which led to fisticuffs breaking out between the two men’s supporters.

Jair Bolsonaro dedicates his vote for the impeachment to Carlos Brilhante Ustra, a recently deceased colonel who led the notorious Doi-Codi torture unit during Brazil’s military dictatorship.
Jair Bolsonaro dedicates his vote for the impeachment to Carlos Brilhante Ustra, a recently deceased colonel who led the notorious Doi-Codi torture unit during Brazil’s military dictatorship.

In the end, with 367/513 votes, the ayes cleared the ⅔ majority they needed to pass the motion of impeachment. The bill then moved to the senate, who, on May 12th, also passed it, though with much less fanfare. Dilma was now suspended for 6 months while they prepared and conducted the actual trial to determine her guilt. In the meantime, her vice president, Michel Temer, took over. In Brazil vice presidents need not (and indeed often are not) from the same political party as the president, although they do run together on the same ticket. Temer is from the Brazilian Democratic Movement Party (PMDB). A sidenote here: Brazilian political parties are very different from their counterparts in the more ‘developed’ world. Brazilian democracy is very young and, therefore, most parties have not had time to carve out a clear political and ideological territory. As a result, there are literally dozens of active political parties in Brazil – in the Chamber of Deputies alone no fewer than 25 parties are represented – and, unlike in the US or the UK, most ordinary citizens do not describe themselves as being more loyal or more committed to one particular party. No one really has a clear idea of what each party stands for and often even educated, well informed citizens have trouble remembering which politician belongs to which party, simply because it doesn’t seem to make much of a difference in how that politician will vote. The party names also are of no guidance: The “Progressive Party” tends to be pretty conservative and right wing; the Brazilian Women’s Party has exactly one deputy in the Chamber, and he is a man.

Michel Temer assumed the presidency of Brazil after Dilma was impeached. Critics accuse him or helping orchestrate the impeachment for his own personal political gain.
Michel Temer assumed the presidency of Brazil after Dilma was impeached. Critics accuse him or helping orchestrate the impeachment for his own personal political gain.

Supporters of Dilma have long accused Temer of helping orchestrate what they describe as the “illegal coup” against her in order to put himself in power. Suspicions intensified when, just hours before the vote to begin the impeachment trial, Temer committed one of those faux pas we all dread: he accidently sent an audio message to an entire WhatsApp group, when he meant to send it to just one friend. The message appeared to contain parts of a speech which he would give once he assumed the presidency. Given that at that point the country had not yet even opened the case for impeachment proceedings, let alone convicted Dilma, such a prepared speech seemed strangely presumptuous. Temer lost even further credibility when it emerged via Wikileaks that he had, since 2006, been acting as something of an informant for the US government, passing detailed reports and information on the current political situation in Brazil to US Southern Command in Miami. Never forgetting the key role that the Johnson administration had played in the 1964 military coup that had overthrown their first attempt at democracy, many Brazilians regarded these revelations as evidence of treachery and became even more convinced that Dilma’s impeachment was essentially a coup without the tanks.

Despite these setbacks, and with a poll showing that only 2% of Brazilians would vote for him in an election, Temer assumed the presidency. His first move was to establish a new cabinet. What ought to have been a fairly procedural affair blew up into a political firestorm. He appointed a creationist to head the Ministry of Science, and a ‘soybean tycoon who has deforested large tracts of the Amazon rain forest’ for his agriculture minister. What really angered people, however, was that Temer’s cabinet was the first in decades to feature only white men. Coming right after the ousting of what had been a remarkably diverse administration, led by Brazil’s first female president, such a decision seemed like a slap in the face to Dilma’s legacy. The impeachment had already been tinted with sexist overtones – “Tchau querida” (“Goodbye dear”) had become a popular slogan for those wanting Dilma out – and Temer’s cabinet picks seemed only to normalize that. It didn’t help Temer that in the same month Veja, a popular news magazine, published a feature special on his wife, Marcela, a 28-year-old former beauty pageant winner, which they titled ‘Marcela Temer: bela recatada e “do lar” (beautiful, demure, and of the home)’. In it, they praised Marcela for being the type of girl who “wears knee-length dresses”. Those furious at this sexist interpretation of a woman’s place in society were quick to respond with a flurry of memes on social media, posting pictures of strong feminist icons, past and present, captioned (ironically) with the phrase “bela, recatada, e do lar”.

Michel Temer with his wife, Marcela.
Michel Temer with his wife, Marcela.

In terms of actual policy, Temer immediately pursued a program of harsh austerity and neoliberal economics. His administration abolished several ministries, including the Ministry of Women, Racial Equality, and Human Rights, as well as the Ministry of Culture, though the latter he was forced to reinstate 11 days after he dissolved it in response to angry, yet creative protests by a variety of artists and musicians. More troublingly, he pushed through a constitutional amendment that freezes government spending for 20 years. Characterized by UN officials as simply “an attack on the poor”, the PEC55 policy, as it is known, prevents future governments from softening or undoing the austerity, thereby locking in a right-wing economic agenda for two decades and jeopardizing many of the gains made in poverty reduction during the Lula years. The measure fails to even take into account increases necessary to support a rising population, meaning that per capita spending on things like education and healthcare are expected to fall. Despite Temer’s promises that it is the shock therapy Brazil needs to climb out of recession, Brazilians have taken to the streets to protest what Vox dubbed “the harshest austerity program in the world.” The police response – in contrast, some have noted, to how police responded to the Dilma protests – has been swift and unrepentant: firing tear gas and pepper spray at unarmed protesters and blinding at least two journalists with rubber bullets.

A protestor holds a sign saying "Out Temer! Out everyone!". Her shirt says "No to PEC55".
A protestor holds a sign saying “Out Temer! Out everyone!”. Her shirt says “No to PEC55”.

As one of the groups expected to be hardest hit by the spending cuts, students have formed the vanguard in many of these protests. Even before PEC55 kicked in, state governments in Brazil had, of their own volition, been ordering the closure of dozens of schools across the country, in an effort to consolidate resources. Faced with the prospect of having now to attend overcrowded schools further from home, students resisted the closures by occupying hundreds of school buildings across the country, refusing to leave until their demands were met. The national austerity program has only exacerbated the students’ plight, and led to more vociferous protest. In October, sixteen-year-old Ana Julia, one of the students involved in the sit-ins, delivered a speech to the senate in her home state of Paraná. Opening with the words “Who is school for?”, she embarked on a lengthy tirade, defending the legitimacy and necessity of the student occupations and lambasting the legislators for failing to address student needs. She also attacked as “insulting” a recent government initiative escola sem partido, which forbids political discourse in public schools. The senators remained silent and attentive throughout, albeit with looks of mild annoyance at being lectured to by a girl who, for most of them, was young enough to be their granddaughter. When she decried them for having ‘blood on their hands’ – a reference to a student who had recently died during an occupation – they could no longer contain their irritation. Some began to murmur disapproval, and one angrily shouted back “my hands aren’t dirty!”. At this point the president of the senate stepped in, and reprimanded Ana Julia, reminding her sternly “You can’t attack parliamentarians here…here no one has hands stained with blood.” The sixteen year old apologized, but then retorted by quoting the Statute of the Child and Adolescent, which proclaims that “responsibility for our adolescents lies with society, the family, and the state.” At this the public crowd in the gallery erupted in applause and Ana Julia’s video soon went viral. Cries of “Ana Julia me representa” resounded across Brazilian social networks.

Ana Julia defends the student protests before a senate hearing in her home state of Parana.
Ana Julia defends the student protests before a senate hearing in her home state of Parana.

Meanwhile back in the nation’s capital, the ‘Lava Jato’ corruption investigation, which is what had first triggered this political crisis, continued to draw ever more powerful politicians into its proverbial noose. Eduardo Cunha, the man who conducted the impeachment proceedings against Dilma, was arrested and charged with accepting $5 million in bribes from a company bidding on state contracts. As the man most responsible for ousting Dilma, his arrest was greeted with unabashed glee by supporters of her party, especially since he had once vehemently sworn that he would ‘walk to Curitiba [the city from which the investigation was being run]’ if they ever found any real evidence against him. Brazilian meme artists had a field day with this quote and the photo of Cunha being escorted out of his home by federal police.

Eduardo Cunha, the former head of the Chamber of Deputies, was arrested on October 19th.
Eduardo Cunha, the former head of the Chamber of Deputies, was arrested on October 19th.

Next on the chopping block was Renan Calheiros, the canny yet uninspiring president of the federal senate. The Lava Jato team charged him with embezzling government funds and using them to support a daughter he had fathered via an extramarital affair with a journalist. Although his case is yet to reach a conclusion and he denies all charges, a federal judge ordered Calheiros to resign, on the grounds that one cannot be in line for the presidency (as head of the senate he is second in line until Temer appoints his own vice) while being under federal investigation. Calheiros spurned the judge’s order, insisting he would stay right where he was. His refusal sets an alarmingly dangerous precedent – that lawmakers can simply evade and defy the rulings of Brazil’s judiciary, in blatant contravention to the separation of powers principle ingrained in the country’s constitution. The same judge, Justice Marco Aurelio Mello, described Calheiros’ defiance as “inconceivable” and “grotesque”. Calheiros, however, knew he had the tacit support of President Temer, who needs him in the senate to help push through his economic agenda – if Calheiros were to fall, Jorge Viana, a senator from the leftist Worker’s Party and a key ally of the ousted president Dilma, would take over as head of the senate and would no doubt give Temer more resistance to his austerity legislation. After a tense exchange of ever more trenchant rhetoric between the Senate office and the judiciary, the case went to the Supreme Court, who softened Judge Mello’s ruling, allowing Calheiros to remain at his post but still forbidding him from ascending to the presidency in the (not unlikely) event that Temer is forced to resign.

Renan Calheiros, the president of the Brazilian Senate.
Renan Calheiros, the president of the Brazilian Senate.

With Cunha and Calheiros both brought to heel, it became clear firstly that the Lava Jato had no intention of closing shop just because Dilma was gone, and, secondly, that no politician was too powerful to be beyond their reach. Those two facts simultaneously overjoyed the Brazilian populace, and terrified the rest of the political elite. It got to the point where almost every day another politician was charged with some form of fraud or corruption and dragged (sometimes literally kicking and screaming) to a federal prison. But Brazilian politicians are a shrewd and wily bunch, and they were not about to just sit back and wait for the maw of justice to close around them. Something had to be done.

The first was that, just after Temer formally took office, the senate very quietly passed a measure granting executive branches of government much more leeway over budgetary adjustments. The blandly named Law 13.322 allows state and federal administrations to increase spending on a particular budget item, beyond what was originally planned, as long as they took the extra funds from another area of the budget. The Brazilian constitution is in general pretty strict about ensuring that government spending sticks to its planned budget and does not deviate from the amounts defined therein. This law would ease some of those restrictions, and, recognizing that economic priorities can change as events unfold, gives governments much more flexibility to adapt spending to meet changing demand. It all sounds quite sensible, but what is rather peculiar about this measure is that it is this practice – namely, unilaterally borrowing from one part of the budget to add more funds somewhere else without legislative approval – that this same Senate impeached Dilma for just one week prior. Moreover it was Dilma’s administration who originally proposed Law 13.322; had it passed when she was in office, there would have been no grounds for impeachment at all. This is not to excuse the fact that what Dilma did was at the time legally dubious, but it does make one wonder what these senators were thinking when they so piously railed against Dilma’s financial imprudence and corruption, if they were going to make what she did legal just one week after. The answer of course, is that these politicians are now desperately trying, ex post facto, to patch the gaping hole in their argument, which is that these accounting tricks, while not completely above bar, had been used, and are still being used, all around Brazil at all levels of government. To be consistent, Dilma’s opponents would have to also throw out all the state governors who did the exact same thing. A lot of those governors are friends or political allies of theirs, so they don’t want to do that. The only solution, therefore, is to be inconsistent, and hurriedly try to shield their comrades from suffering the same fate they just leveled against Dilma.

Having patched the hole they had pushed Dilma through, Brazil’s congressmen then moved to stymie the Lava Jato investigation. While the country was distracted mourning the death of an entire football team in an airplane crash, Brazil’s lower house frantically rewrote an anti-corruption bill to introduce penalties against judges said to have abused their power. They didn’t mention him by name, but the obvious target of the measure was Sergio Moro, the regional judge who is spearheading the Lava Jato investigations. Critics of the bill warn it would “erode the independence of the judiciary.” The chamber also edited the law to maintain certain statute of limitations which will ensure that many of their corrupt members will avoid jail time. The end result would be to make Lava Jato toothless. In response, Brazilians have taken to streets yet again in protest, many of them donning banners proclaiming support for Sergio Moro.

Judge Sergio Moro, the man spearheading the Lava Jato investigation, is seen as a national hero by many Brazilians. Critics say he is overstepping his authority.
Judge Sergio Moro, the man spearheading the Lava Jato investigation, is seen as a national hero by many Brazilians. Critics say he is overstepping his authority.

And that’s where we are now. Brazilian politics continues to lurch from crisis to crisis, with an overall mood that is at once both depressing and terrifying. There are a troublingly growing number of calls for a return to military rule, as well as serious threats of secession from southern states in the country. Having managed to keep its image together for the Summer Olympics, Brazil has hit turbulence again, and is still plagued by economic stagnation. Cynicism, especially about politics, is as Brazilian as football and cachaça, and this year has only reinforced that. I hope that 2017 gives the people of this wondrous country reason to buck that tradition.

Dual problems in dual boot

Background

At Endless we distribute an installer that enables users to run both our own OS and Windows side by side, in a setup commonly known as dual-boot. Dual-boot allows users to try out our OS on their own hardware, without giving up the Windows system with which they are familiar or which they need to retain in order to run some Microsoft applications. A dual-boot enabled computer will, after powering on, display a simple menu screen, at which point the user can select which OS to run.

A grub menu screen showing two boot options: Endless OS and Windows

A grub menu screen showing two boot options: Endless OS and Windows

Most dual-boot installations work by overwriting the bootloader. You can think of the bootloader as the prima causa of all the software running on your computer. Every other piece of software that gets run (including the OS itself) must be loaded and executed by some other piece of software. The chain of causation stops at the bootloader, our unmoved mover. It sits right at the beginning of a hard disk, in the boot sector, and our hardware is physically configured to run whatever binary code is in that boot sector on startup.

What the Endless installer does is write into that boot sector a program called GRUB, the GRand Unified Bootloader, which, as you might guess from its grandiose title, is a powerful and flexible tool which coalesces into one program the ability to boot a variety of free operating systems, including Endless OS. Of course, one of the operating systems it does not know how to boot is Windows, so to get into Windows we use a process called chainloading. Before we write GRUB into the boot sector, we first copy out what was already there – namely, the Windows bootloader – and save it on the Windows partition. When a user chooses to boot into Windows, GRUB hands over control to the pre-saved Windows bootloader (this is the part known as chainloading) and the Windows boot sequence can begin.

Immediately after the boot sector usually comes the partition table, where information about the size and location of each of the disk’s partitions is stored. Most systems have four partitions, though more advanced ones can have as many as 16.

The structure of a Master Boot Record (MBR) showing the bootstrap code and the subsequent partition table entries. (Wikipedia)
The layout of a disk drive, showing the boot record at the start.

The layout of a disk drive, showing the boot record at the start.

Unlike some other Linux distros, such as Ubuntu, Endless does not create a separate partition on which to place its OS image. Rather, we stick the image into the C: drive of Windows itself, extending it to provide adequate space for the OS to work with, and hiding it with ACLs so that the user does not accidentally delete it while back on Windows! In fact, what we put in C: is an entire endless directory, which contains the endless.img image file, as well as a GRUB subdirectory with the grub.cfg file required to complete GRUB’s boot process. To identify the C: drive, GRUB looks for that partition which has the \endless\endless.img file on it. Once the partition is found, it can retrieve the grub.cfg file and complete the boot process. To boot into Endless, we launch the kernel, passing it these extra parameters:

endless.image.device=[id for partition holding endless.img] endless.image.path=/endless/endless.img

The disk layout on a computer with Ubuntu and Windows in dual boot.

The disk layout on a computer with Ubuntu and Windows in dual boot.

The disk layout of a computer running EndlessOS and Windows in dual-boot.

The disk layout of a computer running EndlessOS and Windows in dual-boot.

As one might have surmised, because we are modifying the part of your computer that actually boots the rest of the OS, the stakes are rather high. In contrast to a bug in application code, which might – at worst – crash the application but leave the rest of your system intact, a bug here could render your entire computer unbootable. You could turn it on, but instead of an OS you would just get a dreary GRUB error screen. That is exactly what happened to a user of ours here in Brazil.

The Problem

A user reported that he had completed the installation process, but, upon reboot, had hit a black screen with a cryptic GRUB error message.

This error screen appeared after a user installed Endless and rebooted.

This error screen appeared after a user installed Endless and rebooted.

By examining the log file of another computer which had hit the same problem, we were able to figure out what went wrong. What appears to have happened is the following: our user completed the installation process successfully, but then, before exiting the installer, he closed his laptop lid, which puts the computer ‘to sleep’, or, more technically, tells Windows to broadcast a PBT_APMSUSPEND event signal to currently running applications. Closing the laptop was of course a perfectly reasonable thing to do, but due to a bug in our installer code, this signal caused the installer application to move into an error state, and when our user reopened his laptop lid later in the day, he saw the installer on an error page:

 22:06:48 - Analytics: response code 200
 22:20:17 - Received WM_POWERBROADCAST with WPARAM 0xA LPARAM 0x0
 01:40:39 - Received WM_POWERBROADCAST with WPARAM 0xA LPARAM 0x0
 01:40:40 - Received WM_POWERBROADCAST with WPARAM 0x4 LPARAM 0x0
 01:40:40 - Received PBT_APMSUSPEND so canceling the operation.
 01:40:40 - EndlessUsbToolDlg.cpp:4174 CEndlessUsbToolDlg::CancelRunningOperation
 01:40:40 - DownloadManager.cpp:439 DownloadManager::ClearExtraDownloadJobs
 01:40:40 - CEndlessUsbToolDlg::CheckInternetConnectionThread cancel requested
 01:40:40 - DownloadManager.cpp:452 Error calling EnumJobs. (GLE=[0])
 01:40:40 - EndlessUsbToolDlg.cpp:4155 CEndlessUsbToolDlg::EnableHibernate
 01:40:40 - EndlessUsbToolDlg.cpp:1606 CEndlessUsbToolDlg::ChangePage
 01:40:40 - ChangePage requested from ThankYouPage to ErrorPage

The spurious error page prompts our user to “Retry” the installation, which he dutifully does, despite the fact that nothing was actually ‘wrong’ in the first place. The installer at this point stumbles upon a much more pernicious bug – namely, it fails to check that Endless is not already installed before starting to install it again; it plows right ahead, deleting our C:\endless file and recreating it again (unnecessary, but not by itself problematic), and then goes to install GRUB. When it looks in the boot sector for the Windows MBR to copy out, it sees that the bootloader there is not in fact a Windows one – it’s something else, something strange and unexpected that it doesn’t know how to deal with, so it aborts the installation process and deletes the C:\endless it had just created:

 08:02:50 - EndlessUsbToolDlg.cpp:5174 CEndlessUsbToolDlg::WriteMBRAndSBRToWinDrive
 08:02:50 - EndlessUsbToolDlg.cpp:5320 CEndlessUsbToolDlg::GetPhysicalFromDriveLetter
 08:02:50 - Opened drive \\.\PHYSICALDRIVE0 for write access
 08:02:50 - EndlessUsbToolDlg.cpp:5134 CEndlessUsbToolDlg::IsWindowsMBR
 08:02:50 - C:\ has a non-Windows MBR
 08:02:50 - Error: no Windows MBR detected, unsupported configuration.
 08:02:50 - EndlessUsbToolDlg.cpp:4993 Error on WriteMBRAndSBRToWinDrive (GLE=[87])
 08:02:50 - SetupDualBoot exited with error.
 08:02:50 - EndlessUsbToolDlg.cpp:4698 CEndlessUsbToolDlg::RemoveNonEmptyDirectory
 08:02:51 - Removing directory 'C:\endless\' result=0

The irony of course is that this ‘strange’ bootloader that our installer refuses to deal with is our GRUB installation that we put there in the first place! The computer is now, although still running, a dead man walking. Once you turn it off, it will never boot again, because it is stuck in limbo: it has a GRUB bootloader, but without the requisite C:\endless\endless.img file in place, GRUB can’t find the C: partition, and, hence, can’t find the rest of the code needed to complete the GRUB initialization process and boot into either Endless or Windows.

The Fix

As is often true with nasty, edge-case bugs like this one, the real work is in finding and reproducing it (and in that we were lucky to have the log file of a similarly affected machine). Once the nature of the problem is known, fixing it was quite straightforward. We cannot boot the machine from its internal disks, but we can boot from a USB. Once running on a ‘live’ Endless USB, we can do the repair work needed to get the system back into a coherent state. Concretely, we recreate the deleted C:\endless\ directory, and inside of it we put a blank endless.img file (so GRUB can find the partition) and a grub\ subdirectory (so GRUB can complete its execution). We can then power off the machine and remove the USB drive. Upon reboot, GRUB will now execute to completion and, since endless.img is just a blank file, will boot directly into Windows. From there we can run the uninstaller to clean everything out, then download a new version of the installer and do a proper install.

It is these two items, the endless.img file and the grub directory, that must be manually restored to the Windows partition in order for the computer to be bootable again.

It is these two items, the endless.img file and the grub directory, that must be manually restored to the Windows partition in order for the computer to be bootable again.

The new version of the installer has two important fixes to ensure this error does not happen again. Firstly, it will not show a spurious error page when the application receives the suspend signal; secondly, it will ensure that the error code path includes a check for whether C:\endless is already installed before embarking on the install process all over again. Had that check been in place, the installer would never have deleted endless.img the second time round, thus avoiding that dreadful ‘half-way’ state. This problem was, therefore, one of those curious oddities in software development where you have two bugs layered on top of each other: a glaring, catastrophic one hidden in the code path of a subtle, marginal one.

Reflections on the political crisis in Brazil

Notwithstanding Brazil’s position as the seventh largest economy and fifth most populous nation on Earth, its political crisis of late has received relatively little attention in the foreign press – or, at least, in the American and British press I follow. Part of that is no doubt due to the fact that both countries are fixated on their own respective political dramas: the US its presidential election, and the UK its upcoming referendum on  EU membership. Journalists and commentators have precious little ink to spare on the domestic turmoils of a ‘developing’ country, many thousands of miles away – not when they could be agonizing over the latest Trump or Farage gaffe for their readers.

Continue reading

On the Death Penalty

32 of the 50 states in the US still accept the death penalty as legal sentence for certain criminal offenses. Despite overwhelming evidence that the death penalty is an ineffective deterrent to crime and that it is grossly tainted with racism and other types of prejudice, the US has failed to abolish this medieval form of punishment nationwide. Globally, this puts the United States in strange company – most nations of the world have abolished the death penalty entirely, with a few notable exceptions: China, Iran, Iraq, and Saudi Arabia all maintain it, and lead the world (in that order) in the number of executions they carry out per year (the US comes in at 5th place, followed by Yemen and the Sudan, two other great beacons of freedom and social justice). These are all nations we in the West like to describe invariably as oppressive, ruthless states, and in at least two of them we have threatened or carried out forceful regime change in order to rid the world of their brutality. Yet when it comes to the most violent act a state can take against its own citizens – legalized murder – we stand shoulder to shoulder with them.

Attempts have been made to abolish the death penalty at the ballot in the US. In 2012, proposition 34 was put on the ballot for California voters, which would have abolished the death penalty in their state. At the time I was a student at Stanford University and I would occasionally drop in on public lectures and discussions, often led by Professor Lawrence Marshall (a lifelong opponent of the death penalty), regarding the Prop 34 campaign. Professor Marshall argued that although, in his mind, the chief reason to oppose the death penalty was that it was wrong in itself, it would be more effective when trying to convince the general public to make pragmatic arguments. It would be more prudent, for example, to point out that the death penalty cost California taxpayers a $184 million per year, or $308 million per prisoner executed, than to wax poetic about some sacrosanct, inviolable right to life. If the degenerates on death row don’t deserve life (so the argument would presumably go) then surely they don’t deserve all this money spent on them; much better to simply keep them locked away for life and we will all be richer for it. It was reckoned that this type of reasoning would especially appeal to the state’s conservative base, who would otherwise be most likely to back the death penalty. In order to win them over, Professor Marshall argued, we can just paint this policy – namely, capital punishment – as yet another failed big government program – ineffective, costly, and ripe for removal. I found this strategy to be quite perplexing for the following basic reason: if the roles were reversed; if it were the case that the death penalty were a much cheaper alternative to other forms of punishment, and death penalty advocates were trying to convince me to uphold capital punishment based on the fact that it would save the government hundreds of millions of dollars, I would not be swayed one jot from my position. And, moreover, I would be dismayed at anyone who was. How could you change your mind, on a question about the basic right to life of human beings, on the basis of fiscal responsibility? And I have no reason to believe that advocates of the death penalty are any less committed to their moral position than I am, so why would I expect them to be persuaded by the kind of pragmatic arguments at which I would scoff?

Proposition 34 was ultimately defeated in the November election, keeping the death penalty legal in California. However, in July 2014, Judge Cormac J. Carney of the United States District Court ruled that California’s death penalty was unconstitutional. In his decision, Judge Carney argued that the application of the death penalty violated the 8th Amendment prohibiting ‘cruel and unusual punishment’ since the legal process surrounding the death penalty was so “arbitrary and plagued with delay”. It’s a rather curious justification, since, like the arguments the Professor Marshall was advocating, it nullifies the death penalty based on what is essentially a minor incidental feature of it, rather than what is fundamental or necessary to it. What could have been said about the death penalty in America regarding its implementation, but what was conspicuously absent from Judge Carney’s decision, was its racist component. When most people hear about “racism in the criminal justice system”, they think that what must be being referred to is the fact that minorities are charged with and dealt out harsher sentences for the same crimes as whites. That’s certainly true, but, in a way, it’s perhaps not as disturbing as a less cited, but equally obvious fact: crimes in which the victim is black are punished less severely than crimes in which the victim is white, regardless of the race of the perpetrator of that crime. In fact, when it comes to the use of the death penalty, Amnesty International have concluded that “the single most reliable predictor of whether someone will be sentenced to death is the race of the victim.”

The message this sends is as clear as if it were emblazoned on the front of every courthouse in America: black lives are worth less than those of whites.

This point has been brought before the Supreme Court. In 1987, the Court heard the case of McCleskey v. Kemp, in which the petitioners presented statistical evidence from a scientific study, demonstrating the inherent racist slant of the death penalty’s application: “even after taking account of 39 nonracial variables, defendants charged with killing white victims were 4.3 times as likely to receive a death sentence as defendants charged with killing blacks”. The Supreme Court, however, upheld the death penalty, on the grounds that demonstrating a “racially disproportionate impact” was not enough to nullify the law without also demonstrating a “racially discriminate purpose”. The distinction here between a purpose and an impact is absurd: short of some district attorney coming out as openly racist, how on earth are you supposed to divine the ‘intent’ or ‘purpose’ of those administering a discriminatory policy? And why, moreover, is that relevant? There are many laws whose purpose might be benign, but whose application, because of the social environment in which they are administered, is monstrously unjust. That’s true of virtually every voting law enacted in the Jim Crow South, which kept blacks disenfranchised, all while hiding behind a veil of race-neutrality.

In any case, commendable as these efforts are to argue for the death penalty’s abolition based on its specific implementation as a practice in the U.S., they leave unsaid what ought to be regarded as the more important discussion – namely why the death penalty is intrinsically wrong – regardless of the way it is administered – as matter of principle. It is this subject I turn to next.

On Why the Death Penalty is Wrong as a Matter of Principle

It is a general rule, when deciding what rights to grant the state, or for that matter, any institution of concentrated power, to remember that the burden of proof is always on those wanting more power to justify why such power is necessary. It is not enough to simply point out some good that will be gained or some evil avoided by the appropriation of some power to the state – it must be shown that no alternative way of achieving that good or avoiding that evil might be found.

Legal theorists and philosophers generally provide four broad categories of justification for punishment of a wrongdoer. They are: deterrence, prevention, rehabilitation and retribution. I happen to take the position that only the last of these, namely retribution, provides a morally consistent justification for punishment (more on that later). But let us consider all the possible justifications in turn, and see if, under any of them, there is any merit to the claim that the death penalty is a necessary tool of criminal justice.

Consider first deterrence. It is a general consensus now among all but the most delusional advocates of capital punishment that the death penalty fails to deter crime any more than lifelong prison sentences. In fact, in America, states which enforce the death penalty tend to have much higher rates of violent crime than those which proscribe it. There’s a quite obvious explanation for this: the kind of person who is willing and able to commit the kinds of crimes for which the death penalty would be given (e.g. murder, violent rape etc) are probably not going to be the ones thinking carefully about what their eventual punishment will be (if they even believe they will be punished at all). Take, for example, the case of Michael Taylor , a Missouri inmate executed in February 2014. He was convicted of raping and murdering a 15 year old girl while high on crack cocaine. Do we really believe it ever crossed Mr. Taylor’s deranged, sadistic, drug-induced state of mind that perhaps he shouldn’t commit that crime because he would be eligible for the death penalty if he did so? Almost by definition, the death penalty applies to crimes so shocking that the perpetrator could not be thinking rationally about the consequences of his/her action. That’s why we see the death penalty being such a poor deterrent to violent crime.

Prevention is the idea that inflicting a punishment on someone will prevent that same person from committing the same (or a different) crime again. This is different from deterrence which focuses on preventing others from committing crimes in the first place. There’s no doubt the death penalty is an effective tool of prevention – dead people can’t commit more crimes. But it is no more effective than life imprisonment, which also prevents the wrong-doer from committing more crimes, but without granting to the state the right to kill.

Rehabilitation, though usually not a high priority for those who claim to be ‘tough on crime’, really ought to be. It is the idea that punishment can serve as a way to make someone a better person: educate them, give them a more uplifting moral character, perhaps cure or at least treat their possible drug addictions, all in the hopes that this will make them a better human being, less likely to commit crimes in the future. People killed by the state of course have no opportunity for rehabilitation, so it could never be provided as a justification for the punishment itself. As it happens, rehabilitation for the benefit of the inmate rarely receives even token acknowledgement in the US. But even if you don’t care about the inmate and are concerned only with ‘reducing crime’, you ought to care about rehabilitation: in the United States, almost half of the inmates who are released from jail go back to committing crime. If people were serious about wanting to reduce crime in society, then rehabilitation would be the primary focus, and resources would be directed towards that end.

Retribution: the idea that the criminal deserves, as a matter of intrinsic justice, to be punished in a manner proportional to his crime. It is not particularly relevant, retributivists might say, what contingent benefits or harms might come from the punishment – what justifies it is that it is a counteraction to the wrong deed itself. Incidentally, I consider myself a retributivist: that is, I believe that the sole justification for punishment must be to correct the wrong itself. Any other justification, which focuses on other desirable ends, treats the criminal as a means to those ends. It treats him not as a rational being, afforded basic moral rights, but as a thing – a thing to be used to further some other chosen end (in this case, a supposedly better society). But according people proper human dignity means treating them as ends in themselves. Furthermore, non-retributive justice provides no coherent limitations to how harsh our sentencing ought to be. Suppose, for example, that the only way to prevent jaywalking was to punish it with death. Well, if your justification for punishment is deterrence, then you would have to concede in that situation that the death penalty is an appropriate punishment for jaywalking, which is plainly absurd. Only by grounding your justification for punishment on retribution can you argue that a punishment must be proportional to the crime itself.

It is important to recognize, however, that while retributive justice provides a much needed consistent theory for the justification of punishment, it does not afford (nor even imply) a right for any one particular person or entity to carry out that punishment. In particular, it does not grant the state the power to do so. This is an important distinction. The state ought not be an enforcer of ethics, and although a moral wrong may deserve some kind of punishment, the state (or any person in it) does not have the right to inflict that punishment merely because it is a moral wrong, or merely because the punishment would be morally right. The state ought only use its power to further what Hegel called the ‘coercive protection of right’ – that is, to protect the civil rights of its citizens; hence the state ought only punish crimes where there is a compelling public interest to do so (this is where we can start entertaining ideas about deterrence and crime prevention, though, as we established above, none of those ideas provide a justification for choosing the death penalty over life imprisonment).What does this mean for the death penalty? Well, there are perhaps some people currently on death row who deserve to die – you can think here of serial killers, child rapists, what have you. Perhaps, as a matter of intrinsic justice, they have forfeited their right to life. That is not the question that is before us with regards to the death penalty. The question before us is whether the state has the right to be the supreme arbiter and executioner of that punishment. The answer there is an emphatic no. Executing one of its own citizens does nothing to further the ‘coercive protection of right’ for society – in fact, as Winston Churchill (allegedly) put it “if you kill the murderer the quantity of murders will not change”. Society becomes more, not less, barbaric when the state has a hand in the killing of its citizens.

One may of course be left troubled that this leaves us in a world where wrongs are not justly righted, and where criminals don’t receive their full comeuppance. Well, theists among us can of course rest assured that, unlike the state, God can and should enforce moral law and hence all wrongs will be appropriately punished through His divine judgement. For the unbelievers, well, accepting that not all wrongs can be punished is just one more agony to tack on to the anguish of enduring the human condition in a godless world. Besides, there are much worse things in the world to face than unpunished wrongs, and that would include living in a state which had the power to punish them.

Punishment must be grounded in retributive justice because only then can we have punishments that are morally proportionate to the crime. It does not follow, however, that because a punishment would be proportionate, and thus morally right, that the state has the power to inflict it. The state ought concern itself only with the specific protection of civil rights, and, within that framework, can only carry out a certain punishment if all other punishments emanating from a lesser degree of state power would be inoperable. Under this theory, the death penalty is never justified, and is therefore wholly wrong as a matter of principle.

On “New Atheism”

How, if at all, should we criticize religion and religious convictions? For large swathes of the population, especially in the more liberal hubs of North America and Europe, religious conviction has been treated with a mix of apathy and polite tolerance. For most of these people, religion forms no part of their daily routine – they do not pray, or regularly attend a place of worship – and yet they will rarely actively criticize or even comment on religion, despite the shockingly dominant influence it has over our nation’s politics, touching everything from foreign policy to domestic social issues. According to a recent poll, 15% of Americans claim no religion, yet only 0.7% were prepared to say that they were atheist. The discrepancy here I think can be put down to the belief that an outright rejection of religion might attract accusations of intolerance, and this seems too high a price to pay in a debate about something which to them is of so little consequence.

Perhaps the worst fallout from this general apathy towards religious criticism, is that the criticism does not go away, but is instead taken up and perverted for all the wrong reasons. The standard critique of religion today is to attack it on consequentialist grounds. The so called ‘New Atheists’, led by Richard Dawkins, Sam Harris, and the late Christopher Hitchens, argue that religion has a definitively negative impact on society. Such writers aim their sights especially at the religion of Islam, charging it with being at the root of all Islamic extremism. Domestic terrorist attacks, they claim, can be traced to the fanaticization of muslim youth by radical clerics; Wahhabism, the ultra-orthodox branch of Sunni Islam, accounts for the systematic oppression of women in Saudi Arabia and other Arab countries. Clearly such a view quite unapologetically paints a complicated issue with a broad brush, and in many instances has been employed or invoked in order to justify or advocate for some of the more reprehensible acts of neo-conservative foreign policy. By identifying Islam as the underlying and sole cause of terrorism, we can conveniently ignore the many other reasons – the occupation of their land, bombing of their children, and theft of their natural resources – that might prompt people who happen to be muslim to seek violent reprisals against the west. The fact that it is often these political reasons, and not religious ones, that the perpetrators of terrorist acts themselves invoke as a justification seems to be oddly irrelevant to those who want nothing more than to find common cause in all manifestations of extremist violence.

These consequentialist attacks on religion do not limit themselves to Islam (though Islam does seem to bear the brunt of the assault, despite Muslim countries being far more likely to be on the receiving end of Western violence than vice versa). According to the so-called “New Atheists”, one need only look to the sexual abuses by priests to see why Catholicism is wrong, and to the unwillingness of orthodox Jews to compromise on the Palestinian question to see why Judaism has its own pernicious effects. No religion, it is claimed, is free of its dirty secrets, and it is precisely because of these that we must reject religion in its entirety from our civilization.

New Atheists also go to great lengths, of course, to explain why religious beliefs are wrong, and take enormous pleasure in pointing out how many fundamental tenets of the major religions (virgin birth, omnipotent Gods) can be shown to be nonsensical by science and logic. However, the false beliefs of these religions are rarely viewed as harmful in themselves – it is instead the terrible implementations of those religions on Earth that are seen as having such negative effects on society.

This type of attack on religion is flawed for two reasons. Firstly, it is not clear that, on net, the institution of religion has had a negative effect on society; secondly, it attacks religion only on what is incidental to it, rather than what is necessary to it. I will explain each of these points below.

Why religion might not have, on net, a negative effect

Every ideology is susceptible to human perversion, and man-made religion is certainly no exception. There is no doubt that countless people have lost their lives in the name of religion, and that there is not a major religion in the world that has not been complicit in crimes against humanity. But if we are to lay the crimes of individual zealots at the Church’s steps, then we must also lay there the countless acts of kindness and generosity done by equally fervent adherents to those faiths. It would be a extraordinarily biased assessment of religion indeed if we did not also acknowledge the incredible amount of good that religion has done for the world. Before the advent of the modern welfare state in the post war period, it was the Church, and religious institutions in general, which took on the task of caring for the poor and tending to the sick. Religion has provided solace to many in times of despair and desperation. The strong social bonds that religion has fostered in local communities has also often helped fuel political change. The Civil Rights movement in the United States was born and nurtured in southern, black baptist churches. Sunday sermons provided a venue where blacks could organize, vent grievances, and agitate for changing the political system. Similarly, in South America, it was priests of the Catholic Church who often stood bravely on the side of oppressed masses against right-wing dictators. People like Oscar Romero helped develop liberation theology, which sought to bring Christianity back to its true roots, namely as a champion and defender of the poor and of the oppressed.

Of course, an objector can dismiss these cases as simply examples of good people, who happen to be religious, doing good deeds. To credit Hinduism for Ghandi’s bravery, or Catholicism for Mother Teresa’s compassion, one might object, is to do a detract from the praise that is due to these individuals in their own right. I would, of course, be in agreement with such a view, but I would have then to insist that we take the same view with regard to those who commit immoral acts, also in the name of religion. Either one’s religion does bear some responsibility or credit for one’s actions, or it does not – we cannot have it both ways, and we certainly cannot just ignore the credit and focus exclusively on the guilt that organized religion has accrued over the centuries.

All of this is not to whitewash the very real crimes that have been committed by, for, and in the name of religion. It is simply to question how one could be so sure, given the masses of evidence on both sides, that religion is somehow bad in its effects, or that it has as a whole brought about more suffering than relief thereof in the course of human history. Critics like Hitchens and Dawkins love to point to specific verses in the Bible or the Koran, those which seem to (if read literally) condone barbaric violence, rape, and the cruelest forms of misogyny, as evidence that religion is inherently bad and could only ever be employed for evil. But there is also much in there that gives great comfort to many people in need, and indeed, parts of the New Testament contain some of the more beautiful expressions of social justice and human altruism that Western civilization has composed. To judge a religion solely based on those isolated sections is like those who want to dismiss all of Kant’s philosophy because he has written what we today consider outrageously racist remarks, or to condemn all of Aristotle’s work because of the offensive things he has to say about women. In all these cases, it’s just not clear what point the critic is trying to make, and how it bears any relation to how we judge the philosophy as a whole.

On what is necessary, and what is incidental, to religion

The much deeper reason why it is misguided to inveigh against religion based on its practice, is that this attacks only what is incidental to religion, and not what is necessary to it. For suppose religion rid itself of all violence, purged itself of all prejudice, of all hate, discrimination and medieval cruelty, would then, we as atheists have no more problem with it? Such an outcome is fathomable, since there is nothing analytically particular about religion which forces it to exhibit the extremism that it does today. Would we then perhaps treat religion as we now treat astrology: a foolish and unscientific practice, yes, but nothing harmful to society, and therefore, nothing that is in need of changing. If your answer is yes, then I would submit to you that perhaps you are not against religion at all, but are merely against the current implementation of religion, in the same way that those who are against American foreign policy are not at all against America, but merely opposed to some aspects of it’s current behaviour. I believe people have a right to their own views, and would not force anyone to give up this one, but don’t lump yourself in with those of us who would say no to this question, and who have a much more fundamental problem with religion in regards to what is necessary to it, namely the advocation of belief without sufficient evidence.

Religion is morally wrong because it violates a principle articulated by William Clifford in his essay “The Ethics of Belief”, namely that “it is wrong always, everywhere, and for anyone, to believe anything upon insufficient evidence.” Sufficient evidence showing that God(s) exists has never been presented in a manner that would come close to meeting our standards of scientific rigor. God has often been called upon by believers as an explanation to natural phenomena that scientific inquiry has yet to explain properly. The result of this absurd tactic is that God’s influence on the world seems to diminish in proportion to the advance of science, to the point that now God’s powers are basically defined to consist in those things to which science does not currently have complete answers, such as the origin of the universe or human consciousness. Some theists will accept (and indeed take delight in the fact) that belief in God does not rest on evidence, but instead is held purely on ‘faith’. While such a position does mean that they have at least maintained a semblance of a grip on reality and have not resorted to chasing millennia old fairy tales, it does mean that they now are in violation of Clifford’s principle, which we ought explore further.

Understood correctly, Clifford’s principle is not without controversy, and should not be adopted lightly by someone simply looking for a good reason to have another go at religion. There are many common-sense reasons why someone might think it is sometimes desirable to encourage people to hold an unsubstantiated belief. Oftentimes believing something despite a lack of evidence, or indeed in the face of contrary evidence, is reassuring and comforting to the believer. Thinking that you will get a better job despite knowing full well that such prospects are bleak, or believing that someone who has wronged you will get their just desert even when your legal courts have let them off can perhaps make you feel better about an otherwise unhappy situation. It does not seem clear, one might object, why these people should have an ethical duty to confront the cold reality, when that reality makes them feel miserable. If holding an incorrect belief makes them feel better about their situation, why ought they not cling to it – after all, it is only affecting themselves. This is an objection that many so-called liberals like to raise; it is in keeping with their position that society (and especially government) should be neutral on conceptions of the good, and should not intervene in affairs that do not bring harm to ‘other people’. I would first say that I find such a position to be strangely cold-hearted – a wrong act does not stop being wrong simply because the only victim is also the perpetrator. And secondly, there are indeed very real harms, many affecting others, that come about when people fail to proportion their belief to the evidence. In fact any belief which is to have a meaningful effect on one’s life is likely also to affect with whom one shares that life. This is especially true of religious beliefs, since adopting them implies making significant changes in how you treat others.

Clifford’s own famous example was that of a shipowner, who sent out to sea a ship which he knew to be old and in need of repair. Despite the compelling evidence that the ship was not in a safe condition for travel, the shipowner chose to instead “put his trust in Provedence” and send the ship out with a number of families on board. The ship then sinks, sending to a watery grave all those onboard. Clifford insists that the shipowner is guilty of those deaths since, although he sincerely believed that the ship would complete its journey in one piece, he had “no right to believe on such evidence as was before him”. Moreover, Clifford adds, the owner’s guilt would be reduced “not one jot” if in fact the ship had completed its voyage successfully. What actually happens to the ship once it set sails is not up to him, and so clearly it cannot have an influence on his moral culpability. What was wrong was that he chose to adopt a belief despite the evidence against it – in other words, what was wrong was his decision to have ‘faith’.

Beliefs based on faith are simply forms of wishful thinking, and should be treated as an affront to your own dignity. We accept that people have ethical duties not to lie to others, and lying to yourself should not be treated any differently. Sometimes lying to others brings you some personal gain, just as lying to yourself can make you feel reassured, but we should accept neither as a justification for the wrongdoing. And what could be a more shameful lie than one told about your own mortality, and about the existence of an omnipotent deity? I agree that such a false belief brings great relief, since it is frightening and depressing to come to terms with your own mortality, or to accept that horrendously evil acts committed in this world will never be righted or punished. But to try to escape from the absurd and wretched condition we call human existence by giving in to superstition and deceit is to show no regard for your own dignity as a rational being.  Nothing other than self-contempt could be responsible for a person deceiving themselves in this way.

The violence and intolerance we see exhibited by religious persons is certainly wrong, but it cannot (indeed should not) be attributed to the religion itself. What certainly can be attributed to the religion itself is the total willingness on behalf of its devotees to believe without (indeed in spite of) evidence before them. In doing that they have violated an ethical duty – a violation which is in no way mitigated if the unsubstantiated belief they held did not lead them to commit bad deeds. One can imagine a world in which religion was free of all violence, but one cannot imagine a world in which religion was free of ‘faith’ (if you think you can then should reconsider what your definition of religion is) – that is what it means for violence to be incidental to religion, but faith to be necessary to it. We atheists should make sure that we are opposing what is necessary to religion, rather than what is merely incidental to it.

On Gaza

Amidst the war of words raging on in the media regarding the recent Gaza war, supporters of each side have tended to distill their vocal support into a handful of oft-repeated phrases. Having ready-to-go, prepackaged phrases like these make it easy to shore up support for your side, since people tend to think that if something is said often and loud enough, it must have at least some degree of truth to it. But that is precisely what makes these platitudes particularly damaging: they become so common-place and so easy to regurgitate, that newcomers to the debate enthusiastically adopt them without considering the validity of their content. In fact, when someone brings one up, it is an almost sure sign that they don’t have any arguments of their own to use to defend their position and so have resorted to using one of these ‘off-the-shelf’ arguments instead. The wide proliferation and constancy of these points does nothing to shore up their validity.

These aphorisms (for that is what they have become) tend to be either unsound – that is, they rest on dubious or outright false claims of fact – or they are invalid – the facts that are assumed do not lead to the purported conclusion. In this post I focus on the invalidity of the claims, not because the factual nature of them is any less important, but because I find that disagreements on fact are more likely to grind to impasse, since the two sides arrive at a fundamental disagreement about what authority they can trust to get facts from. Of course, inevitably, I must make reference to some facts, but I hope for the most part that they are those which are less controversial.

The first, and most popular claim, is that of Israel’s right to self-defense. It is asserted that Israel’s invasion and bombardment of Gaza is a response to the bevy of rockets fired at Israel by Palestinian militants. This line of reasoning is often summed up in what has become the trite phrase “what would any other country do if they had thousands of rockets landing on their territory?” The point here is, apparently, that Israel’s use of force is not excessive nor disproportionate, given the nature of the threat they face.

First, it should not be asked, what would another government do? The only morally relevant question is what would another government be justified in doing. National governments quite frequently violate not only basic moral principles but also the set of international laws to which they claim to adhere. The fact that we live in a world of excessive state violence does not excuse or absolve the actions of any one instance of that excess.

Secondly, to ask the hypothetical is this way is incredibly misleading. Yes, if rockets were being fired, unprovoked, from a neighbouring country, a government would (perhaps) be right to do what it could to stop them. But that is not what is happening here. Palestinians are retaliating to and resisting ongoing Israeli occupation of what the international community has declared is their rightful territory. So that hypothetical can only begin to make sense if you also stipulate that the country against which rockets are being fired has established a blockade around their neighbouring country, with the declared intention of putting the inhabitants on a ‘diet’ – that is, controlling the flow of food and and supplies into the territory, and only allowing in the bare minimum for the people to survive. The (now going on) 7 year blockade of Gaza is a grotesque form of collective punishment, imposed on the Palestinians for committing the grave crime of voting the wrong way in a free and fair election. Israel has no right to defend this blockade, and it is the blockade that Palestinians are trying to erase.

Putting it another way, perhaps the most obvious answer here is to simply turn the rhetorical question on its head, whereupon it takes on real power: “what would any other people do if they were trapped in the world’s largest open-air prison, subject to periodic invasions and bombardments by the one of world’s most sophisticated militaries?”. The answer, of course, is that they would resist. That is the desperate choice the Palestinians in Gaza have to make: they can either die slowly and miserably under the siege, or die giving their last breath to lift the siege that has forced them to live in this prison. I don’t know which one I would choose, but I do know that the existential problem inherent in that awful choice is a far more wretched one than that faced by Israel, for which we are supposed to show understanding.

Turning now to the specific issue of the rockets. The targeting of Israeli civilians by Palestinian militants is a grave crime, and the innocent civilians of Israel should be lamented over no less than the innocent civilians of Gaza. But as a whole, the rockets are miserably ineffective – described by the Guardian as little more than ‘useless fireworks’. This is not to trivialize the very real state of fear in which residents of southern Israel live because of the rockets, but it is to put them in perspective: four civilians (three Israeli citizens and one Thai national) were killed by rockets in the most recent attack. Over the same period, more than 1400 Palestinian civilians have been killed by Israeli warplanes and tank shells. So if we are to condemn Hamas for inducing a state of terror among Israelis, we must condemn 300 times over the IDF for the much stronger state of terror it imposes on the Palestinians.

People here will be quick to point out that it is the intention of Hamas militants to kill many more civilians, and that were it not for Israel’s Iron Dome system, which intercepted some rockets, many more civilians would be killed. I will come to the issue of ‘intention’ later, but with respect to the alleged efficacy of Iron Dome, it is worth pointing out that in the 2008-09 war, before Iron Dome was deployed, a similar number of civilians, namely 3, were killed. Either Iron Dome is not as effective as is claimed or (more likely) comparisons between the two scenarios are statistically meaningless precisely because the number of deaths in both cases is so small.

The next claim we hear is that Hamas uses its civilians as ‘human shields’ and that this tactic is what explains the large amount of civilian deaths on the Palestinian side. The blood of innocent Palestinians, it is said, is on the hands of Hamas, since they deliberately store rockets in Palestinian homes, knowing that Israel will bomb them, and that the resultant loss of innocent life will elicit sympathy for their cause. This argument is nothing more than a perverse form of victim blaming, and shows to what ludicrous depths the masters of war have to stoop in order to try to defend the indefensible. It is always and everywhere wrong to kill civilians, and when such a crime is committed, responsibility rests solely with the perpetrator of the crime. Hamas did not induce Israel to kill the four boys playing on the Gaza beach, nor did it induce Israel to drop bombs on hospitals and power plants throughout the Gaza strip. When families are killed in their homes at night, they tell us it is their fault for staying in their homes. Where are these people supposed to go? Putting aside the fact that the Gaza Strip is one of the most densely populated areas on Earth, where is anyone supposed to go when their land is under siege and being bombarded from above. A UN shelter? How would that have turned out?

I use the phrase ‘victim blaming’ quite deliberately, because it is also the tactic deployed to try to excuse or mitigate accusations of rape. It is tragic that she was raped, they say, but maybe she shouldn’t have been in that neighbourhood to begin with, when she knew it was dangerous; or maybe she shouldn’t have been wearing that outfit, or drinking those drinks. These (feebly transparent) attempts to shift blame from where it ought to reside serve only to confirm how distant from any consistent moral position apologists for crimes such as these have to go. It is a double injustice, since it first excuses the perpetrator, and, second, blames the victim herself!

It is also worth pointing out that to say that these resistance groups hide amongst the population is sort of a red herring: the resistance is the population. Hamas doesn’t have an army – they have fighters, drawn from the people in Gaza who have decided – incorrectly and unjustly, in my view, but nevertheless have decided –  that they must use violence to bring about some respite from the occupation under which they live. Just as the Vietcong in Vietnam, or the FLN in Algeria, or the Communist resistance in Nazi-occupied Europe, they are fighting to expel foreign forces from their land.

Now, those who don’t go so far as to try to blame deaths of Palestinians on the Palestinians themselves will still retort: well, the difference is Israel does not intend to kill civilians, whereas Hamas does. As Sam Harris put it, regarding the killing of civilians in Gaza “we know that this isn’t the general intent of Israel. We know the Israelis do not want to kill non-combatants, because they could kill as many as they want, and they’re not doing it.” We have to ask ourselves, however, what constitutes an intention. In so far as we cannot read minds and divine their ‘true intention’, we must accept that the inevitable and forseeable consequences of an individual’s action constitute an intention. Suppose as an act of malice you decide to set fire to part of the house of someone you don’t like. You don’t want to kill them – in fact, perhaps you believe them to be out of town – but you do want to commit serious damage. But then it turns out that the fire gets out of control, and that an entire family is sleeping inside, who all perish. Well, when you are subsequently brought before a magistrate, you cannot, at that point claim, well look, I didn’t intend to injure anyone with my act. Why not? Because the inevitable and foreseeable consequences of setting fire to a house is that you will injure someone. Once you choose to commit that action, it is not up to you what happens, so it is morally meaningless what you intended to happen. How does this relate to the conflict? Well, when you fire tank shells into the middle of a crowded city, it is again, irrelevant what your true intention was, because the inevitable and foreseeable consequences of your action is that you will kill civilians living there. The philosopher Hegel had this exact idea in mind when he gave his approval to the phrase, “The stone belongs to the devil when it leaves the hand that threw it.” If you throw a stone near a window, you may not intend, nor indeed actually cause, any damage. But the risk of serious damage is clearly there and it is no good to disown that risk when it comes to fruition.

Inevitably following on the heels of this talk about which side has the worse ‘intention’ comes the issue of the Hamas Charter, and it is this issue to which I would now like to turn. The Hamas Charter is an abhorrent, contemptible document, full of vicious language and hateful claims resting on total falsehoods about the world. It is also true that the people who most often reference this document are not Hamas members themselves, but Israeli supporters. They use it to try to show how monstrous Hamas are, since the more monstrous they can depict Hamas as being, the more justified they feel they can be in confining all Gazans to live in a constant state of imprisonment. It is entirely overlooked, of course, that the majority of Gazans today were not even alive when the charter was written and that Hamas itself has not officially adopted the charter as part of its political programme since it won the Palestinian legislative elections in 2006. Those facts must be irrelevant, since they don’t fit the desired narrative of US-Israel apologists.

And while we are scrutinizing political charters, we would do well to look at that of Likud, the governing political party in Israel. The Likud Platform of 1999 (written much more recently than the Hamas charter) “flatly rejects the establishment of a Palestinian Arab state west of the Jordan river.” So it denies the right of the Palestinian state to exist, just as the Hamas charter denies Israel that right. The crucial difference, of course, is that unlike Hamas, the Likud party doesn’t just confine that rejectionist idea to an old piece of paper – they actually act on it. They are carrying out that policy in the West Bank: with the construction of the West Bank wall, in gross violation of international law, and the expansion of the illegal settlements, the Israeli government is slowly dismantling any idea of a Palestinian state. These actions deny the Palestinians a right to statehood much more than Hamas’ charter could ever do to Israeli statehood.

The next objection we hear, and the final one I will address in this post, is about the disproportionate media coverage of the Israel-Palestine conflict. Many more people are dying in other conflicts around the world, it is said, and yet we focus so much attention on Israel. Isn’t that indicative (they say) of a prejudice? The idea that a state or group should be exempt from criticism simply because other states commit similar or worse crimes is an argument we would do well not to dignify with a response. But there is a more salient point here that is worth spending time on: what makes Israeli crimes so deserving of attention is that every single one of them is enabled by the support, diplomatic and financial, of the United States. The US funds Israel to the tune of $3 billion per year. We provide them with the weapons used to enforce the occupation. Whenever a UN resolution calls upon Israel to settle the conflict based on international law, it is the US which vetoes it, providing Israel with a diplomatic shield under which it can continue to annex Palestinian territory. It is no exaggeration to say that Israel could not do what it is currently doing without the support of the United States, which therefore makes us complicit in every one of those crimes.

There will, of course, always be an inexhaustible supply of specious arguments that apologists for state terror will use in order to try to justify themselves. I have tried here to address what I have found to be the most widely disseminated ones, in the hopes of preventing people from falling for this kind of sophistry.