In Git, Say What You Did, Not How

Writing good commit messages is something I sometimes obsess over. To me, commits need clear messages that, when read, tell a story about how the project has been evolving. I get rather annoyed when a teammate commits things like “Implements X’s feedback”. This tells nothing about the commit, nor about the history of the project. Over the years I’ve found that a good rule of thumb is to describe what you did, not how. This is better explained with an example:

Say you are fixing a bug that requires you to change a multiplication operation for a sum operation. Instead of writing

“Changes multiplication to sum”

You could write

“Fix the total price calculation. Wrong totals were given.”

This way anybody reviewing the git log can see right away that in that particular commit a bug in total price calculation was fixed. The first message doesn’t tell a story about the project, it tells a story about the code. You don’t want that in your commit messages.

Another thing I’ve learned is that commit messages aren’t always about the thing you are trying to fix or implement. For example, I recently had a teammate report to me that an form error was not displaying in the right place. This was for a floating form that opened via a button. When the user didn’t enter information in a required field, the form would disappear and the error message would be displayed in the main page instead. This was confusing to say the least.

My job was to display the error message right there when the form was open. I saw that the form already implemented HTML validation for some of the required fields, so it was a good idea to do the same for the ones that it didn’t so the experience remains consistent. I did just that, and when the time came to write a commit message I was tempted to say something about the commit being for fixing an error display issue. But when I thought about it a bit more, I realized that was not what the commit was about. The commit was about adding HTML validation to fields that were missing it. So I wrote that instead:

Implement HTML validation for fields that don’t have it.

But I’m guessing future me may want to know “why” this was needed. So, I made future me a favor and added a longer explanation as well as the initial “heading” message above:

“We want to show errors about missing information for X and Y input types when they are required right on the form instead of having the form refresh the page with an error message.”

I’ve found that sometimes it is useful to explain why you did what you did as part of the commit message, but I’m always careful to put that in a paragraph bellow the commit heading which explains in short words what I did. I don’t always add a commit message body explaining why I did what I did. I usually only add a commit message heading that explains what I did in as few words as I can, but whenever I find it necessary, I add a commit message body without worrying about commit message length.

Use the Pipe

A few days ago I was trying to extract a piece of data from certain lines of a CSV file. The file is a list of inventory items. Some of those items have a special field set to the value “R”. This lets us know that those items can be purchased after their loan term has expired. The CSV file has different fields for each item. Each line in the CSV file represents an item. So, identifying those special items was quite easy with sed:

sed -n -e '/"R"$/p' file.csv

I knew the special field was the last item in each of the lines of the file, and that command above would give me all the lines of items that I was interested on. However, each line has a lot of information that I didn’t care about at the moment. I was interested only on the stock number of each item, which follows a pattern that can also be searched for using a regular expression. I wanted to get a list of stock numbers, so my first instinct was to check the man page for sed to see if there was a way to print only a specific part of the line that matched the address in the p command. A quick scan through the man page quickly revealed that there wasn’t a real way to do what I wanted. How was I supposed to do it? Did I have to write a small program to do it?

I always keep in mind the unix philosophy: <<Make each program do one thing well. To do a new job, build afresh rather than complicate old programs by adding new “features”>>. But I think keeping it in mind is not enough. It has to be part of your way of thinking. I was reminded of this by an answer in stack overflow. Composition is a fundamental part of how the shell works. You run a program, take its output and use it as input for another program:

sed -n -e '/"R"$/p' file.csv | grep -o "regexp" > output.txt

The day after, when I wanted to count the lines that matched a pattern in a file, reaching for the pipe was my first instinct. Rather than wanting a single program do everything I wanted, my first thought was: What programs can I combine to achieve this?

sed -n -e '/"R"$/p' file.csv | wc -l

The unix philosophy is something I’ve been thinking quite a lot recently after a few months ago I realized that at work we were writing functions that tried to do a ton of things. That is when I remembered that a function should do one thing, and one thing only, and do it well. This is also the philosophy behind functional programming where composition is THE WAY to do things. But until we’ve baked this into our way of thinking, just knowing it won’t do us any good.

Use the pipe.

The Boring Stack

I think  someone finally put in writing something I’ve been thinking for  some time: https://justmarkup.com/notes/2020-01-14-boring-by-default/

To me it makes a lot of sense to start any new project with a blank static html page, some old fashion CSS and the vanilla js framework. Over complicating things seems to be the norm nowadays, and it’s leading us to an increasingly fatter web.

I remember back when I first started learning about web development there was a strong push for fast websites in terms of page load, and interaction. File size and external resources was something you were trying to keep as low as possible. But things quickly got out of control with the rise of javascript frameworks. Suddenly there were many different javascript frameworks and developers started loading them in their pages, sometimes more than one at the same time. The fact that libraries had to implement a no-conflict function is a testimony of this issue.

Many new web developers compensated their lack of experience with a ton of plugins. Inexperienced programmer quickly began creating fat websites where simple static HTML would have sufficed; no plugins required. WordPress development, for example, is based completely around the use of plugins, many of which load their own version of X library. It became common to see websites that loaded 2 or more version of jQuery on the same page because different plugins required different versions. At some point it seemed to me that a WordPress developer was just someone who could login to the admin panel, and install a bunch of plugins. And the plugin market didn’t make it any better.

Plugin makers, in an effort to capture as many sells as possible, ship plugins with a gazillion features out of which you will only use 1 or 2. The thing is, developer Y will require a different 1 or 2 features of the same plugin, so having them available increases the chance of a purchase.

Then came heavier frameworks like Vue and React. The problem is not the frameworks themselves, but developers who just use anything new and fancy for the sake of appearing cool, and in with the current web trends. Add to all of this the ton of tracking scripts that websites add plus the ads and you have a mess. No wonder people have been talking about a bloated web for years.

I hope one day we will realize the error in our ways and get back to the right path. But for now, do me a favor, be boring…

Drupal Error: PDOException: SQLSTATE[42000]: Syntax error or access violation: 1231 Variable ‘sql_mode’ can’t be set to the value of ‘NO_AUTO_CREATE_USER’ in lock_may_be_available()

I was setting up a drupal 7 site on a Mac OS computer, and got the error in the title when trying to sync the local DB with a remote DB. After a lot of time, the problem came down to a mysql incompatibility. I had installed MySQL 8, and had to downgrade to MySQL 5.7.24. The full error message contained a reference to the file includes/loc.inc line 167 as the source of the exception, but scrolling a little up the file I saw a catch statement in the lock_acquire function, and decided to dump the error caught. It turns out the exception is actually thrown on file includes/database/mysql/database.inc, line 94, in the constructor of the DatabaseConnection_mysql object. In the constructor is where Drupal tries to set sql_mode to a value which MySQL 8 is rejecting. For more information visit https://dev.mysql.com/doc/refman/8.0/en/mysql-nutshell.html#mysql-nutshell-removals

Sick and Tired of Most People

Today, I read the news about the father of Javascript stepping down from hist role as CEO of Mozilla after just 10 days since he took that role. The reason for this is that he donated $1,000.00 to a proposition to ban gay marriage in Californa, and people didn’t like that.

I have my own views on the gay marriage issue. I may not agree with you, but I sure will not discriminate, judge, and bully you because your views are different than mine. I don’t agree with Brendan Eich’s views on the matter, but I respect his opinion.

The one thing that really bothers me in this controversy is the reaction of many people. It seems to me that gay advocates, and activists are at least just as intolerant as anti-gay people are. For example, OK cupid went as far as denying service to anyone who uses Firefox (http://www.cnet.com/news/okcupid-piles-on-mozilla-calls-for-new-ceo-to-resign/). This is unacceptable. This is a great demonstration of intolerance, and abusive action. Rarebit is asking Brendan to apologize (http://www.teamrarebit.com/blog/2014/04/03/a-sad-victory/). No one should ever have to apologize for their opinions. We apologize for our actions, not for our thoughts.

I think marriage should not be a legal issue. Marriage should be a fundamental right such as the right to live. It should not be open for questioning, nor should it be denied to anybody. I don’t care what the Bible says, or what my religious views teach, I will always support the rights of others, even if they differ with my personal views because as soon as I try to take away other people’s rights, I’m stating that it is OK for others to take away mine.

Please, keep that in mind when you read the following:

I’ve had enough of these activists people. I’ve had enough of the LGBT movement. I’ve had enough of all the crap going around. If you are gay, lesbian, bi, or trans, I respect that. I will be the first to help you on anything I can if I see you in trouble. I will respectfully turn you down when you flirt with me, and I will be your friend if you are the kind of people that I like to hang out with. I will not, however, congratulate you for being “brave”, I will not think of you as more (or less) than anybody else, I will not believe that you being LGBT entitles you to any more, nor any less rights than anybody else, I will not fight for you cause, because you don’t have one. What you have is a sexual preference, and that is nothing special to have. We all have one.

You are not special in any way, you don’t get a free pass if you disrespect me, you don’t get to have special treatment. I am telling you that you are equal to anybody else, and I think that is the best thing you can get, if you truly want equality. If what you are looking for is special treatment, you don’t get that with me. I am tired of those who actively push their sexual orientation onto others, gay or straight.

Those are my views on this subject, and while I am aware that the LGBT community is only fighting for their rights, I don’t support their methods in many cases.

Links of the Day – 12/16/2012

Some of the links I have for you today are old. They have been sitting there on one or another of my many firefox windows.

Security:
http://neobits.org/?p=1115 – hecky takes us through a brute force attack using the command line. (Spanish)

Mozilla
http://techcrunch.com/2012/12/14/mozillas-future-in-mobile-19-adopt-do-not-track-on-android-desktop-only-8-6/ – About the future for mozilla in the mobile world.
https://hacks.mozilla.org/2012/12/firefox-os-simulator-1-0-is-here/ – Mozilla launches FFOS simulator as a FF addon.

Terminal
http://fooyeahcode.tumblr.com/post/22848216070/a-little-collection-of-cool-unix – A collection of some unix tools.

Programming:
http://www.shockoe.com/blog/typingcodeout/ – About the benefit of typing code rather than copying and pasting.

Microsoft:
http://blogs.windows.com/ie/b/ie/archive/2012/12/13/ten-reasons-why-internet-explorer-10-is-best-for-business.aspx – 10 reasons why IE 10 is best for business.

Javascript:
https://gist.github.com/768272 – A list of javascript game engines.

Life:
http://www.raptitude.com/2012/07/most-lives-are-lived-by-default/ – An invitation to live the life you want, no the one you got by default.
https://www.facebook.com/notes/facebook-engineering/under-the-hood-rebuilding-facebook-for-android/10151189598933920 – Facebook for android is now native. Bye bye to HTML5

Other:
http://tiamat.tsotech.com/24-bit-color-sucks – Someone’s rant about 24-bit color.
http://googleenterprise.blogspot.com/2012/12/changes-to-google-apps-for-businesses.html – Changes to the goolge apps for businesses.
http://www.mickgardner.com/2012/12/an-introduction-to-static-site.html – An introduction to static site generators.

2011 in review

The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

The concert hall at the Syndey Opera House holds 2,700 people. This blog was viewed about 13,000 times in 2011. If it were a concert at Sydney Opera House, it would take about 5 sold-out performances for that many people to see it.

Click here to see the complete report.

Having Problems with WiFi

I was playing with the settings on my modem/router (Motorola NVG510) last night and it seems I screwed something up. I was trying to make my local server available to the outside world. That is easy.Just go to the admin page of the device, then Firewall->NAT/Gaming and associate the HTTP service to the server.

The problem is that once online, the server can’t be access from within the network. That is, you cannot access the public IP from behind the NVG501. If you try to access it from anywhere else it will work, but not from behind the modem/router. It turns out the NVG501 doesn’t support NAT loopback, so you cannot access your own public IP. You can access the server from any device in the network via the private IP, but not via the public one.

Why is this a problem? Suppose you associate a domain name with your public IP. When you try to access that domain from within your network you will be unable to do that. In my case I was trying to make a wordpress site available to the whole world. This presented a problem because the site was set up using localhost/site/ as it’s URL, so somewhere in the wp database, that domain was set as the domain of the site. You cannot have two domain names on the same site, so the only option is to change the database value. This is easy. The problem comes when you want to continue working on the site.

Since the NVG510 does not support NAT loopback, you cannot access the site. If you cannot access the site, then you cannot work.

If you were hopping to find a solution to this problem on this post, sorry to disappoint you, but the only one I have for you is: buy a new, better router that supports NAT loopback. You might be able to get another one from your ISP, just give them a call and see if they are kind enough.

I was foolish enough to think there could be a way around this problem, so I started playing around with the settings. Most of what I did was just change settings here and there. I really know nothing about most of what I did, but I’m never afraid of fooling around with settings.

At some point I got the stupid idea of changing the settings for the public subnet. At around 3 am I decided to go to sleep. As far as I remember, the Internet connection was still working, but today when I woke up, it wasn’t. At some point it stopped working and I had no idea why.

I was able to connect to the NVG510, but there was no Internet service, although the status page said there was no problem with it. I went to check the settings that I had fooled around with last night. At first it asked me for the device password, which I input and got back an error. I verified the password, input it again, and got another error. This happened about 5 times. I decided to reset the device.

After restarting, I was able to input the password and get to the restricted parts of the device’s admin interface. The settings for the public subnet were all there, so I guessed that was the problem, and I decided to set them back as they initially where. When I tried to save the settings, the modem would just not respond. It was “loading”, and it would not submit the settings.

After much trying, I decided to reset the device again. This time I held the reset button for 10 seconds to make sure it would reset it’s settings. After this I was able to connect to the modem and the Internet service was once again working.

A few things worth noting: When I reset the device for the last time, the SSID has been reset to it’s original name, rather than the name I’d given it, so trying to connect to the usual network would not work. After some time the pc figured that out and connected to the original network on the device. Fortunatelly, the computer remembers all the networks it connects to, when one is not available, it tries the next one if in range. So the computer tried until it finally connected to the original network from when I first set the modem up. Also, in the public subnet, the option that says Primary DHCP Pool would remain marked as public. I think this was the reason for the problem.

My thoughts are that since the Primary DHCP Pool was set as public, the device tried to assigned the computer and other devices attached to it (the modem), a public ip from the range specified. This would prevent the router from properly redirecting traffic to the right device. This is just a guess, since I currently have really no idea what happened in reality.

If, unlike me, you do know something about this things, it would be nice if you could explain more about what you think happened.

Diveintohtm5.org is gone.

Today I learned by a tweet that diveintohtml5.org was gone. There is a mirror on diveintohtm5.info and there is another on http://diveintohtml5.ep.io/ . There are also mirrors of the diveintopython.org book and of The Man on github. But the question everybody is asking is, Where is The Man?

Mark Pilgrim, who I’ve decided to call “The Man”, has disappeared. Apparently none seems to know where he’s gone. There is only one tweet by @textfiles that reads

“Mark Pilgrim is alive/annoyed we called the police. Please stand down and give the man privacy and space, and thanks everyone for caring.”

https://twitter.com/#!/textfiles/status/121436177298493440

For now, you can go to this mirrors of the old diveinto sites
http://diveintohtml5.info
http://diveintohtml5.ep.io/
http://diveintopython3.ep.io/

And his GitHub projects have been also mirrored on https://github.com/diveintomark/

Ajustando las pantallas, like a boss

Hoy compré un monitor nuevo. En realidad no es nuevo.  A mi me gusta reciclar y reusar, por lo que cuando puedo compro cosas que sean “de segunda”. Aparte del obvio beneficio económico de hacer esto, hay un beneficio ecológico, y es esta la razón principal por la cual yo escogo comprar algunas cosas en tiendas de segunda. Acá en San Francisco se encuentran cosas prácticamente nuevas si sabes a donde ir.

Bueno, la cosa es que compré mi monitor y lo conecté a mi laptop corriendo ubuntu. Me llevé una descepción cuando ví que la pantalla se “estiraba”. Mi laptop ya es muy vieja, y no la he cambiado por que tengo mis ojos puestos en un alien ware que cuesta algo carita. El hecho de que mi laptop es vieja me limita en muchas cosas, por ejemplo, la pantalla tiene una resolución máxima de 1024 x 768 a un radio 4:3. Mi nuevo monitor tiene un radio 5:4. Ubuntu me da solo las siguientes opciones para la resolución del monitor nuevo:

1152×864
1280×1024

Solo he puesto las que son mayores a 1024×768 ya que menores no me interesan.

De estas dos, la única que se ve bien es la de 1280×1024, la cual tiene un radio de 5:4. Esta resolución se ve de lujo, el problema es que compiz empieza a consumir más del 50% del cpu y aveces lo lleva hasta 100% solo para mover una ventana. Esto por supuesto no es bueno.

A 1280×1024 la pantalla se empieza a “estirar” ya que este radio es de 4:3, además compiz sigue de comelón.

Mi mejor opción fué 1024×768 ya que compiz prácticamente consume los mismos recursos que con un solo monitor. El problema aquí es que la pantalla se “estira” hacia abajo. Mi otro monitor (una tv) tiene la opción de mostrar solo negro el resto de la pantalla en lugar de “estirar” la imagen para cubrir toda la pantalla. El monitor nuevo no tiene esta opción.

Que podemos hacer en estos casos?

Lo primero que podemos hacer es aplicar una escala a nuestro monitor en cuestión. Para esto vamos usar la utilidad xrandr. Antes que nada necesitamos saber cuanto vamos a escalar nuestra pantalla. Para esto vasta con hacer unos cuantos sencillos cálculos matemáticos.

Lo primero que haces es determinar el radio o proporción de nuestra pantalla. Para esto puedes  probar con cada resolución que Ubuntu te ofrece. Notarás que a lado de la resolución te muestra las relación proporcional entre el ancho y el alto de tu monitor,

Provando con cada una encontrarás la que se vea bien, y esa es la relación proporcional entre los lados de tu monitor. Como tip, no prueves con resoluciones cuya relación proporcional es igual. Por ejemplo, en mi caso no tiene caso que prueve con 1024×768 y con 1152×864 ya que ambas tienen una relación proporcional de 4:3.

Una vez que encuentras la relación proporcional (radio de ahora en adelante), puedes hacer tus calculos matemáticos.

Otra forma de encontrar este radio es midiendo ambos lados lados de forma manual y calcular que parte del lado mas grande representa el lado más chico, pero eso es solo trabajo de más.

En mi caso, el radio es de 5:4, pero estoy usando una resolución de 1024×768 la cual tiene un radio de 4:3. Lo que quiero es escalar mi imagen de modo que sea de 1024×4/5(1024).

Para los que se han perdido con esto del radio. Lo único que quiere decir es que en un radio x:y hay x unidades por cada y unidades. De este modo, en un radio 5:4 hay 5 unidades de ancho por cada 4 unidades de alto. Esto es importante por que a partir de esto podemos determinar cuantos pixeles debemos tener de alto para cunplir el radio 5:4 de mi monitor.

Si por cada 5 unidades de ancho, hay 4 unidades de alto, entonces el alto total de  mi monitor es de 4/5 (cuatro quintos) del ancho del mismo. Con esto podemos determinar el alto de mi monitor de la siguiente manera:

(4 * 1024)/5

Esto nos da como resultado 819.2. Como no podemos tener decimales vamos a redondear a 819 pixeles de alto. Actualmente tiene 768, por lo que tenemos que encontrar el numero que multiplicado por 768 nos da 819:

768x = 819;

x = 819/768;

x=1.06640625

Y este es el factor por el cual tenemos que escalar nuestro monitor. Probablemente hay formas más rápidas de llegar a este numero, pero creo que esta es la forma más sencilla de comprender.

Ahora que ya tenemos nuestro factor, abrimos la terminal (ctrl + alt + t) y ponemos:

xrandr

Esto nos va a mostrar una lista de los diferentes monitores disponibles y sus propiedades. Lo que nos importa en este caso es el nombre. En mi caso, el monitor está conectado con en el puerto VGA, y tiene como nombre VGA1. Ahora que ya conozco el nombre puedo proseguir a hacer la escala:

xrandr –output VGA1 –scale 1×1.0664025

Después de un rápido flasheo en la pantalla veo que mi monitor se ve mucho mejor. La imagen ya no se ve estirada. La desventaga que he notado hasta ahora es que Xorg empieza a consumir más recursos, probablemente por que tiene que escalar la pantalla.

Otra opción que probablemente podría servir mejor es agregar un nuevo “mode” usando la opción –newmode de xrandr. En mi siguiente post, hablaré de esta segunda opción y daré mi opinión en cuanto a cual creo que es la mejor opción.

Es importante mencionar que estos cambios solo aplican durante la seción actual. Más adelante veremos como hacer estos cambios permanentes.

Les dejo esta imagen para que vean el antes y después de aplicar la escala al monitor.

NOTA:

Una forma más rápida de encontrar la escala es ver la diferencia entre ambos radios:

5:4 y 4:3

5/4 =  .8

4/3 = .75

.75x =  .8

x =  .8 / .75

x =  1.066666666667

El resultado es un poco diferente, pero es de hecho el resultado que obtenemos si no redondeamos 819.2

NOTA 2:

No noté anteriormente, pero xrandr te dice la medida de tu monitor en mm, por lo que no hay que medir manualmente si quieres poder calcular el radio sin probar todas los radios disponibles para ver cual es el mejor.