How to fix LaTeX Error: File `scrartcl.cls’ not found on Ubuntu

Problem:

You want to compile your LaTeX file on Ubuntu using latex or pdflatex but you see an error message like this:

! LaTeX Error: File `scrartcl.cls' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: cls)

Solution

sudo apt -y install texlive-latex-recommended

This will install, among many other LaTeX files, scrartcl.cls.

Posted by Uli Köhler in LaTeX, Linux

C++ equivalent of NumPy/PHP rad2deg

In order to convert radians to degrees, PHP provides the rad2deg function whereas Python’s NumPy library provides np.rad2deg.

In C++ there is no standard function to convert radians to degrees.

However, you can use this simple snippet:

#define _USE_MATH_DEFINES
#include <cmath>

/**
 * Convert the angle given in radians to degrees.
 */
template<typename F>
F rad2deg(F angle) {
    return angle * 180.0 / M_PI;
}

This will work for double, float etc. and returns the angle in degrees.

The formula is pretty simple:

\text{Degrees} = \frac{\text{Radians} \cdot 180°}{\pi}
Posted by Uli Köhler in C/C++, Mathematics

How to parse ISO8601 datetime in Python

The easiest way to parse a ISO8601 timestamp like 2019-05-29T19:50:55.463+02:00 is to install the maya library using e.g.

sudo pip3 install maya

In case you still use Python2, use pip instead of pip3.

After installing maya, use it like this:

import maya
result = maya.parse('2019-05-29T19:50:55.463+02:00').datetime()
# Result is a standard datetime object!
print(result)

This will print

2019-05-29 17:50:55.463000+00:00

Notice how the original timestamp from timezone +02:00 is automatically converted to a UTC datetime object.

maya can parse a lot of different formats e.g.

print(maya.parse('2019-05-29T19:50:55+02:00').datetime()) # No fractional seconds
print(maya.parse('2019-05-29T19:50:55').datetime()) # No timezone (UTC assumed)
print(maya.parse('2019-05-29 19:50:55').datetime()) # Not ISO8601
print(maya.parse('2019-05-29').datetime()) # 00:00:00 & UTC assumed

 

Posted by Uli Köhler in Python

What’s the formula for 2/3/4 parallel resistors?

Formula for 2 parallel resistors R1 and R2:

R_{total} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2}}

Python code:

rtotal = 1. / (1./r1 + 1./r2)

Formula for 3 parallel resistors R1 and R2:

R_{total} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2} + \frac{1}{R_3}}

Python code:

rtotal = 1. / (1./r1 + 1./r2 + 1./r3)

Formula for 4 parallel resistors R1 and R2:

R_{total} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2} + \frac{1}{R_3} + \frac{1}{R_4}}

Python code:

rtotal = 1. / (1./r1 + 1./r2 + 1./r3 + 1./r4)

 

Posted by Uli Köhler in Electronics, Python

How to disable Secure Boot on InsydeH20 UEFI BIOS / Acer Aspire A515-52-51EL

On my Acer Aspire A515-52-51EL Secure Boot is enabled by default.

When accessing the BIOS/UEFI by pressing the F2 key during boot, the Secure Boot option is [Enabled] and greyed out so I couldn’t change it.

In order to change it you need to temporarily set a supervisor password in the BIOS.

Go to the Security page and navigate to Set Supervisor Password.

Press enter. This will show a prompt to set a supervisor password.

Important: DO NOT use a hard-to-remember password here! I recommend using abc123 as a password and writing it down just in case. If you forget your supervisor password you WILL BRICK YOUR MACHINE! This password will only be used temporarily so you DO NOT want to use a secure password!

Enter the password, press return, enter the password again and press return again. On the top of the page, Supervisor password is should now read Set.

Now go to the Boot tab where you can now disable Secure Boot.

Warning: DO NOT SKIP THE NEXT STEP!

Now we will unset the supervisor password. Go to the Security tab again, go to Set Supervisor Password and press return.

Enter the password you used before (e.g. abc123), then press enter. In the Enter new password and Confirm New Password fields, DO NOT ENTER ANY PASSWORD! Just press return two times.

Double-check that Supervisor password is now read Clear. This means that we un-set our supervisor password.

Important: If Supervisor password is does not read Clear, repeat the last step to ensure there is no supervisor password set.

Now go to Exit, select Exit Saving Changes and press return. Select Yes and press Enter.

Even though we have unset the supervisor password, secure boot will stay disabled.

Posted by Uli Köhler in Hardware

How to check if secure boot is enabled on Ubuntu?

On the command line, run

sudo mokutil --sb-state​

This will tell you

SecureBoot enabled​_

if secure boot is currently active on your machine or

SecureBoot disabled

else.

In case you see an error message like

bash: command not found: mkoutil

you need to install mokutil first using

sudo apt install mokutil​_
Posted by Uli Köhler in Linux

How to fix C++ boost/array.hpp:118:61: error: expected primary-expression before ‘,’ token

In a legacy C++ project that is using Boost ProgramOptions. trying to compile it will yield this error message:

In file included from /usr/include/boost/lexical_cast/detail/converter_lexical.hpp:50:0,
                 from /usr/include/boost/lexical_cast/try_lexical_convert.hpp:42,
                 from /usr/include/boost/lexical_cast.hpp:32,
                 from /usr/include/boost/program_options/value_semantic.hpp:14,
                 from /usr/include/boost/program_options/options_description.hpp:13,
                 from /usr/include/boost/program_options.hpp:15,
                 from /home/uli/dev/myproject/datasplit.cpp:15:
/usr/include/boost/array.hpp: In member function ‘T& boost::array<T, N>::operator[](boost::array<T, N>::size_type)’:
/usr/include/boost/array.hpp:118:61: error: expected primary-expression before ‘,’ token
             return BOOST_ASSERT_MSG( i < N, "out of range" ), elems[i];

I didn’t find a satisfying way to fix this issue but it can be worked around fixing the issue in the source file:

First, open /usr/include/boost/array.hpp in your favourite editor as root (sudo!). I use nano.

Then, go to line 118 which reads:

return BOOST_ASSERT_MSG( i < N, "out of range" ), elems[i];

Replace that line by

BOOST_ASSERT_MSG( i < N, "out of range" );
return elems[i];

Also, 4 lines below what we just edited you’ll find another instance of

return BOOST_ASSERT_MSG( i < N, "out of range" ), elems[i];

Also replace that by

BOOST_ASSERT_MSG( i < N, "out of range" );
return elems[i];

Now. save the file and close your editor. Your code should compile now.

Posted by Uli Köhler in C/C++, GCC errors

How to fix numpy TypeError: Cannot cast ufunc subtract output from dtype(‘float64’) to dtype(‘int64’) with casting rule ‘same_kind’

Problem:

You are trying to do a simple arithmetic operation on a NumPy array but you see an error message like

TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'

Solution:

You are trying to substract a float from an int64 array. This does not work with operators like += or -=

Example:

import numpy as np

data = np.asarray([1, 2, 3, 4], dtype=np.int64) # This is an int array!

print(data - 5) # This works
print(data - 5.0) # This works as well
# This raises: Cannot cast ufunc subtract output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
data -= 5.0

Option 1 (preferred):

Use - instead of -=: Instead of data -= 5.0 use data = data - 5.0

Option 2:

Explicitly cast data to float (or the first dtype of your error message):

data = data.astype('float64')
# Now this works
data -= 5.0

This option is not preferred since doing it requires using the correct datatype. The first option works without regarding the actual datatype.

Posted by Uli Köhler in Python

How to fix ‘Configuring tzdata’ interactive input when building Docker images

Often, when installing deb packages in your Dockerfile, some packages will install tzdata as a dependency.

The tzdata installer will try to interactively prompt you for your location using

Configuring tzdata
------------------

Please select the geographic area in which you live. Subsequent configuration
questions will narrow this down by presenting a list of cities, representing
the time zones in which they are located.

 1. Africa      4. Australia  7. Atlantic  10. Pacific  13. Etc
 2. America     5. Arctic     8. Europe    11. SystemV
 3. Antarctica  6. Asia       9. Indian    12. US
Geographic area:

This will stall your image build.

In order to fix that, we’ll need to make the tzdata prompt non-interactive.

The preferred method is to add

ENV DEBIAN_FRONTEND=noninteractive

before the first RUN statements in your Dockerfile.

Alternatively you can run just the apt install or apt-get install command using DEBIAN_FRONTEND=noninteractive:

RUN DEBIAN_FRONTEND=noninteractive apt install -y tzdata

This will automatically select a default configuration for tzdata.

Posted by Uli Köhler in Container, Docker

How to install NodeJS 12.x on Ubuntu in 1 minute

Run these shell commands on your Ubuntu computer to install NodeJS 12.x:

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs

Instead of setup_12.x you can also choose other versions like setup_8.x. However, using this method, you can’t install multiple versions of NodeJS in parallel.

Source: Official nodesource documentation

Posted by Uli Köhler in Linux, NodeJS

What is a ‘headless’ program or application?

If you’re a backend programmer, you most likely have encountered the term of headless applications (like headless Java or headless Chromium) many times. But what does headless actually mean?

headless means it runs without a graphical user interface (GUI). In most cases, headless applications are command line applications or applications that are interfaced from a programming language.

When you open your browser on your Desktop or Laptop, you’ll see the browser window pop up. This window is a graphical user interface (GUI). Unless you are living under a rock, you have had your fair share of experience with GUIs and know how convenient they can be sometimes.

However, especially in the professional IT world, command line user interfaces are also common – mostly, because they can be used on servers and local PCs with a screen alike, and they are much easier to automate than GUIs.

If you have worked in application development for some time, you might know that GUI applications require a huge number of incredibly complex libraries to run. On Linux that includes the X11 server (X11 is the system that displays and arranges all the windows and other graphical features on your screen), some utility libraries for X11 and possibly some libraries to be able to create the high-level user interfaces in use in most applications today: While high-level GUIs consist of buttons and text inputs, low-level GUIs consist of pixel, colored areas and callback functions (from which the buttons and text inputs are built of).

As said before, headless applications run without a GUI. Under the right circumstances, this has two main advantages:

  • You don’t have to spend as much time developing a complex graphical user interface
  • You can easily run it on a server
Why can you run headless applications on a server but not normal GUI applications?

Firstly, as we said before, GUIs require a large number of complex libraries and software infrastructure to be present on a server. On many servers (like most Linux servers), this software is not installed by default – because installing it would eat up valuable resources like system memory (RAM), hard drive space and the system would be hard to maintain.

Contrary to common belief, running a GUI infrastructure on Linux (i.e. X server plus some utilities) does not require a screen or a dedicated graphics card. See our post on How to run X server using xserver-xorg-video-dummy driver on Ubuntu for an example on how to accomplish this.

Secondly, GUIs are hard to monitor, maintain and automate:

Imagine you have 25 servers running the same application on each of them. If that were a GUI application, you would have to look at 25 windows displaying the state of the application – not to mention the time spent to make all the windows display on your local screen reliably – or the development time spent to make the GUI

Using headless applications you can instead easily automate the task of monitoring the applications and therefore just display a summary on your local screen. Since you don’t have to spend time writing and maintaining GUIs, you can also spend your time more wisely.

Posted by Uli Köhler in Technologies

How to iterate all days of year using Python

To iterate all days in a year using Python you can use this function snippet:

from collections import namedtuple
from calendar import monthrange

Date = namedtuple("Date", ["year", "month", "day"])

def all_dates_in_year(year=2019):
    for month in range(1, 13): # Month is always 1..12
        for day in range(1, monthrange(year, month)[1] + 1):
            yield Date(year, month, day)

Usage example:

for date in all_dates_in_year(2019):
    print(date)

This will print (excerpt):

Date(year=2019, month=1, day=1)
Date(year=2019, month=1, day=2)
Date(year=2019, month=1, day=3)
[...]
Date(year=2019, month=2, day=27)
Date(year=2019, month=2, day=28)
Date(year=2019, month=3, day=1)
[...]
Date(year=2019, month=12, day=29)
Date(year=2019, month=12, day=30)
Date(year=2019, month=12, day=31)

You can also install my Python3 library UliEngineering using sudo pip3 install -U UliEngineering and then use all_dates_in_year() by importing it like this:

from UliEngineering.Utils.Date import *

 

Also see How to get number of days in month in Python

 

Posted by Uli Köhler in Python

How to get number of days in month in Python

If you want to find out how many days a month using Python use this snippet:

from calendar import monthrange

num_days = monthrange(2019, 2)[1] # num_days = 28

print(num_days) # Prints 28

The calendar module automatically takes into account leap years.

You can also use this function snippet:

from calendar import monthrange

def number_of_days_in_month(year=2019, month=2):
    return monthrange(year, month)[1]

# Usage example:
print(number_of_days_in_month(2019, 2)) # Prints 28

You can also install my Python3 library UliEngineering using sudo pip3 install -U UliEngineering and then use number_of_days_in_month() by importing it like this:

from UliEngineering.Utils.Date import *

 

Posted by Uli Köhler in Python

How to get unit/resolution of NumPy np.datetime64 object

NumPy’s datetime64 objects are represented as 64 bit integers (that’s what the 64 in the name means).

In order to find out what the resolution (e.g. us, ns etc) first install my Python 3 UliEngineering library using

sudo pip3 install -U UliEngineering

and then use datetime64_unit() from UliEngineering.Utils.NumPy like this:

from UliEngineering.Utils.NumPy import *

my_datetime = datetime64_now()
print(datetime64_resolution(my_datetime)) # Prints "us"
Posted by Uli Köhler in Python

How to get unit/resolution of NumPy np.timedelta64 object

In order to get the unit (e.g. us, ms, ns, …) of a np.timedelta64 object like

my_timedelta = np.timedelta64(625, 'us') # Unit is 'us'

first install my Python 3 UliEngineering library using

sudo pip3 install -U UliEngineering

and then use timedelta64_unit() from UliEngineering.Utils.NumPy like this:

import numpy as np
from UliEngineering.Utils.NumPy import *

my_timedelta = np.timedelta64(625, 'us')
print(timedelta64_resolution(my_timedelta)) # Prints "us"
Posted by Uli Köhler in Python

How to convert numpy timedelta (np.timedelta64) object to integer

If you have a NumPy np.timedelta64 object like

import numpy as np
my_timedelta = np.timedelta64(625, 'us')

a common task is to convert it to an integer.

This is often as easy as

my_timedelta.astype(int) # = 625, type: np.int64

This will give you the number (which is always an integer!) stored in the np.timedelta64 object, however it will ignore the unit  (e.g. us i.e. microseconds in our example).

To get the unit of the timedelta, first install UliEngineering using sudo pip3 install -U UliEngineering which you can then use like this:

import numpy as np
from UliEngineering.Utils.NumPy import *

my_timedelta = np.timedelta64(625, 'us')
print(timedelta64_resolution(my_timedelta)) # Prints "us"
Posted by Uli Köhler in Python

How to create a new numpy timedelta (np.timedelta64) object

There are two basic ways to create a new np.timedelta64 object:

Construct directly:

import numpy as np
my_timedelta = np.timedelta64(625, 'us')

Note that the constructor will only work with ints, i.e. np.timedelta64(625.5, 'us') won’t work. See

Construct as a difference between two np.datetime64 objects:

See How to get current datetime as numpy datetime (np.datetime64) for more details on how to get the current datetime as np.datetime64.

For any two np.datetime64 instances, we can compute the difference using

from datetime import datetime
import numpy as np

# There will be a minimal time difference between those two
dt1 = np.datetime64(datetime.now())
dt2 = np.datetime64(datetime.now())

my_timedelta = dt2 - dt1
print(my_timedelta) # For me, this prints "16 microseconds"
Posted by Uli Köhler in Python

How to get current datetime as numpy datetime (np.datetime64)

The simplest way of getting the current time as np.datetime64 object is to combine datetime.datetime.now() and the np.datetime64() constructor:

from datetime import datetime
import numpy as np

dt_now = np.datetime64(datetime.now())

print(dt_now)

Or use this function for convenience:

from datetime import datetime
import numpy as np

def datetime64_now():
    return np.datetime64(datetime.now())

dt_now = datetime64_now()
print(dt_now)

datetime64_now() is also available on my library UliEngineering.
Install using sudo pip3 install -U UliEngineering, then use like this:

from UliEngineering.Utils.NumPy import datetime64_now

dt_now = datetime64_now()
print(dt_now)
Posted by Uli Köhler in Python