Programming languages

How to change CMake object file suffix from default ‘.o’

In order to configure CMake to use an alternate object file suffix (default: .o on Linux) use these lines in your CMakeLists.txt:

set(CMAKE_C_OUTPUT_EXTENSION ".rel")
set(CMAKE_CXX_OUTPUT_EXTENSION ".rel")

This example changes the output extension from .o to .rel (which is required for the SDCC compiler). Be sure to replace ".rel" by your desired output suffix.

Note that in order for these to take effect, you might need to completely remove CMakeCache.txt, CMakeFiles & cmake_install.cmake:

rm -rf CMakeCache.txt CMakeFiles cmake_install.cmake

 

Posted by Uli Köhler in C/C++, CMake

How to force the_date() / get_the_date() to a specific locale

The WordPress function the_date() and get_the_date() always return the date / time in the locale format defined by the language setting of the current WordPress installation.

What if you need to get the date in a specific locale, e.g. english?

Setting the wordpress language to the target locale will successfully achieve this, but will also change the language of other parts of WordPress and is therefore often not an option.

In case you can’t do that and you have to find a programmatic solution, this is my way to force

<?php the_date('r', '', '', TRUE); ?>

to a specific locale ("C" i.e. plain english in this case)

<?php
    setlocale(LC_TIME, "C"); // Set to target locale (in which you want the date to be formatted
    echo strftime("%a, %d %b %Y %H:%M:%S %z", get_post_time('U', TRUE)); // Parse wordpress time and format it again
    setlocale(LC_TIME, "de_DE"); // Set back to the original locale!
?>

Since the_date() ignores setlocale() calls, we use PHP’s strftime() to work around this.

First, we set the target tocale (the locale for the date to be formatted in) using setlocale(LC_TIME, "C"); Replace "C" by your target locale! "C" is a good choice if you want plain english.

Then, we get the post date & time (the same date & time that is used / returned by the_date() & get_the_date()) using get_post_time('U', TRUE); . "U" means return as Unix timestamp. TRUE is very important here since it tells get_post_time() to return the timestamp as UTC. If you don’t use TRUE here, your dates will be offset by several hours (depending on your timezone) in case they are not UTC already.

After that, we run strftime() to format the timestamp. You need to insert your desired format string here. In my case, the format string is "%a, %d %b %Y %H:%M:%S %z" which is a RFC2822 date. Note that using this method, the timezone (%z) will always be +0000 since it’s formatted as a UTC date. However, the timezone offset will be correctly accounted for.

As a last step, we re-set the original locale using setlocale(LC_TIME, "de_DE"); . This avoids affecting other function, e.g. in other plugins. You need to insert the correct (original) locale here. In my case, I know the correct locale is "de_DE", but in your case this may differ.

Posted by Uli Köhler in PHP, Wordpress

How to fix Python ‘ImportError: No module named wx’ on Ubuntu

Problem:

You want to run a Python script, e.g. Pronterface, but you see an error message like this:

wxPython is not installed. This program requires wxPython to run.
Traceback (most recent call last):
  File "./pronterface.py", line 23, in <module>
    import wx  # NOQA
ImportError: No module named wx

Solution:

sudo apt install python-wxtools

 

Posted by Uli Köhler in Python

How to fix LaTeX error File `environ.sty’ 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 `environ.sty' not found.

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

Solution

sudo apt -y install texlive-latex-extra

This will install, among many other LaTeX files, environ.sty.

Posted by Uli Köhler in LaTeX, Linux

How to fix LaTeX error Package babel Error: Unknown option `ngerman’ on Ubuntu

Problem:

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

! Package babel Error: Unknown option `ngerman'. Either you misspelled it
(babel)                or the language definition file ngerman.ldf was not foun
d.

See the babel package documentation for explanation.
Type  H <return>  for immediate help

Solution

sudo apt -y install texlive-lang-german

This will install, among many other LaTeX files, the files for the ngerman language.

Posted by Uli Köhler in LaTeX, Linux

How to fix Ubuntu LaTeX ! I can’t find file `ecrm1200′.

Problem:

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

kpathsea: Running mktexmf ecrm1200
! I can't find file `ecrm1200'.
<*> ...ljfour; mag:=1; nonstopmode; input ecrm1200
                                                  
Please type another input file name
! Emergency stop.
<*> ...ljfour; mag:=1; nonstopmode; input ecrm1200
                                                  
Transcript written on mfput.log.
grep: ecrm1200.log: No such file or directory
mktextfm: `mf-nowin -progname=mf \mode:=ljfour; mag:=1; nonstopmode; input ecrm1200' failed to make ecrm1200.tfm.
kpathsea: Appending font creation commands to missfont.log.

! Font T1/cmr/m/n/12=ecrm1200 at 12.0pt not loadable: Metric (TFM) file not fou
nd.
<to be read again> 
                   relax 
l.105 \fontencoding\encodingdefault\selectfont

Solution

sudo apt -y install texlive-fonts-recommended

This will install, among many other LaTeX files, ecrm1200.mf and ecrm1200.tfm.

.

Posted by Uli Köhler in LaTeX, Linux

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 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 install NodeJS 14.x LTS on Ubuntu in 1 minute

Newer version 16 available: How to install NodeJS 16.x LTS on Ubuntu in 1 minute

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

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

Instead of setup_14.x you can also choose other versions like setup_12.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

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