Posts on Manuel Pineda https://pin3da.github.io/posts/ Recent content in Posts on Manuel Pineda Hugo -- gohugo.io en Sat, 06 Apr 2024 11:57:24 +0200 Installing Bazel in Fedora https://pin3da.github.io/posts/install-bazel-fedora/ Sat, 06 Apr 2024 11:57:24 +0200 https://pin3da.github.io/posts/install-bazel-fedora/ Ref https://bazel.build/install/compile-source#bootstrap-bazel. Download from source Download links are available at https://github.com/bazelbuild/bazel/releases. Note: It requires downloading the distribution artifacts (dist), otherwise fails to find PROTOC :thinking_face:. More information in https://github.com/bazelbuild/bazel/issues/3801. Dependencies Fedora doesn’t have build-essential, but it has a concept for groups of packets, the following worked: sudo dnf groupinstall "Development Tools" "Development Libraries" sudo dnf install java-latest-openjdk java-latest-openjdk-devel Self-contained binary This can be moved/copied to any place, e.g. cp output/bazel /usr/bin/bazel Ref https://bazel.build/install/compile-source#bootstrap-bazel.

Download from source

Download links are available at https://github.com/bazelbuild/bazel/releases.

Note: It requires downloading the distribution artifacts (dist), otherwise fails to find PROTOC :thinking_face:. More information in https://github.com/bazelbuild/bazel/issues/3801.

Dependencies

Fedora doesn’t have build-essential, but it has a concept for groups of packets, the following worked:

sudo dnf groupinstall "Development Tools" "Development Libraries"

sudo dnf install java-latest-openjdk java-latest-openjdk-devel

Self-contained binary

This can be moved/copied to any place, e.g. cp output/bazel /usr/bin/bazel

]]>
Using Fedora on a Framework Laptop https://pin3da.github.io/posts/framework/ Fri, 23 Jun 2023 18:33:51 +0200 https://pin3da.github.io/posts/framework/ I recently switched to a Framework laptop. They suggest Fedora as their linux distro, so I decided to give it a try despite being a long-time Debian user. This post aims to document some of the issues I had and how to solve them. Official guideline The framework team has amazing support. Their documentation just worked out of the box. https://guides.frame.work/Guide/Fedora+38+Installation+on+the+Framework+Laptop+13/165 The only small change I added was the tap-buttom-map configuration in Gnome to something sensible: I recently switched to a Framework laptop. They suggest Fedora as their linux distro, so I decided to give it a try despite being a long-time Debian user. This post aims to document some of the issues I had and how to solve them.

Official guideline

The framework team has amazing support. Their documentation just worked out of the box.

https://guides.frame.work/Guide/Fedora+38+Installation+on+the+Framework+Laptop+13/165

The only small change I added was the tap-buttom-map configuration in Gnome to something sensible:

gsettings set org.gnome.desktop.peripherals.touchpad tap-button-map "lmr"

Installing i3

I’ve also been using i3 wm for a long time. This worked pretty well, specially if you are not resource constrained and can run it on top of Gnome (e.g. using gnome flashback).

This time it didn’t work for me, since the new Gnome settings work on Wayland and i3 is not compatible with it.

Installing sway

Fortunatelly, there is a drop-in replacement: Sway. It also happens to be that Fedora supports an official spin with it.

I re-installed Fedora using the Sway spin and it almost worked out of the box.

Small problems

Note: In order to update the config, you can copy the default config (/etc/sway/config) to ~/.config/sway/config and edit it there.

1. Scaling

For some reason the default scaling is set to 2.0, which is too much. To solve it you need to get the name of your display by doing:

swaymsg -t get_outputs

You will see the name of the output (e.g. “DP-3”) and the current scaling factor.

Then you can update the scaling to a reasonable value in the sway config:

output eDP-1 scale 1.25

2. Missing fonts

Some of the icons were broken, I installed fontawesome sudo dnf install fontawesome-fonts which fixed most of the issues. For the other icons I went to the waybar configuration and changed them.

3. Touchpad

It was not working by default. The solution was very similar to the scaling issue. First ran swaymsg -t get_inputs, look the name of the touchpad and then add a new entry to the sway config:

input "<ID from prev command>_Touchpad"  {
      tap enabled
      tap_button_map lmr
}

Thoughts

Overall I’m very happy with Fedora + Sway spin. It is easy to configure and it works well with the Framework hardware.

]]>
Advent of Kotlin https://pin3da.github.io/posts/advent-of-kotlin/ Tue, 22 Dec 2020 15:20:52 +0100 https://pin3da.github.io/posts/advent-of-kotlin/ Since 2018 I started participating in Advent of Code with the goal of learning new programming languages. This year I chose kotlin, and the experience was very good. I&rsquo;ll list some of the language features I liked so far. Sealed Classes For Day&rsquo;s 14 solution I wanted to have a class Entry and different subclasses of it. The only difference with normal OOP inheritance is that I wanted to restric all the object to belong exactly to a single subclass. Since 2018 I started participating in Advent of Code with the goal of learning new programming languages. This year I chose kotlin, and the experience was very good. I’ll list some of the language features I liked so far.

Sealed Classes

For Day’s 14 solution I wanted to have a class Entry and different subclasses of it. The only difference with normal OOP inheritance is that I wanted to restric all the object to belong exactly to a single subclass. It turns out that sealed classes are designed for this behavior.

sealed class Entry
data class Mask(val mask: CharArray) : Entry()
data class Mem(val addr: Long, val value: Long) : Entry()

When statement

Now, in order to evaluate the different kinds of Entry we need to conditionally check its “real” type. This is a good use case for the when statement:

when (entry) {
  is Mask -> mask = entry.mask
  is Mem -> memory[entry.addr] = applyMask(entry.value, mask)
}

Since the class was sealed, the compiler knows all the possible subclasses and will verify that there is a proper evaluation for all of them. For instance, if we add a new subclass of Entry we will get an error in the code above (which would be uncaught otherwise).

If we add the subclass Extra, the compiler will show the following error: 'when' expression must be exhaustive, add necessary 'is Extra' branch or 'else' branch instead.

Another nice property of the when statement is that we can use it for conditional branching executions (an statement), but also as an expression.

  • Conditional execution, this is very similar to switch in other programming languages (nothing surprising here):
    val a = 10
    when (a) {
        3 -> println("first condition")
        4 -> println("second condition")
        else -> println("else")
    }
  • Statement: This allows to reduce unnecessary mutability in the message, unlike the if alternative:
    // Immutable (defined as val)
    val msg = when(a) {
        3 -> "first condition"
        4 -> "second condition"
        else -> "else"
    }
    // Mutable (defined as var)
    var msg = "else"
    if (a == 3) {
        msg = "first condition" 
    } else if (a == 4) {
        msg = "second condition"
    }

Note: Initially I thouhgt that having val and var was very confusing, but in practice I found it handy and easy to remember ¯\(ツ)

Smart Cast

Kotlin keeps track of the results of the is operator, which becames really handy in the case you need to downcast an object. Based of the code above, let’s check the differences between Java and Kotlin.

if (expr instanceof Mask) {
    // cast needed in order to access "Mask" members.
    System.out.println(((Mask)expr).mask);
}
if (expr is Mask) {
   // No cast needed.
   print(expr.mask)
}

Functional flavor

After a few solutions I got used to the functional-like approach that kotlin uses, the support for lambda functions is really good and the code ends being clear and concise. This will also help to reduce mutablility in some places.

Example, let’s suppose we have a file 01.in with several lines representing integer numbers, and we want to compute the sum of all of them.

// Both variables can be immutable.
val numbers = File("data/01.in").readLines().map { it.toInt() }
val sum = numbers.sum()
// Do something else with numbers
// Both variables must be mutable.
var numbers = mutableListOf()
for (line in File("data/01.in").readLines()) {
    numbers.add(line.toInt())
}
var sum = 0
for (n in numbers) {
    sum += n
}
// Do something else with numbers

Data Classes

In most of the challenges I ended creating classes that only hold information, and use those classes in maps or sets (which require some sort of comparator or hash). I also often want to print these objects.

In C++ I would end doing something like:

struct Entry {
    int add;
    long value;
    // Default comparator since C++ 20: https://en.cppreference.com/w/cpp/language/default_comparisons
    auto operator<=>(const Entry&) const = default;
}

ostream& operator<<(ostream& os, const Entry& entry) {
    os << '{' << entry.add << ": " << entry.value << '}';
    return os;
}

But in kotlin, it is a one-liner :D.

data class Entry(val add: Int, val value: Long)

Next ?

I will keep trying Kotlin in other scenarios, and update this post if I found somethig interesting. Also, if you have interesting ideas for next year’s advent of code, please let me know! (contact in the “about” page of this site).

]]>
¿Las competencias de programación son importantes en la vida laboral? https://pin3da.github.io/posts/programming-contests/ Wed, 28 Nov 2018 14:09:38 -0200 https://pin3da.github.io/posts/programming-contests/ Actualmente existen muchas opiniones contradictorias acerca de si las competencias de programación son útiles o no, a continuación contaré por que creo que son bastante importantes bajo mi experiencia. No duden en comentar y discutir lo escrito en este blog. ¿Qué son las competencias de programación? Son como las olimpiadas de matemáticas, pero con computadores. En este tipo de competencias se presenta una serie de retos de diversos temas, por ejemplo, estructuras de datos, algoritmos, geometría, física, teoría de grafos, entre otros. Actualmente existen muchas opiniones contradictorias acerca de si las competencias de programación son útiles o no, a continuación contaré por que creo que son bastante importantes bajo mi experiencia. No duden en comentar y discutir lo escrito en este blog.

¿Qué son las competencias de programación?

Son como las olimpiadas de matemáticas, pero con computadores.

En este tipo de competencias se presenta una serie de retos de diversos temas, por ejemplo, estructuras de datos, algoritmos, geometría, física, teoría de grafos, entre otros. Se deben escribir programas de computador (individualmente o por equipos) para resolver dichos problemas.

¿Qué es la vida laboral?

Es una competencia de programación con duración indefinida donde nos pagan por resolver problemas. También se escriben programas de computador (individualmente o por equipos) para resolver dichos retos.

Respuesta a la pregunta original:

Aquí las razones por las cuales considero que las competencias de programación son importantes en la vida laboral, trataré de hacer un paralelo de las habilidades adquiridas y como se usan en la industria:

  • Habilidades para resolver problemas: Generalmente en las competencias de programación debemos resolver los retos de la manera más eficiente posible, para esto debemos conocer entre otras cosas, la complejidad computacional de nuestras soluciones, estructuras de datos y técnicas de programación. Cuando aplicamos estos conocimientos en nuestro trabajo, escribimos programas más rápidos, más eficientes y generalmente más simples.
  • Trabajo en equipo: Muchas competencias se realizan en equipos, generalmente de 2 o 3 personas. Esto es una experiencia increíble ya que nos ayuda a buscar formas para comunicar mejor nuestras ideas, también nos ayuda a comprender las reacciones de nuestros compañeros y a mantener un ambiente cómodo para todos. Supremamente importante en la vida laboral.
  • Revisión de código: Esto está relacionado con el punto anterior, generalmente es necesario leer código de nuestros compañeros y que ellos lean el nuestro para compartir soluciones y discutir ideas. Cuando tenemos equipos sólidos, se tiende a escribir el código de la manera más clara posible y con algún tipo de convención para que todos puedan entenderlo más fácilmente. Esto es comparable con algún tipo de pair programming (dado que en las competencias sólo se puede usar un computador por equipo) o el famoso code review. Incluso en las competencias individuales, se suele leer el código de competidores avanzados (después de terminada la competencia) para encontrar mejores maneras de solucionar los problemas. Esto nos ayuda mucho a comprender el código de las demás personas.
  • Búsqueda de errores (bugs): Todo programa de computador tiene una alta probabilidad de errores. En las competencias de programación, parte de nuestro trabajo es eliminar dichos errores de nuestros programas o los de nuestros compañeros. Esto es una habilidad que personalmente valoro mucho y que hace una gran diferencia en la vida laboral.
  • Pruebas unitarias: Cada uno de los retos, viene con un conjunto de datos para probar si nuestro código resuelve correctamente el problema o no. Esto crea el ambiente perfecto para escribir nuestro código de tal forma que podamos comprobar su salida para una entrada específica, de igual forma como lo haríamos con unit test en cualquier programa de nuestra vida laboral. En las competencias incluso existen casos de prueba los cuales podemos conocer antes de resolver el problema (parecido a lo que se pretende con TDD).
  • Preparación para entrevistas: La mayoría de las empresas (principalmente los gigantes como google o facebook) utilizan preguntas muy similares a los retos que encontramos en las competencias de programación para sus entrevistas. Al practicar constantemente podemos incrementar nuestras posibilidades de encontrar un buen trabajo (:

¿Dónde puedo practicar?

Existen muchos sitios en internet donde resolver retos de programación, entre mis favoritos están:

Conclusión

Las competencias de programación no cubren el 100% de las habilidades que necesitamos para ser buenos desarrolladores pero son un gran complemento para lograrlo.

No dudes en compartirnos tu opinión o las dudas que puedas tener al respecto.

]]>