Uli Köhler

http: How to get redirect location in Python

response = httpx.post("https://my.domain/api/redirect") 
# Get redirect location
if response.has_redirect_location:
    redirect_location = response.headers['Location']
else:
    redirect_location = None

 

Posted by Uli Köhler in Python

How to ‘wp package install’ in wpcli docker container

Using docker-compose with a config such as

# ...
  wpcli:
    depends_on:
      - wordpress
    image: wordpress:cli
    user: 1000:1000
    command: tail -f /dev/null
    volumes:
      - ./wordpress:/var/www/html
    environment:
        - WORDPRESS_DB_HOST=mariadb:3306
        - WORDPRESS_DB_USER=wordpress
        - WORDPRESS_DB_NAME=wordpress
        - WORDPRESS_DB_PASSWORD=${MARIADB_PASSWORD}

You need to install the package in the container as root to avoid

Error: Composer directory '/.wp-cli/packages' for packages couldn't be created: mkdir(): Permission denied

Use the following command to install a package

docker-compose exec -u root wpcli wp package install wp-cli/profile-command:@stable --allow-root
Posted by Uli Köhler in Docker, Wordpress

How to change admin password using wpcli on docker-compose

docker-compose exec wpcli wp user update admin --user_pass='ee7saeNg9Moh5shoodocaixaingoov'

This works, for example with a docker-compose wpcli config like:

wpcli:
    depends_on:
      - wordpress
    image: wordpress:cli
    user: 1000:1000
    command: tail -f /dev/null
    volumes:
      - ./wordpress:/var/www/html
    environment:
        - WORDPRESS_DB_HOST=mariadb:3306
        - WORDPRESS_DB_USER=wordpress
        - WORDPRESS_DB_NAME=wordpress
        - WORDPRESS_DB_PASSWORD=${MARIADB_PASSWORD}

 

Posted by Uli Köhler in Docker, Wordpress

How to identify which docker container is consuming 100% CPU

  • Open htop and press F6 and select PERCENT_CPU. Repeat until you’ve sorted descending by CPU consumption
  • Now identify the PID (process ID) of the offending process consuming 100% CPU

docker inspect -f '{{.State.Pid}}, {{.Name}}' $(docker ps -q)
  • Now identify the line with the PID, e.g.
8599, /wordpress-myblog-btronik_mariadb_1

Now you know which container is consuming 100% CPU.

Posted by Uli Köhler in Docker

How to find list of docker containers with PID (process ID)

The following command will show you a list of all running docker containers with their PIDs

docker inspect -f '{{.State.Pid}}, {{.Name}}' $(docker ps -q)

Example output:

9046, /wordpress-myblog-btronik_wpcli_1
8848, /wordpress-myblog-btronik_wordpress_1
8795, /wordpress-myblog-btronik_phpmyadmin_1
8599, /wordpress-myblog-btronik_mariadb_1
3627, /wordpress-secondpage_wpcli_1
3505, /wordpress-mywebsite_wpcli_1
3172, /wordpress-secondpage_wordpress_1
2907, /wordpress-mywebsite_wordpress_1
2646, /wordpress-secondpage_mariadb_1
2518, /webmail_roundcube_1
2323, /wordpress-mywebsite_mariadb_1
2303, /redmine-mywebsite_mariadb_1

 

Posted by Uli Köhler in Docker

JLCPCB PCB assembly: List of known “Standard only” parts

For some parts, JLCPCB doesn’t support Economic PCBA but charges 25$ per assembly side for Standard PCBA.

You can find out which parts are Standard only by checking the JLCPCB component listStandard only parts are marked Standard only directly after the part number column while parts supporting economic PCBA are not marked at all.

Know parts include, according to my own research (this list is non-exhaustive and I don’t take any responsibility for correctness, beyond what’s legally required):

 

Posted by Uli Köhler in Electronics

Angular: How to format number without any decimals using ‘number’ pipe

In Angular, you can use the number pipe to format a number without decimals by specifying '1.0-0' as the format. Here is how you can do it:

<div class="value">{{myvalue | number:'1.0-0'}}</div>

In order for this to work, you need to import CommonModule:

imports: [
  CommonModule
],

 

Posted by Uli Köhler in Angular

Angular HttpClient: Return both Blob and response Headers

export interface BlobAndHeaders {
  blob: Blob;
  headers: Headers;
}

myApi(arg: string): Observable<BlobAndHeaders> {
  return this.http.get<BlobAndHeaders>(`${this.baseURL}/api/myapi`, {
    observe: 'response',
    responseType: 'blob' as 'json',
    params: {arg: arg},
  }).pipe(map(
    response => {
      if(response.body === null) {
        throw new Error('No data received');
      }
      return {"blob": response.body, "headers": response.headers};
    }
  ));
}

 

Posted by Uli Köhler in Angular, Typescript

How to fix Python TypeError: lru_cache() got an unexpected keyword argument ‘max_size

Problem:

In Python, you’re using code such as

from functools import lru_cache

@lru_cache(max_size=128)
def myfunc(arg: str):
   # ...
   return arg + "x"

but you see an error message such as

Traceback (most recent call last):
  File "/dev/shm/test.py", line 3, in <module>
    @lru_cache(max_size=128)
TypeError: lru_cache() got an unexpected keyword argument 'max_size'

Solution:

You’ve mis-spelled the argument to @lru_cache: You wrote max_size with underscore whereas it actually is maxsize without underscore.

Posted by Uli Köhler in Python

Which distributors can JLCPCB source components from?

Please note: I can’t guarantee any of this, this is just according to my own research in April 2024

JLCPCB can order components from the following distributors:

  • DigiKey
  • Mouser
  • TTI
  • Chip1stop
  • Verical
  • Sager
  • Arrow
  • Element14 UK
  • Future
  • Powell
  • Avnet
  • Element
  • Onlinecomponents
  • Rutronik
  • CoreStaff
  • TME
Posted by Uli Köhler in Electronics

JLCPCB PCBA assembly price overview

This post summarizes JLCPCB fees. Please note that this is according to my own research in April 2024 and I can’t guarantee any of these prices or price structures in any way.

Economic vs standard PCBA

  • Economic PCBA: One-side only, 0$
  • Standard PCBA, 25$ for one-sided PCBA, 50$ for two-sided PCBA

Some parts such as ESP32 modules or WS2812-style LEDs force you to select standard PCBA.

See JLCPCB PCB assembly: List of known Standard only parts for more details.

Basic vs extended components

  • Basic components: 0$ per component type
  • Extended components: 2.74$ per component type

SMT Assembly fees per solder joint

  • 0.0017$ per SMD pin

THT fees

  • Manual assembly fee: 0.02$ per THT pin.
  • Hand soldering3.22$, not sure what makes up that price for my PCB but it’s approximately 70% of the manual assembly fee.

Other fees

  • Special component fee: For USB-C connectors such as HC-TYPE-C-16P-01A, e.g. €0.1382 per component type (not per individual component)
  • Stencil: 1,38€ for a 75x100mm PCB, 5pcs, unclear how this is computed
  • Setup fee: 7,37€ for a 75x100mm PCB, 5pcs, unclear how this is computed
  • Panel: 0,00€, unclear how this is computed
  • Large size: 0.00€, unclear how this is computed
  • Components: How much your components cost, no additional markup.

 

Posted by Uli Köhler in Electronics

How to iterate rows of a pandas DataFrame with timestamp index

You can use df.iterrows() normally:

import pandas as pd
import numpy as np

# Assuming 'df' is your DataFrame
# For demonstration, let's create a sample DataFrame
dates = pd.date_range('2023-01-01', periods=5)
data = np.random.randn(5, 2)
df = pd.DataFrame(data, index=dates, columns=['A', 'B'])

# Iterating over rows
for index, row in df.iterrows():
    print(f"Index: {index}, A: {row['A']}, B: {row['B']}")

Note that index is a pd.Timestamp.

Posted by Uli Köhler in pandas, Python

How to drop multiple rows from pandas DataFrame by index

import pandas as pd
import numpy as np

# Create a sample DataFrame with datetime index
dates = pd.date_range('2023-01-01', periods=10)
data = np.random.randn(10, 2)
df = pd.DataFrame(data, index=dates, columns=['A', 'B'])

# Timestamps to drop
timestamps_to_drop = [pd.Timestamp('2023-01-03'), pd.Timestamp('2023-01-05'), pd.Timestamp('2023-01-07'),
                      pd.Timestamp('2023-01-08'), pd.Timestamp('2023-01-10')]

# Drop rows
df_filtered = df.drop(index=timestamps_to_drop)

 

Posted by Uli Köhler in pandas, Python

How to fix “snap refresh”: snap “…” has running apps

Problem:

You want to update your snap, e.g. signal-desktop, but when you try to snap refresh it, you see the following error message:

Error: cannot refresh "signal-desktop": snap "signal-desktop" has running apps (signal-desktop),
        pids: 471050,471137,471138,471189,471204,471248

Solution:

You can’t stop the running apps via snap. Just kill them using killall, for example:

killall signal-desktop && sudo snap refresh signal-desktop

Alternatively, you can kill the PIDs listed in the error message (you need to separate them by space, not by comma):

kill 471050 471137 471138 471189 471204 471248

 

Posted by Uli Köhler in Linux

How to initialize your KiCAD 8 project on the command line

TL;DR:

Inside the directory where you want to create the project, run

wget -qO- https://raw.githubusercontent.com/ulikoehler/KiCAD-ProcessAutomation/master/InitializeKiCad8Project.sh | bash /dev/stdin MyProject

You should replace MyProject (at the end of the command) with your project name.

Note: This will initialize an empty KiCAD project without any libraries. This is equivalent to creating a new project in KiCAD itself (using the GUI).

Continue reading →

Posted by Uli Köhler in Electronics, KiCAD, Shell

How to fix pyspice OSError: cannot load library ‘libngspice.so’

Problem:

When trying to run a PySpice program, you see an error message such as

OSError: cannot load library 'libngspice.so': libngspice.so: cannot open shared object file: No such file or directory.  Additionally, ctypes.util.find_library() did not manage to locate a library called 'libngspice.so'

Solution:

Install libngspice, often called libngspice0.

On Ubuntu, install it using

sudo apt -y install libngspice0-dev

You need to install the -dev library since libngspice0 only contains libngspice.so.0 whereas the -dev library contains libngspice.so which is required by pyspice.

Posted by Uli Köhler in Python, SPICE

STM32 HAL PlatformIO LED blink example

In the autogenerated main.c, use the following while() loop:

/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */
  HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, GPIO_PIN_SET);
  HAL_Delay(1000);
  HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, GPIO_PIN_RESET);
  HAL_Delay(1000);
}
/* USER CODE END 3 */

On STM32H7 Nucleo boards, this will toggle the green LED.

Posted by Uli Köhler in C/C++, PlatformIO, STM32

How to fix Nextcloud docker container permissions

docker-compose exec nextcloud chown -vR www-data:www-data /var/www/html

 

Posted by Uli Köhler in Nextcloud

What are the cheapest general purpose SMD diodes?

Typically some 1N4001…1N4007 in SOD-123 or SOD-123FL package is the cheapest available diode. It is available from many manufacturers and at all distributors.

The typical rating is:

  • 1A forward current
  • 1000V reverse voltage
  • Instantaneous forward voltage of <=1V @1A

On LCSC, a full reel (3000pcs) of SOD4007-MS by MSKSemi costs just 6,60€

Posted by Uli Köhler in Components

What cheap general purpose MOSFET to use?

The 2N7002 or 2N7002K MOSFET is one of the best MOSFETs to use if you just want to have a general purpose switching FET.

  • 60Vds
  • 300mA
  • 1.9Ohm RDSon

It or its variants is available from many manufacturers and at all distributors.

On LCSC, for example, one reel of 2N7002 from chinese manufacturer HL, only costs 15.90€, that is 0,0053€/pc

Posted by Uli Köhler in Components, Electronics