How to biohack your brain to pass the Mensa test

Since some years ago, every christmas, I write down 5 goals to achieve during the year. They are usually focused on acquiring experiences, but also some challenges that I want to put to myself.

This year I wanted to check how much I could improve my ability to perform logic problems through studying, training and diet.

The Mensa Association only admits the top 2% of the population based on their IQ. The IQ is measured by a standardised test that measures the ability of logical thinking.

So, the bar is high enough to give a try.

I researched all the scientific information posible to get all the hacks that I could apply for this pursose and now, I will share them with you.

In this post I will talk about Neuroplasticity (the ability of the brain to change and adapt), Brainwaves (the brain’s working modes) and some hacks to put our brain at peak performance.

1- How does intelligence work?

In psychology, crystallized and fluid intelligence are factors of general intelligence.

Crystallized intelligence is the ability to use experience and knowledge to solve a determined problem.

Fluid intelligence is the capacity to reason and solve new problems.

We need to train both in order to achieve the best score possible for us.

1.1- Master the rules of the game. Crystallized intelligence:

When we study for an exam,  we acquire information and learn processes that will help us to perform better on the test. 

In other words, we are acquiring experiences and knowledge that will be used by our crystallised intelligence to elaborate a better answer on the test.

Therefore, the best way to improve the crystallised intelligence is to know the basic rules and apply them repeatedly in order to interiorize the process. 

There are color changes, things that rotate and shape transformations.

It’s all about patterns. Usually the design consists of 3 rows and 3 columns that contain 8 figures so you have to guess the 9th.

The patterns go from left to right []→[]→[] , from top to bottom (↓↓↓) and usually, the rows are connected (the last element of a row connects with the first of the following row).

This is very important and useful when there seems to be more than one possible solution.

As long as we answer questions, they will become more and more difficult as more patterns are introduced.

For example, the first figures may have only a color or shape transformations. As we advance on the test, they will add more and more patterns that you will have to take into account to successfully make the correct figure.

This makes a lot of sense. Intelligence (in the way it’s measured in this test), is the ability to retain and process different thoughts at the same time.

Practice with as many tests as possible, but try not to repeat them or you will be training memory instead of process execution.

*It is a good idea to watch explanations or live resolutions of some tests. I will leave a link at the end of the post if you want to take a look.

1.2- Reinforce your neuronal synapses. Fluid intelligence:

We can get a new habit in 21 days, which is the time that takes the brain to create and establish a new circuit. This is called neuronal plasticity and it will help to  increase our fluid intelligence.

As we said, fluid intelligence is the ability to reason and solve new problems.

We can only improve this by reinforcing the neuronal circuits (synapses) responsible for that matter.

How can we do that?

The answer is simple, by reasoning and solving new problems. We can do this by playing logic games, puzzles, Rubik cubes, sudokus…

Whatever that forces you to think about a process to solve a problem.

Practicing this will reinforce your hability to solve complex problems. It’s important that we don’t look for processes or rules on the internet. For example, if you are solving a Rubiks cube, don’t try to find new ways when you get stuck. If you are playing chess, try to figure out by yourself the best moves for each situation. We are training our ability to reason, don’t look for shortcuts.

The golden rule is: “Don’t settle”, if it starts becoming easy, change the game.

2- Brainwaves. Go with the flow

There are cycles on everything!

The cycles of the planet’s path around the sun defining the seasons.

The day/night cycles due to the rotation of the Earth (That define our circadian rhythms).

The water cycle where ocean’s water is evaporated and form clouds, that latter on precipitates on the land and goes back to the ocean through rivers.

We need to realize that we are part of an ecosystem, that happens to have all these cycles that allows life to develop and thrive.

It is amazing how we, the humans, depend from these cycles. The regulate our sleep/awake cycles that connects beautifully how the brain works.

*ENLAZAR CICLOS CON BRAINWAVES* Here I will explain how the brain works from a brainwave perspective.

A brainwave is a measurement of the frequency which the brain works at.

Depending on the longitude of the brainwaves, we can classify them into different “working modes” of the brain. They vary approximately  from 0.2Hz to 30Hz: 

–       Δ Delta -> Deep sleep (<3*Hz)

–       Θ Theta -> Light sleep (3-8 Hz)

–       α Alpha -> Wakeful relaxed (8-13 Hz)

–       Beta -> Wakeful concentrated (13-30Hz)

These brainwaves alternate depending if we are sleep or awake and are the triggers (or the cause) of important processes in the brain.

There are usually triggered alternatively between our biggest working modes:

Sleep -> Delta – Theta

Awake -> Alpha – Beta – Gamma

In the absence of a better example, it would be a mix of hard/soft work and hard/soft rest. We can understand this a bit better looking the image below:

The idea here is that we cannot stay at the “hard work” mode for a long time. If we want to put ourselves into the highest beta possible, we have to start from a very relaxed/rested Alpha.

It is very important to take into account that the brain frequency has to be gradually increased or decreased.

For example, the same way a car engine cannot go from idle to maximum power, a human brain cannot wake up and start solving logic problems immediately. 

How to optimize the brainwaves to get most of it?

We want to maximize Delta and Theta waves while sleeping and Alpha and Beta while awake.

Delta waves while awake may be the reason of “brain fog”, Beta waves during sleep may decrease sleep quality and cause insomnia. It’s crucial that we acquire routines that help us to release every brainwave when they are suposed to.

Why is this important for solving logic problems?

Beta (and Gamma) are the highest frequency brainwaves. 

Beta waves mean that the brain is in a high state of awakeness and focus.

These are the waves that we generate when we are, for example, solving math problems.

The higher the frequency, the higher the focus. 

The most important point regarding the brainwaves is that one day is like one cycle through the spectrum, from deep sleep Delta brainwaves to high focus Beta. In order to reach one extreme, we have to be able to reach the other.

The bottom line is, the quality of the brain waves during sleep will directly affect the quality of our focus and problem solving capabilities.

3- Lifestyle

3.1- Nutrition

The brain, yet another muscle.

As any other muscle in our body, the brain will perform better if we fuel it with high quality foods. 

It is very important to provide the brain all the vitamins, minerals and antioxidants that it needs to perform at its best.

I wouldn’t focus on specific foods, just eat a wide variety of foods (fruits, vegetables, nuts, beans, etc..). The rule is: the less processed it is, the better. 

Avoiding trans fats and sugars is crucial (specially together). A bad nutrition is proven to generate free radicals and inflammatory cells. Studies have shown a correlation between high sugar diet and impaired brain function.

Recent studies have discovered that a healthy gut microbiome, produces some neurotransmitters that the brain will use.

Now, we know that around 90% of the body’s Serotonin is produced in the gut. Let’s remember Serotonin biological function is (among others) to modulate cognition, learning and memory. 

Yet another reason to eat that salad!

3.2- Exercise

Exercise is as important as the diet. When we exercise, the heart rate increases pumping more oxygen into the brain. Also, it promotes brain plasticity by stimulating the growth of new connections, regulates insulin levels and improves the mood and sleep.

Apparently, aerobic activities (running, swimming, cycling… ) are the best for this purpose.

Exercise increases the levels of Serotonin and BDNF (Brain-derived neurotrophic factor), this protein stimulates neuronal plasticity, which is essential for learning and memory.

3.3- Sleep

Why do we have to sleep?

Sleep is, without a doubt the most important factor of this equation. 

The reason why we have to sleep was unanswered until some years ago and though, we don’t fully understand how this happens.

The body releases growth hormone, which helps not only to repair the body cells but also brain cells, improving cognitive functions. From a brainwave perspective, while sleeping, the brain triggers theta and delta waves, the more we are at theta/delta zone at night, the more we will trigger alpha/beta during the day.

A good night of sleep is crucial for a brain and body recovery.

Latest researches have discovered that important processes happen in the brain while we are sleeping.

We convert and order the experiences that we have acquired during the day into long lasting memories by repeating them unconsciously while sleeping. 

4- Other ways to put your brain to work


Replaces Adenosine (block the tiredness receptors) and puts your brain right on Beta mode.

Binaural beats:

The binaural beats are just stereo sounds that plays at different frequencies, where the difference between them is the frequency of the different brain waves. 

We can find binaural beats for every working mode of the brain.

In this case, we are interested in the beta binaural beats, especially if it starts at low beta and increases slowly (this way, we allow the brain to catch up).

So, the day of the test, while we walk around to get ready before it, we can start playing these binaural beats. If we have noise canceling headphones would be perfect.

My recommendation is to use these beats to focus before and during the test, helping you to put the brain at the correct state and isolating you from distractions.

Mental warm up:

When we go to the gym, right before starting a training session, we always do a little warm up. It raises the heart rate, fills the lungs of oxygen and pump the blood into the muscles – and basically prepares the body for a hard training.

The same happens with the brain.

A part of keeping the blood flowing and the brain oxygenated, we need to slightly put the brain on the focus mode (beta). 


Starting from a relaxed state (alpha), we can start making some mental calculus. A simple addition with a two cypher number can work. 

If for example, we take 27 and add the same number we get 54. If we continue this way, each time we will have to handle mentally a bigger number, making use of the parts of the brain that we will use on the exam. 

IQ is basically how many “items” you can retain in your short-term memory. As long as the number gets bigger, more “items” you will have to handle in your brain, so you will be putting your brain in the correct wavelength for the exam. 

It’s amazing how many hacks we have available to put our body (and brain) on peak performance and most of them are things that we already know. 

5- Conclusion

Study and practice, exercise, eat well and sleep better. We (somehow) know that a healthy lifestyle is important for our performance and yet, we don’t realise how much.

We wait for kind of over explanation to do things. Stop doing that. Get started now!

Take this IQ test and set it as a baseline. After that you can check out this video to assure the logic behind the answers.

Start applying these techniques and let me know the improvements you make. 

If someone came to your mind while you were reading this post, share it with them. You have a 65% more probabilities to achieve your goal if you commit to someone :-)

No longer at the mercy of the reptile brain, we can change ourselves. Imagine the possibilities.

Carl Sagan

Mi viaje a Tromsø y la aurora boreal

¿Has tenido alguna vez la sensación de estar viviendo en piloto automático?

Hace casi un año, cuando por fin me había asentado en Dinamarca, empecé a notar que mi vida se volvía más y más rutinaria.

De la espontaneidad de salir a tomar unas cervezas de imprevisto o los mil y un planes que tenía cada fin de semana en España, pasé a las tradiciones (el arroz al horno de los domingos o las cerves del Friday bar) y la planificación a largo plazo. No hay nada malo en ser buen planificador, por algo son uno de los países más ricos de la Unión Europea (o quizá también sea porque a -5º no apetece irse de cañas), pero por desgracia, las oportunidades de ocio son más limitadas.

Era el momento de planear un viajecito.

Desde hace unos cuantos años, en mi afán de tener experiencias extraordinarias, he querido ver la aurora boreal. Es una cosa que tenía apuntada en mi lista de “Cosas que hacer antes de morir”, y sin duda era el momento de hacerlo.

La aurora boreal ocurre cuando el viento solar choca con el campo magnético de la Tierra (la magnetosfera). Cuando estas radiaciones solares llegan a la Tierra, la energía se va acumulando en los polos hasta que no se puede contener más y se libera en forma de luz.

Sin duda, uno de los fenómenos más hermosos y extraños del planeta Tierra.

¿Cuál es el mejor momento?

En teoría, es durante los solsticios cuando las auroras son más intensas. Sin embargo, en estas fechas las condiciones meteorológicas son extremas. Éste fue un punto que casi nos hizo cancelar el viaje. Se necesita mucha preparación para aguantar horas a la intemperie esperando divisar alguna aurora y cualquier imprevisto en la naturaleza podría llegar a ser peligroso.

Es por ello, que decidimos ir en la primera semana de marzo, cuando las condiciones meteorológicas son un poco mejores, aunque la intensidad de las auroras es menor.

Hay tres condiciones que se deben cumplir para que podamos ver una aurora boreal:

  1. Que haya radiación, para ello hay que estar dentro del círculo polar ártico (o antártico) o muy cerca.
  2. Que los periodos nocturnos sean más largos (y no haya contaminación lumínica), es decir, no vayas en verano y aléjate de la ciudad. No serías el primero ni el último, pero no te lo aconsejo. ;)
  3. Que esté el cielo raso.

Dicho esto, tan importante es el cuándo, como lo es cuánto. No hay que tentar a la suerte con un viaje de un par de días, unos días malos (nublados) pueden arruinarte el viaje.

¿Dónde ir?

No existe mejor lugar, la intensidad de las auroras varía aleatoriamente dependiendo de la localización. Aunque recuerda, lo más importante es que el cielo esté raso, independientemente de donde te encuentres.

Ante esto, tenemos dos opciones: Contratar un tour organizado que te llevará en un minibus a los puntos donde es más probable encontrarlas o alquilar un coche e ir buscándolas por ti mismo.

Este último es un poco más complicado sin conocer la zona, pero esto no es un simple viaje organizado, esto es una AVENTURA y el que no arriesga no gana.

Por suerte, la tecnología está de nuestro lado para hacernos las cosas un poco más sencillas.

Hay un par de aplicaciones especialmente interesantes: My Aurora forecast y Aurora alerts. Con ellas puedes saber la probabilidad de ver una aurora y el porcentaje de encapotamiento por franjas horarias para una determinada localización.

Lo único malo es que no te dice la mejor zona, sino que tienes que ir probando en distintas localizaciones usando el mapa.

¿Y qué me llevo?

Ropa de frío, muuucho frío. Ten en cuenta que podemos estar esperando horas hasta que las veamos y cuando esto ocurra, no querremos que el frío nos arruine la experiencia por no poder soportarlo.

Empezando por abajo, por supuesto: botas y doble o triple calcetín (yo me compré unos que me llegaban hasta las rodillas). Esto es crucial, los pies son la parte más propensa a coger humedad y lo último que queremos es perdernos el espectáculo por tener los pies congelados.

Triple pantalón, mallas térmicas, pantalones normales o de pijama y un pantalón de nieve (de esquiar). Y arriba, más capas que una cebolla.

Gorro (si tapa las orejas mejor), braga de cuello, bufanda, unos guantes finos y unos más gruesos (esto va de lujo si quieres hacer fotos y no pasar frío en las manos).

Con todo esto, ya estás preparado para competir contra el muñeco de Michelin o adiestrar una jauría de perros hambrientos. Parece una exageración (y quizá lo sea), pero recuerda que estarás a la intemperie por HORAS.

Respecto a la equipación, nosotros llevamos una mochila grande de mochilero (ésta incluía una funda impermeable que luego utilizamos para sentarnos en la nieve), un termo con té de jengibre y limón para calentarnos, el móvil con suficiente batería, varias linternas y una brújula (que no sirve de nada, pero me gusta llevarla).

En mi caso, no solo quería ver la aurora boreal, sino que también quería llevarme un buen recuerdo, así que me llevé una cámara de fotos reflex y – muy importante – un trípode.

¿Cómo fotografiar la aurora boreal?

Bueno, esto es toda una ciencia. Para un newbie de la fotografía como yo, hay demasiadas configuraciones que desconocía.

Al parecer, tener el obturador abierto por un tiempo (entre 30 segundos y 1 minuto) es lo más importante. De esta forma, el dispositivo fotosensible absorbe toda la luz posible y queda una foto increíble.

Por este mismo motivo, en foto, una aurora siempre va a parecer más intensa y voluminosa de lo que es en realidad, pero verla en persona es una experiencia increíble.

Por esta misma razón, es totalmente indispensable un trípode. Ni con un pulso de hierro vas a poder mantener la cámara estática por 30 segundos o más.

Aquí tenéis un link con las configuraciones recomendadas.

¿Cómo retocar las fotografías?

Dos opciones, las puedes editar manualmente o puedes utilizar una app que lo haga automáticamente.Yo utilicé Snapseed en un primer momento, y cuando tuve un poco más de tiempo seguí los siguientes tutoriales (tutorial 1 y tutorial 2).

El viaje

Estábamos listos. Teníamos la mochila, la cámara de fotos e infinitas capas de ropa. Era el momento de emprender el camino hacia el Polo Norte (casi).

No habían vuelos directos de Copenhague a Tromsø, así que tuvimos que hacer escala en Oslo.

Aunque parezca que Noruega es un país pequeño por tener poca población, nada más lejos de la realidad.

Noruega es un país muy grande y largo. La distancia entre su capital Oslo (situada al sur) y Tromsø (situada al norte), es de 1740 km. Sería equivalente a por ejemplo, ir de Valencia a Frankfurt.

Una vez estábamos de camino, en la primera escala vimos desde el avión montañas y montañas de nieve acumulándose a los laterales de la pista de aterrizaje. Nos esperamos lo peor, pues se pronosticaba una ola de frío y estábamos ya a -20ºC en Oslo. No quería ni imaginar el frío que haría en Tromsø.

Por suerte, al parecer la ola se llevó todo el frío de Tromsø y cuando llegamos hacían unos más que placenteros -7ºC.

Una vez en el aeropuerto, fuimos a recoger el coche de alquiler que teníamos reservado y nos dirigimos hacia el apartamento a dejar los trastos y prepararnos para la noche. Este sería nuestro primer intento.

Empieza la búsqueda de la aurora boreal

Después de cenar, preparamos unas infusiones para verterlas en el termo, nos pusimos todas las capas posibles y cargamos las cosas en el coche.

No era un buen día para ver la aurora. A pesar de que se pronosticaba radiación, el cielo estaba encapotado.

Estuvimos dando vueltas sin saber muy bien que estábamos buscando, simplemente tratamos de librarnos de toda contaminación lumínica. Al final acabamos en un sitio llamado Skulsfjord (el fiordo de las calaveras) donde se pronosticaba mucha intensidad.

Una vez llegamos, bajamos del coche y empezamos a explorar la zona. Estaba todo oscuro y cada paso que dábamos se hundía en la nieve. Buscamos en varios sitios hasta que encontramos una idílica casa de madera al lado de un río congelado.

Tan pronto llegamos al sitio y sin darnos tiempo a prepararnos, vimos una ligera luz verde en el cielo. ¿Será una aurora? pensamos.  Rápidamente tratamos de hacer una foto, no teníamos siquiera el trípode instalado así que la hicimos a pulso.

Con ello confirmamos dos cosas:

La primera, que sí que era una aurora, aunque muy tenue.

La segunda, que las fotos salen terriblemente mal sin un trípode.

Después de instalarnos estuvimos horas esperando a que se desencapotara el cielo, pero nada. Al final recogimos y volvimos al coche, encendimos la calefacción, le dimos al Warm Butt Button (los asientos calefactables) y condujimos de vuelta al apartamento.

Un poco de cultura

Al día siguiente, fuimos al poblado de los Sami, una tribu que vive de la crianza de renos de una forma muy tradicional. Es uno de los atractivos turísticos más importantes de Tromsø.

Ahí, dimos un paseo en trineo tirado por renos por una llanura congelada. Otra experiencia inolvidable que tuvimos gracias a no centrarnos solo en la aurora boreal y explorar otros aspectos de la cultura.

Después de esto, dimos de comer a los renos y luego ellos nos dieron de comer a nosotros. Era una sopa preparada con carne de reno. Esto sin duda trastocó a algunos (los más sensibles) y nos dió a todos una valiosa lección de vida.

Para finalizar, nos sentamos con algunos Sami a charlar. Nos contaron cómo viven y algunas historias sobre los diferentes poblados.

Una vez nos despedimos, hicimos un poco más de turismo por la ciudad y nos tomamos una Mack (cerveza noruega) en Rorbua, un bar acogedor cerca del puerto. Tras esto, volvimos ya al apartamento para preparar el segundo intento.

La recompensa

La preparación fue la misma: Dormir un poco, cenar, preparar algo de té para no morir congelado y salir a por todas.

Antes de salir, también comprobamos la intensidad de las auroras y justamente en el sitio donde acampamos el día anterior, era donde más intensidad se preveía.  Una vez preparados, salimos dispuestos a conducir hacia ese lugar, esperando tener más suerte que el día anterior.

¿Cómo íbamos a imaginar lo que estaba a punto de pasar?

Cuando abrimos la puerta de casa, tuvimos la gran sorpresa de ver la aurora boreal en todo su esplendor, justo encima de nuestras cabezas.

Unas luces brillantes y moviéndose como nunca habíamos visto, que hicieron parecer, a las que habíamos visto el día anterior, inmensamente insignificantes.

No sabíamos cuánto iba a durar, así que sacamos la cámara rápidamente y olvidando la regla nº 1 (siempre utilizar trípode) tratamos de hacer una foto.

Como era de esperar, no salió demasiado bien, pero para el segundo intento, preparamos el trípode y esta vez sí, sacamos una foto decente.

Nos alejamos un poco de la zona residencial para evitar la contaminación lumínica y nos dirigimos a un puerto cercano con casitas de colores en la costa. Desde allí gozamos de una localización perfecta para fotografiar las auroras que se divisaban a lo lejos, sin apenas contaminación lumínica.

Estuvimos jugando con la cámara por un rato hasta que la aurora se disipó. Luego condujimos hasta Skulsfjord, dónde por suerte el cielo estaba raso y se podían ver auroras incluso más intensas que las anteriores.

Paramos en el arcén de la carretera y empezamos a hacer fotos con la esperanza de que no se acabaran pronto. Por suerte esto no pasó, cuándo se extinguía a una, aparecía otra y así pudimos hacer fotografías desde todos los ángulos y localizaciones.

Después de 3 horas y cientos (sino miles) de fotografías, nuestros cuerpos no aguantaban más la temperatura (el termómetro marcaba -12ºC  cuando entramos en el coche) y decidimos volver a casa, con la cara llena de escarcha, pero muy felices de haber cumplido nuestro objetivo.

Una vez ya en casa, retoqué las fotos con los siguientes tutoriales para que se vieran incluso más impresionantes (tutorial 1 y tutorial 2).

Estas son algunas de ellas:

Somewhere, something incredible is waiting to be known.

Carl Sagan

Code Review. How to modify an old commit.

Sometimes, when using Code review, you need to modify an old commit with the suggestions. I used to create a new commit for the modifications, but this is non clean, intuitive (if you wrap commits by task), nor backwards compatible.

There is a better way to this using git rebase, which basically allows you to change a commit and apply those changes to further commits.

In order to do that, we need to rebase the commit this way.
1º- Checkout the branch
2º- git rebase –interactive ‘xxxxxx^’
3º- In the editor, change ‘pitch’ to ‘edit’ on the commit we want to modify.
4º- Make the changes
​5º- git commit –all –amend –no-edit
6º- git rebase –continue
​7º- git push (–force) origin <branch_name>​
I hope it helps

From Java to Kotlin. Cheatsheet

I wanted to keep everything regarding the differences between Java and Kotlin on one place. That’s why I’ve created with Cheatsheet.
I hope it would be useful for you as well.



System.out.print("Hello, World!");
System.out.println("Hello, World!");
print("Hello, World!")
println("Hello, World!")

Variables I

final int x;
final int y = 1;
val x: Int
val y = 1

Variables II

int w;
int z = 2;
z = 3;
w = 1;
var w: Int
var z = 2
z = 3
w = 1

Null I

final String name = null;

String lastName;
lastName = null
val name: String? = null

var lastName: String?
lastName = null

var firstName: String
firstName = null // Compilation error!!

Null II

if(text != null){
  int length = text.length();
val length = text?.length

val length = text!!.length // NullPointerException if text == null

Strings I

String name = "John";
String lastName = "Smith";
String text = "My name is: " + name + " " + lastName;
String otherText = "My name is: " + name.substring(2);
val name = "John"
val lastName = "Smith"
val text = "My name is: $name $lastName"
val otherText = "My name is: ${name.substring(2)}"

Strings II

String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";
val text = """
        |First Line
        |Second Line
        |Third Line

Ternary Operator

String text = x > 5 ? "x > 5" : "x <= 5";
val text = if (x > 5)
              "x > 5"
            else "x <= 5"

Bits Operations

final int andResult  = a & b;
final int orResult   = a | b;
final int xorResult  = a ^ b;
final int rightShift = a >> 2;
final int leftShift  = a << 2;
val andResult  = a and b
val orResult   = a or b
val xorResult  = a xor b
val rightShift = a shr 2
val leftShift  = a shl 2

Is As In

if(x instanceof Integer){ }

final String text = (String) other;

if(x >= 0 && x <= 10 ){}
if (x is Int) { }

val text = other as String

if (x in 0..10) { }

Smart Cast

if(a instanceof String){
  final String result = ((String) a).substring(1);
if (a is String) {
  val result = a.substring(1)

Switch / When

final int x = // value;
final String xResult;

switch (x){
  case 0:
  case 11:
    xResult = "0 or 11";
  case 1:
  case 2:
  case 10:
    xResult = "from 1 to 10";
    if(x < 12 && x > 14) {
      xResult = "not from 12 to 14";

    if(isOdd(x)) {
      xResult = "is odd";

    xResult = "otherwise";

final int y = // value;
final String yResult;

  yResult = "is Negative";
} else if(isZero(y)){
  yResult = "is Zero";
}else if(isOdd(y)){
  yResult = "is Odd";
}else {
  yResult = "otherwise";
val x = // value
val xResult = when (x) {
  0, 11 -> "0 or 11"
  in 1..10 -> "from 1 to 10"
  !in 12..14 -> "not from 12 to 14"
  else -> if (isOdd(x)) { "is odd" } else { "otherwise" }

val y = // value
val yResult = when {
  isNegative(y) -> "is Negative"
  isZero(y) -> "is Zero"
  isOdd(y) -> "is odd"
  else -> "otherwise"


for (int i = 1; i < 11 ; i++) { }

for (int i = 1; i < 11 ; i+=2) { }

for (String item : collection) { }

for (Map.Entry&ltString, String&gt entry: map.entrySet()) { }
for (i in 1..10) { }

for (i in 1..10 step 2) {}

for (item in collection) {}
for ((index, item) in collection.withIndex()) {}

for ((key, value) in map) {}


final List&ltInteger&gt numbers = Arrays.asList(1, 2, 3);

final Map&ltInteger, String&gt map = new HashMap&ltInteger, String&gt();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Java 9
final List&ltInteger&gt numbers = List.of(1, 2, 3);

final Map&ltInteger, String&gt map = Map.of(1, "One",
                                        2, "Two",
                                        3, "Three");
val numbers = listOf(1, 2, 3)

val map = mapOf(1 to "One",
                2 to "Two",
                3 to "Three")


for (int number : numbers) {

for (int number : numbers) {
  if(number > 5) {
numbers.forEach {

numbers.filter  { it > 5 }
       .forEach { println(it) }


final Map&ltString, List&ltInteger&gt&gt groups = new HashMap<>();
for (int number : numbers) {
  if((number & 1) == 0){
      groups.put("even", new ArrayList<>());


    groups.put("odd", new ArrayList<>());

val groups = numbers.groupBy {
                if (it and 1 == 0) "even" else "odd"


final List&ltInteger&gt evens = new ArrayList<>();
final List&ltInteger&gt odds = new ArrayList<>();
for (int number : numbers){
  if ((number & 1) == 0) {
  }else {
val (evens, odds) = numbers.partition { it and 1 == 0 }


final List&ltUser&gt users = getUsers();

Collections.sort(users, new Comparator&ltUser&gt(){
  public int compare(User user, User otherUser){
    return user.lastname.compareTo(otherUser.lastname);

// or

users.sort(Comparator.comparing(user -> user.lastname));
val users = getUsers()
users.sortedBy { it.lastname }


How to create a REST API with Node.js and LoopBack

how to API REST tutorial

In this post, we are going to learn how to use LoopBack Node.js framework  to create a fully functional REST API over MongoDB.

We will follow these steps:

1- Define the models in the database

2- Define the relations between models

3- Define users access levels


To follow this tutorial we will need NodeJS and MongoDB installed in our computer.


Install the LoopBack module.

sudo npm install loopback -g

Run Loopback and follow instructions.

slc loopback
[Node version -> 2.x, Stable version]
[Kind of application -> API server]

Move to the new folder.

cd "folder name"

We are going to do an e-commerce API for the example. We want to to store all date in a persistent way into a MongoDB database that will have Clients, Products and Comments.

In order to do so, we need to specify the route of the database. As it is not created yet, will create a new folder and connect it to MongoDB.

mkdir -p mongo/data
mongod --dbpath mongo/data

Then, in another terminal, we run the Loopback commands to create the database

We’ll call it “ecommerce”

slc loopback:datasource
? Enter the data-source name: MongoDB
? Select the connector for MongoDB: MongoDB (supported by StrongLoop)
Connector-specific configuration:
? Connection String url to override other settings (eg: mongodb://username:passw
? host: localhost
? port: 27017
? user:
? password:
? database: ecommerce
? Install loopback-connector-mongodb@^1.4 Yes

Once we generated the database, we can see the code generated by Loopback at the file model-config.json.

It is recommendable to change the attribute “dataSource”: “db” to the database we just created (“MongoDB”) at ACL,RoleMapping and Role.


To create a new collection (what would be a table), we’ll use the following command.

slc loopback:model

The way to define the data will be as the following example:

? Enter the model name: Customer
? Select the data-source to attach Customer to: MongoDB (mongodb)
? Select model's base class User *
? Expose Customer via the REST API? Yes
? Custom plural form (used to build REST URL):
? Common model or server only? common

*In this case is not needed to define more attributes because we are extending the “User” class that already have username, password, email and other needed attributes.

Now we are going to define the “Product” collection.

slc loopback:model
? Enter the model name: Product
? Select the data-source to attach Product to: MongoDB (mongodb)
? Select model's base class PersistedModel
? Expose Product via the REST API? Yes
? Custom plural form (used to build REST URL):
? Common model or server only? common
? Property name: name
invoke loopback:property
? Property type: string
? Required? Yes
? Default value[leave blank for none]:
? Property name: description
invoke loopback:property
? Property type: string
? Required? Yes
? Default value[leave blank for none]:
? Property name: category
invoke loopback:property
? Property type: string
? Required? Yes
? Default value[leave blank for none]:
? Property name: image
invoke loopback:property
? Property type: string
? Required? No
? Default value[leave blank for none]:
? Property name: label
invoke loopback:property
? Property type: string
? Required? No
? Default value[leave blank for none]:
? Property name: price
invoke loopback:property
? Property type: number
? Required? Yes
? Default value[leave blank for none]:

Now, the comments:

slc loopback:model
? Enter the model name: Comments
? Select the data-source to attach Comments to: MongoDB (mongodb)
? Select model's base class PersistedModel
? Expose Comments via the REST API? Yes
? Custom plural form (used to build REST URL):
? Common model or server only? common

Let’s add some Comments properties now.

? Property name: rating
invoke loopback:property
? Property type: number
? Required? Yes
? Default value[leave blank for none]: 5
? Property name: comment
invoke loopback:property
? Property type: string
? Required? Yes
? Default value[leave blank for none]:

Now we have all the collections defined, it’s time to define the relation between them.


Let’s review what we have done up to now.

On the one hand, we have the e-commerce Users and on the other hand we have the Products.

We also want the Users to post Comments about our Products.

So these would be the relations:

1- A product can have several comments.

2- A product can have several users commenting about it.

3- A comment belongs to determined product.


4- A user can post several comments.


5- A product can have several comments about it.

[insert schema here]

To define the relations between collections, we will use the following command:

slc loopback:relation

1- A product can have several comments.

slc loopback:relation
? Select the model to create the relationship from: Product
? Relation type: has many
? Choose a model to create a relationship with: Comments
? Enter the property name for the relation: comments
? Optionally enter a custom foreign key:
? Require a through model? No

2- A product can have several users commenting about it.

slc loopback:relation
? Select the model to create the relationship from: Product
? Relation type: has many
? Choose a model to create a relationship with: Customer
? Enter the property name for the relation: customers
? Optionally enter a custom foreign key:
? Require a through model? No

3- A comment belongs to determined product.

slc loopback:relation
? Select the model to create the relationship from: Comments
? Relation type: belongs to
? Choose a model to create a relationship with: Product
? Enter the property name for the relation: product
? Optionally enter a custom foreign key:

4- A user can post several comments.

slc loopback:relation
? Select the model to create the relationship from: Customer
? Relation type: has many
? Choose a model to create a relationship with: Comments
? Enter the property name for the relation: comments
? Optionally enter a custom foreign key: customerId
? Require a through model? No

5- A product can have several comments about it.

slc loopback:relation
? Select the model to create the relationship from: Comments
? Relation type: belongs to
? Choose a model to create a relationship with: Customer
? Enter the property name for the relation: customer
? Optionally enter a custom foreign key: customerId

With what we have done up to now

Up to this point, we already have the API and we can do some testing by this command.

node <project folder>/server/server.js


node .

Despite of this, we haven’t finished yet, as any user could use all the methods and CREATE and DELETE some data without any authentication, which drives us to the last step.


The first thing that we are going to do in this section is to create the users “admin” and “kike” (although you can change the last one for your username) and we will give to the administrator privileges to the user “admin”.

Loopback allows us to include a script that will run whenever we start the service, so we will use that to introduce these two users into the database.

So, we create a file at <our project folder>/server/boot/script.js and copy the following code:

module.exports = function(app) {
  var MongoDB = app.dataSources.MongoDB;

  MongoDB.automigrate('Customer', function(err) {
    if (err) throw (err);
    var Customer = app.models.Customer;

    {username: 'admin', email: '', password: 'abcdef'},
    {username: 'kike', email: '', password: 'abcdef'}
  ], function(err, users) {
  if (err) throw (err);
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;

  //create the admin role
    name: 'admin'
  }, function(err, role) {
    if (err) throw (err);
  //make admin
    principalType: RoleMapping.USER,
    principalId: users[0].id
    }, function(err, principal) {
      if (err) throw (err);

This will create two new users. A regular user (Kike) and an Admin user (obviously, admin). After that we create a Role admin and bind them together.

Now, let’s restrict the some accesses for Authenticated users:

We will use the Loopback Access Control List (ACL) by using this command:

slc loopback:acl

So first, let’s deny all kind of accesses:

slc loopback:acl
? Select the model to apply the ACL entry to: (all existing models)
? Select the ACL scope: All methods and properties
? Select the access type: All (match all types)
? Select the role All users
? Select the permission to apply Explicitly deny access

Once we have done this, let’s enable GET (READ) accesses for autheticated users:

slc loopback:acl
? Select the model to apply the ACL entry to: (all existing models)
? Select the ACL scope: All methods and properties
? Select the access type: Read
? Select the role Any authenticated user
? Select the permission to apply Explicitly grant access

And finally, allow Admins to perform all operations:

slc loopback:acl
? Select the model to apply the ACL entry to: (all existing models)
? Select the ACL scope: All methods and properties
? Select the access type: All (match all types)
? Select the role other
? Enter the role name: admin
? Select the permission to apply Explicitly grant access

Once we have done this, we finished and already have a fully functional REST API with Node.js.

We can run it and start playing with it with he following command:

node <project folder>/server/server.js

Cool, isn’t it? Now you can relax, take a cup of coffee and tell your coworkers how hard you have been working.