- The Institute for Energy Economics and Financial Analysis reports that India is cancelling plans for huge coal power stations because solar energy prices are lower, which, if true, represents a huge threshold for sustainable energy productions. If solar energy is cheaper than coal (and other types of energy), that means the market itself will naturally migrate over.
- A company is suggesting that young blood cuts cancer and Alzheimer’s risk, which seems like a huge deal. That said, a healthy dose of skepticism is warranted. For example, the company’s trial did not have a placebo test group.
- A new paper describes a test in which they were able to restore damaged brain cells in mice using stem cells.
Blog
Casting objects and boxing
I’m back from a trip to a customer.
How was it?
Okay. I got more snow that I expected on the way there, so the drive wasn’t much fun. Then again, a part of the trip goes through a beautiful forest that was worth everything else.
Cool!
Also, while showing the customer a new feature, the app crashed.
Typical. Blame it on Murphy!
That’s what I did at first. Then I blamed it on the developer. And then I finally went looking at the C# code to find out why it happened.
What was it?
It turned out to be a rather common but not obvious mistake. See the code below and tell me what is the value of each of doubleF, doubleI, and doubleO.
float f = 0.0;
int i = (int)f;
object o = f;
var doubleF = (double) f;
var doubleI = (double) i;
var doubleO = (double) o;
I’m sensing a catch here, but I’ll bite. They’re all cast from the same original variable f so I’m guessing they’d all end up 0.0…?
You would, wouldn’t you? But you’re wrong.
Waaat?
The final line in that code will throw an InvalidCastException at you — and crash your app if you don’t catch it, as was the case in our app.
Wait what? How? How come you can’t cast 0.0 to double?
Well, you can. For instance, this works perfectly —
var d = (double) 0.0f;
But this doesn’t —
object f = 0.0f;
var d = (double) d;
It makes no sense!
Actually it does. The problem is taking object to mean “anything.” Which incidentally it does, just not the way most people think. You see, object is a type representing Object, which is a class other types inherit from but not all. You can store anything as object because Object boxes whatever object you put in it. It stores the value internally but the compiler doesn’t know what type is stored there.
No no no! I know for a fact that you can too check what type is stored in an object
You’re right, you can. For instance —
object o = /* something */
Console.WriteLine(o.GetType());
This will print the type of whatever you put in the variable o. But this is at run time: the compiler doesn’t know.
That’s why we using casting. If we know for a fact that variable o will contain a, say, int, we can help the compiler and tell it about it with a cast. Remember, when you cast something, you are telling the compiler what type will be stored in the variable. The compiler can’t be held responsible if you lie to it.
Let’s get back at the original problem —
object o = 1.0f;
var d = (double) o;
You told the compiler that o will be a double, but it isn’t. Remember a double is a shorthand for the struct Double as float is for Single. And guess what? A Double is not a Single. When you stored a float in the variable o of type object, the float value was boxed inside an object of type Object. When you cast, the compiler has to unbox whatever was inside o and guess what, the value stored in o is of a different structure, with different methods and storage, than what you told it it was. You could convert between them, but they are not the same.
So the compiler expects an object of type Double but it has a Single and things fail miserably.
But you just said that we can convert between them! Why don’t the compiler does it?
It could. But think of how this would work out in real life. Remember the compiler doesn’t know what will be inside o so it needs to test what the value is. It would need to test if the type is a, say, string. If it is, then convert string to Double. If it isn’t then check if it is a Int32. Then a Int64. Then a DateTime. The number of possibilities is enormous and the compiler would have to generate all this code every time it needs it finds a cast. This would be a lot of code. It would be so much code in fact that you’d be mad not to put it all in separate methods. It would also be slow so the compiler won’t do this by default.
That’s why we have the Convert class, which in turn depends on types implementing the IConvertible interface. Whenever you want to convert a value of TypeA to TypeB, you can use this conversion methods. You can do —
object o = 1.0f;
var d = Convert.ToDouble(o);
The compiler authors had to make a decision: either they’d generate lots of slow code to test for the type and convert the value, or they’d leave the decision for the programmer who can call Convert.ToSomething when needed.
And they chose the former.
Exactly. I believe it was reasonable. If you know something will be of a given type at run time, you can still cast it. Otherwise, you should convert it.
Retreating back into my bubble
A few months back I decided to try and burst out of my bubble. I then decided to follow some public figures from all sides on Facebook and Twitter. On Facebook this is particularly weird because you’re forced to like the page. So it tells the world “Roberto likes Mrs. Public-Figure”, which is sometimes undesirable.
Still, I wanted to see what both sides of the political spectrum were saying. Also, I consider myself a centrist so I expected to agree with everyone on at least something.
Anyway, my town suffered a terrorist attack a couple of days ago and as soon as the identity of the suspect became known, the media started drawing conclusions based on who he “liked” on Facebook. That got me thinking: someone will eventually go through my social media and conclude I believe in X because I “like” Y on FB, even though I may only “like” Y because I want to be informed and not because I necessarily agree with them.
There are also reports that US Border agents now require people to provide social network credentials so that their political leanings can be attested. Regardless on my personal opinions about this, the fact is that someone with access to my FB account can quickly draw the conclusion that I lean this or that way because of the pages I like, even though I liked them only to be informed.
I then realized that it’s time to give up on my bubble-bursting experiment. I “unliked” pretty much every public figure on Facebook.
Cedilha no Fedora 25
Quem utiliza teclado US Internacional para escrever no Linux já deve ter dado de cara com o fato de que na maioria das distribuições, a combinação ‘+c gera um “ć” em vez de um “ç”. Resolver isso no Fedora 25 é fácil, mas não evidente.
tl;dr – eu criei este script que faz todos os passos abaixo automaticamente. Basta rodar isso:
curl https://raw.githubusercontent.com/robteix/c-cedilla-fedora/master/c-cedilla-fedora | bash
Se você preferir não executar o script, continue lendo.
Primeiro, vamos criar um novo mapa de teclado para seu usuário. Rode o comando abaixo:
sed -e 's,\xc4\x86,\xc3\x87,g' \
-e 's,\xc4\x87,\xc3\xa7,g' \
< /usr/share/X11/locale/en_US.UTF-8/Compose > ~/.XCompose
Isso copia o arquivo de mapeamento de teclas do Fedora para o diretório $HOME do usuário, substituindo o “Ć” por um “Ç”.
Agora vamos configurar o GNOME para que ele não controle a configuração do teclado, para que possamos usar nossa própria:
gsettings set org.gnome.settings-daemon.plugins.keyboard active false
Para selecionar o input method apropriado, o Fedora fornece um programinha chamado im-chooser que não é instalado por padrão. Para instalá-lo:
sudo dnf install im-chooser
Por fim, executamos o im-chooser e escolhemos “Use X Compose table”:
Clique em “Log out” para aplicar as modificações e a partir de agora deve ser possível gerar o c-cedilha com a combinação ‘+c.
The Woman the Mercury Astronauts Couldn’t Do Without
Must-read article on “human computer” Katherine Johnson. Not only was she a key figure in pushing NASA’s efforts forward, but she did it while fighting misogyny and racism:
Outside the gates, the caste rules were clear. Blacks and whites lived separately, ate separately, studied separately, socialized separately, worshipped separately, and, for the most part, worked separately. At Langley, the boundaries were fuzzier. Blacks were ghettoed into separate bathrooms, but they had also been given an unprecedented entrée into the professional world. Some of Goble’s colleagues were Yankees or foreigners who’d never so much as met a black person before arriving at Langley. Others were folks from the Deep South with calcified attitudes about racial mixing. It was all a part of the racial relations laboratory that was Langley, and it meant that both blacks and whites were treading new ground together. The vicious and easily identifiable demons that had haunted black Americans for three centuries were shape-shifting as segregation began to yield under pressure from social and legal forces. Sometimes the demons still presented themselves in the form of racism and blatant discrimination. Sometimes they took on the softer cast of ignorance or thoughtless prejudice. But these days, there was also a new culprit: the insecurity that plagued black people as they code-shifted through the unfamiliar language and customs of an integrated life.
Katherine understood that the attitudes of the hard-line racists were beyond her control. Against ignorance, she and others like her mounted a day-in, day-out charm offensive: impeccably dressed, well-spoken, patriotic, and upright, they were racial synecdoches, keenly aware that the interactions that individual blacks had with whites could have implications for the entire black community. But the insecurities, those most insidious and stubborn of all the demons, were hers alone. They operated in the shadows of fear and suspicion, and they served at her command. They would entice her to see the engineer as an arrogant chauvinist and racist if she let them. They could taunt her into a self-doubting downward spiral, causing her to withdraw from the opportunity that Dr. Claytor had so meticulously prepared her for.
Source: The Woman the Mercury Astronauts Couldn’t Do Without