Home Interests Raspberry Pi

How to Configure a Static IP Address on the Raspberry Pi

Making things a little less dynamic.
howchoo   (467)
September 15, 2023
8 minutes

Share

You’ll Need 1

What you’ll need
Interests
Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.
Posted in these interests:
pi • 92 guides

The network capabilities on the Raspberry Pi make it possible to create some really fun projects. Once in a while, you’ll come across a project that could benefit from a static IP address. If you’re using your Raspberry Pi for storage as a NAS device, an FTP server—or any other kind of server for that matter—a static IP address can be a big help.

1 – Update Raspberry Pi OS

This guide should work with any Raspberry Pi using Raspberry Pi OS (formerly Raspbian). Make sure your copy of is up to date. If you’re not sure where to begin, visit our guide on how to update Raspberry Pi OS.

How to Install Raspberry Pi OS on Your Raspberry Pi
Get the new official Raspberry Pi OS on your Pi.

2 – Find your router IP address

We’ll need both your router IP address and name server IP. We can find this information by running a few commands in a terminal on the Pi. Remote into the Pi using SSH or open a terminal window from within Raspberry Pi OS.

How to Connect to a Raspberry Pi Remotely via SSH
The preferred (and most common) method of connecting to your Pi to run commands.

To find your router IP address, enter the following command:

ip r | grep default

The router IP address will appear after the text “default via”—take note of it. The name server can be found in the resolv.conf file. Open it using the following command.

sudo nano /etc/resolv.conf

Take note of the name server IP address and close the file with CTRL + X.

3 – Edit the dhcpcd file on the Raspberry Pi

The static IP is set by adding it to a file on the Raspberry Pi. In the terminal window, run the following command to edit the dhcpcd.conf file.

sudo nano /etc/dhcpcd.conf

4 – Set the static IP address

This document has a few lines of code that can be activated by removing the # to the left of each line. Use the following ledger to properly set your static IP address.

  • Network = If you’re using a wired connection, set this to eth0. If you’re using a wireless connection, set this to wlan0.
  • Static_IP = This is the static IP address you want to assign to the Raspberry Pi.
  • Router_IP = This is the IP address for the router.
  • Name_Server = This is the name server address. You can use another DNS IP here if you’d like.

Enter your information into the file, be sure to remove the  brackets. Check the screenshot for an example.

interface 
static ip_address=/24
static routers=
static domain_name_servers=

When that’s completed, save the file using CTRL + X.

5 – Test the static IP address

When the changes have been made, restart the Raspberry Pi. Now is a good time to test your project and make sure the IP address isn’t changing. Disconnect and reconnect your Pi from the network. If the IP address changes, verify the information in the previous step saved properly. If it stays the same, congratulations! You’ve set a static IP on the Raspberry Pi.

NEXT UP

How to Run a Minecraft Server on the Raspberry Pi

A whole world trapped inside your Pi.
howchoo   (467)
December 7, 2023

There are several ways to go about running a Minecraft server on the Raspberry Pi. In this guide, I’ll cover how to install Nukkit—a cross-platform Minecraft server that’s super easy to set up on the Raspberry Pi. This server should work with PCs, consoles, and tablets running Minecraft 1.14. I’ll be using a Raspberry Pi

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests DevOps

How to Add a Health Check to Your Docker Container

howchoo   (467)
September 15, 2023
12 minutes

Share

Interests
Posted in these interests:
devops • 3 guides
docker • 4 guides

This guide will cover Docker health checks. First, we’ll talk about what health checks are and why they’re valuable, then will talk about implementation. I’ll be cover the material in the form of a tutorial, so feel free to grab a shell and follow along.

1 – What is a health check?

Health checks are exactly what they sound like – a way of checking the health of some resource. In the case of Docker, a health check is a command used to determine the health of a running container.

When a health check command is specified, it tells Docker how to test the container to see if it’s working. With no health check specified, Docker has no way of knowing whether or not the services running within your container are actually up or not.

In Docker, health checks can be specified in the Dockerfile as well as in a compose file. I’ll cover both implementations in a later step.

2 – An example using Flask

Let’s see how health checks work by building a simple Flask app.

Before we begin, note that all of this code is available in a Github repository: Howchoo/docker-flask.

Let’s start with the requirements.txt:

Flask==0.12.2

And the Dockerfile:

FROM python:3.6-alpine

COPY . /app

WORKDIR /app

RUN pip install -r requirements.txt

CMD ["python", "app.py"]

And finally, app.py:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello world'


if __name__ == '__main__':
    app.run(host='0.0.0.0')

Now let’s build the container:

docker build -t docker-flask .

This should build pretty quickly. Then we’ll run the container.

docker run --rm --name docker-flask -p 5000:5000 docker-flask

Now test by opening up your browser to localhost:5000. You should see “Hello world”.

3 – Why do we need a health check?

Well, to be honest, in our case it may not make that much of a difference because we’re just running the development server, but in a production environment we’d probably be running a few different processes. We’d probably serve our Flask app using nginx and uwsgi, possibly using supervisor.

In this case, we could theoretically lose our Flask app, but the container would still be running. So the normal state of the container would be “running” even though we are no longer serving traffic.

If we’re running this service in a swarm, the swarm will still think everything is OK because the container is running. But actually, we’d prefer the swarm to know that things aren’t healthy and restart the container so we can serve traffic again.

4 – Add a health check to the Dockerfile

Since the goal of our container is to serve traffic on port 5000, our health check should make sure that is happening.

A health check is configured in the Dockerfile using the HEALTHCHECK instruction. There are two ways to use the HEALTHCHECK instruction:

HEALTHCHECK [OPTIONS] CMD command

or if you want to disable a health check from a parent image:

HEALTHCHECK NONE

So we’re obviously going to use the first. So let’s add the HEALTHCHECK instruction, and we’ll use curl to ensure that our app is serving traffic on port 5000.

So add this line to the Dockerfile right before the last line (CMD).

HEALTHCHECK CMD curl --fail http://localhost:5000/ || exit 1

In this case, we are using the default options, which are interval 30s, timeout 30s, start-period 0s, and retries 3. Read the health check instruction reference for more information on the options.

5 – See the health status

Let’s rebuild and run our container.

docker build -t docker-flask .
docker run --rm --name docker-flask -p 5000:5000 docker-flask

Now let’s take a look at the health status. Notice we have the –name option to the above command so we can easily inspect the container.

docker inspect --format='{{json .State.Health}}' docker-flask 

If you run this immediately after the container starts, you’ll see Status is starting.

{"Status":"starting","FailingStreak":0,"Log":[]}

And after the health check runs (after the default interval of 30s):

{"Status":"healthy","FailingStreak":0,"Log":[{"Start":"2017-07-21T06:10:51.809087707Z","End":"2017-07-21T06:10:51.868940223Z","ExitCode":0,"Output":"Hello world"}]}

We have a little more information here. We see the Status is healthy as well as some details about the health check.

We can also see the health status by running docker ps.

docker ps

You’ll see the following:

CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS                   PORTS                    NAMES
9f89662fc56a        howchoo/docker-flask   "python app.py"          2 minutes ago       Up 2 minutes (healthy)   0.0.0.0:5555->5000/tcp   docker-flask

Notice under STATUS, the status is Up with (healthy) next to it. The health status appears only when a health check is configured.

6 – Configure the health check using a compose file

We can also configure the health check using a compose file. Let’s make a file called docker-compose.yml.

version: '3.1'

services:
  web:
    image: docker-flask
    ports:
      - '5000:5000'

And we deploy our stack to a swarm using:

docker stack deploy --compose-file docker-compose.yml flask

Now, the health check was specified in the Dockerfile, but we can also specify (or override) the health check settings in our compose file.

version: '3.1'

services:
  web:
    image: docker-flask
    ports:
      - '5000:5000'
    healthcheck:
      test: curl --fail -s http://localhost:5000/ || exit 1
      interval: 1m30s
      timeout: 10s
      retries: 3

7 – In conclusion

Hopefully you have a better understanding of Docker health checks and how to implement them. If you have any questions or would like to suggest improvements to this guide, please comment below.

NEXT UP

Secure Your Sensitive Data with Kubernetes Secrets

Learn how to create and use Kubernetes secrets.
howchoo   (467)
November 26, 2023

Kubernetes secrets are objects that store and manage sensitive data inside your Kubernetes cluster. One mistake developers often make is storing sensitive information like database passwords, API credentials, etc in a settings file in their codebase. This is very bad practice (hopefully for obvious reasons). Most developers know this, but still choose the option because it’s easy.

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Raspberry Pi

How to Control a DC Motor (Or Motors) Using Your Raspberry Pi

howchoo   (467)
September 15, 2023
15 minutes

Share

You’ll Need 3

What you’ll need
Interests
Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.
Posted in these interests:
python • 18 guides
pi • 92 guides

Controlling DC motors from your Raspberry Pi is quite easy! Whether you want to control a single motor or build a Raspberry Pi NERF tank, the principles are the same — but the hardware needed will vary. You can use any Raspberry Pi for this project (Zero, Zero W, 3, 4, etc.)

This guide will cover a basic example — using the TB6612 to drive a single DC motor for use in my Amazon Echo Furby project. This little chip is offered by Adafruit (and others), but I prefer the Adafruit version as it includes diodes to protect both the Pi and motors. Some chips require you solder your own diode circuit (such as the Sparkfun TB6612FNG), and I’d rather avoid this.

This little chip can drive either two DC motors or one stepper motor. Also, the chip is only $5. Not bad.

Hardware

There are a few components that make Raspberry Pi DC motor control work:

  1. Motor driver/controller (TB6612, in this example).
  2. Motor power supply (e.g. battery).
  3. Your Pi itself.

GPIO and PWM

Basically, your Pi’s GPIO (general purpose input/output) pins connect to the driver board, supplying both board power and data signals that will tell the motor when to run using PWM (pulse-width modulation). We’ll then write a simple Python script that will toggle the GPIO pins HIGH or LOW, thus activating the motor!

Power

A separate power source supplies power to the driver board which gets passed directly to the motors. Thus, there are two power sources in total:

  1. Power for the motors (provided by an external battery/power supply), and
  2. Power for the motor driver (provided by the Pi’s GPIO pins).

Anyways, this is a very simple project that’s a great foray into both Raspberry Pi GPIO and PWM. Let’s get started!

1 – Choosing a driver board and motor(s)

For my project, I only need to run one motor. However, if you wanted to build a Raspberry Pi robot or rover of some kind, you might need to drive many motors. In this case, you’ll want to use a driver board that supports more motors (and a larger power supply to drive them as well). For this guide, we’re going to work with the Adafruit TB6612 (same as TB6612FNG).

This board can drive two DC motors or a single stepper motor — with a maximum current of 1.2A. When choosing your motor, be sure you don’t exceed this maximum amperage.

2 – Building the circuit

I recommend using a breadboard to prototype and test your connections prior to soldering.

The attached wiring diagram shows the connections you need to make to build your TB6612 driver board circuit. I also created a Fritzing diagram if you’re into that sort of thing.

Remember (per the diagram), the power provided to the motor is different than the power provided to the motor driver’s logic circuit!

STBY = Pin 13 (GPIO #21)

Motor A:
PWMA = Pin 7 (GPIO #4)
AIN2 = Pin 11 (GPIO #17)
AIN1 = Pin 12 (GPIO #18)

Motor B:
BIN1 = Pin 15 (GPIO #22)
BIN2 = Pin 16 (GPIO #23)
PWMB = Pin 18 (GPIO #24)

 If you’re only using one motor, simply don’t make the BIN1, BIN2, or PWMB connections.

3 – Writing the code

The following code can be used to drive your DC motors. This sample code will drive the motors clockwise for 5 seconds and then counterclockwise for 5 seconds.

Log into your Raspberry Pi and create a new file:

How to Connect to a Raspberry Pi Remotely via SSH
The preferred (and most common) method of connecting to your Pi to run commands.

sudo nano ~/motor/motor.py

Paste the following code, save, and exit:

Drive a single motor:

#!/usr/bin/env python

# Import required modules
import time
import RPi.GPIO as GPIO

# Declare the GPIO settings
GPIO.setmode(GPIO.BOARD)

# set up GPIO pins
GPIO.setup(7, GPIO.OUT) # Connected to PWMA
GPIO.setup(11, GPIO.OUT) # Connected to AIN2
GPIO.setup(12, GPIO.OUT) # Connected to AIN1
GPIO.setup(13, GPIO.OUT) # Connected to STBY

# Drive the motor clockwise
GPIO.output(12, GPIO.HIGH) # Set AIN1
GPIO.output(11, GPIO.LOW) # Set AIN2

# Set the motor speed
GPIO.output(7, GPIO.HIGH) # Set PWMA

# Disable STBY (standby)
GPIO.output(13, GPIO.HIGH)

# Wait 5 seconds
time.sleep(5)

# Drive the motor counterclockwise
GPIO.output(12, GPIO.LOW) # Set AIN1
GPIO.output(11, GPIO.HIGH) # Set AIN2

# Set the motor speed
GPIO.output(7, GPIO.HIGH) # Set PWMA

# Disable STBY (standby)
GPIO.output(13, GPIO.HIGH)

# Wait 5 seconds
time.sleep(5)

# Reset all the GPIO pins by setting them to LOW
GPIO.output(12, GPIO.LOW) # Set AIN1
GPIO.output(11, GPIO.LOW) # Set AIN2
GPIO.output(7, GPIO.LOW) # Set PWMA
GPIO.output(13, GPIO.LOW) # Set STBY

Drive two motors:

#!/usr/bin/env python

# Import required modules
import time
import RPi.GPIO as GPIO

# Declare the GPIO settings
GPIO.setmode(GPIO.BOARD)

# set up GPIO pins
GPIO.setup(7, GPIO.OUT) # Connected to PWMA
GPIO.setup(11, GPIO.OUT) # Connected to AIN2
GPIO.setup(12, GPIO.OUT) # Connected to AIN1
GPIO.setup(13, GPIO.OUT) # Connected to STBY
GPIO.setup(15, GPIO.OUT) # Connected to BIN1
GPIO.setup(16, GPIO.OUT) # Connected to BIN2
GPIO.setup(18, GPIO.OUT) # Connected to PWMB

# Drive the motor clockwise
# Motor A:
GPIO.output(12, GPIO.HIGH) # Set AIN1
GPIO.output(11, GPIO.LOW) # Set AIN2
# Motor B:
GPIO.output(15, GPIO.HIGH) # Set BIN1
GPIO.output(16, GPIO.LOW) # Set BIN2

# Set the motor speed
# Motor A:
GPIO.output(7, GPIO.HIGH) # Set PWMA
# Motor B:
GPIO.output(18, GPIO.HIGH) # Set PWMB

# Disable STBY (standby)
GPIO.output(13, GPIO.HIGH)

# Wait 5 seconds
time.sleep(5)

# Drive the motor counterclockwise
# Motor A:
GPIO.output(12, GPIO.LOW) # Set AIN1
GPIO.output(11, GPIO.HIGH) # Set AIN2
# Motor B:
GPIO.output(15, GPIO.LOW) # Set BIN1
GPIO.output(16, GPIO.HIGH) # Set BIN2

# Set the motor speed
# Motor A:
GPIO.output(7, GPIO.HIGH) # Set PWMA
# Motor B:
GPIO.output(18, GPIO.HIGH) # Set PWMB

# Disable STBY (standby)
GPIO.output(13, GPIO.HIGH)

# Wait 5 seconds
time.sleep(5)

# Reset all the GPIO pins by setting them to LOW
GPIO.output(12, GPIO.LOW) # Set AIN1
GPIO.output(11, GPIO.LOW) # Set AIN2
GPIO.output(7, GPIO.LOW) # Set PWMA
GPIO.output(13, GPIO.LOW) # Set STBY
GPIO.output(15, GPIO.LOW) # Set BIN1
GPIO.output(16, GPIO.LOW) # Set BIN2
GPIO.output(18, GPIO.LOW) # Set PWMB

Special thanks to Alex Wilkinson for providing the basis for this sample code!

Obscure note: Certain Pi HATs might make use of some of the pins above—so if you have some sort of HAT/board connected to your Pi’s GPIO header, you may need to adjust the pins selected above to output things properly.

For example, I’m using a Pimoroni Speaker pHAT on my motorized Pi; I checked the Speaker pHAT pinout and discovered that GPIO pin 12 is in use by the HAT, so I’m using an alternate pin (16) instead.

4 – Execute the code

To drive your motor(s), run the Python script:

sudo python ~/motor/motor.py
NEXT UP

How to Run a Minecraft Server on the Raspberry Pi

A whole world trapped inside your Pi.
howchoo   (467)
December 7, 2023

There are several ways to go about running a Minecraft server on the Raspberry Pi. In this guide, I’ll cover how to install Nukkit—a cross-platform Minecraft server that’s super easy to set up on the Raspberry Pi. This server should work with PCs, consoles, and tablets running Minecraft 1.14. I’ll be using a Raspberry Pi

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests MacOS

How to Set the Default View Options for All Finder Windows in macOS

howchoo
howchoo   (467)
September 15, 2023
7 minutes

Share

Interests
Posted in these interests:
finder • 2 guides
osx • 6 guides
macos • 20 guides

If you’re using a Mac and you’ve found yourself in a place where every Finder window is opening up with a different set of view options (that is icons, list, columns or Cover Flow), there’s a way to quickly remedy this.

If your workspace is cluttered, it’s worth noting it’s also possible to close all Finder windows at once.

1 – First, understand how Mac saves your Finder settings

You may have seen a file in some of your folders called .DS_Store. The dot means this is a hidden file so it won’t usually show up in Finder. .DS_Store stands for Desktop Services Store and is used to store folder specific settings. If many of your folders have different view options, it’s because their unique .DS_Store files have different settings.

2 – Set the default view options

First, we want to set the default view options for all new Finder windows. To do so, open Finder and click on the view setting that you want to use. The settings are four icons and the top of your Finder window.

If you don’t see the Finder toolbar type:

cmd + option + t

After selecting the option you want, type:

cmd + j

to open the view options window.

Make sure you check the top two checkboxes that say Always open in list view and Browse in list view. Keep in mind it will reflect whichever view you’ve selected.

Now click the button at the bottom that says “Use as Defaults”.

🛈 The “Use as Defaults” button won’t appear for the “Column” view type, only the other 3 view types. This is intentional as your view settings for Column View will save without clicking the button.

3 – Delete all .DS_Store files on your computer

Chances are you’ve opened some Finder windows in the past. Individual folder options will override this default setting that we just set.

In order reset your folder settings across the entire machine we have to delete all .DS_Store files. This will ensure that all folders start fresh. Open up the Terminal application (Applications/Utilities/Terminal), and type:

sudo find / -name .DS_Store -delete; killall Finder

You will then be prompted for your password. You won’t see your password as you type, so type carefully. This may take a minute or two because it’s going to search your entire computer for .DS_Store files.

🛈 In the future, whenever you switch views, it will automatically save in the new .DS_Store file. This will override the default settings.

4 – The slow, careful way

If you’re worried about losing precious settings, you can simply change the view options for each folder individually. So whenever you navigate to a folder in Finder that doesn’t have your preferred layout, simply change it. This won’t be an instant fix, but it will ensure that you don’t lose any of your existing settings.

NEXT UP

How to Enable the “Popping” Sound When Adjusting the Volume on Your Mac

howchoo
howchoo   (467)
December 13, 2023

Starting with MacOS Sierra and High Sierra, your Mac will no longer play a “pop” sound when you adjust your volume. If you prefer to have this sound when you adjust volume up and down (as I do), this guide will teach you how to reenable it. 1 – Open Sound System Preferences Navigate to System

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Minecraft

How To Install Shaders in Minecraft

Because you deserve nice graphics.
howchoo   (467)
September 15, 2023
6 minutes

Share

Interests
Posted in these interests:
READY PLAYER 1
gaming • 85 guides
Minecraft is an epic sandbox video game developed by Swedish game developer Mojang Studios.
minecraft • 66 guides

Shaders, also known as shader packs, are a way to bring your Minecraft gameplay to a new level of beautiful. Minecraft Shaders improve the game’s visual elements, such as color enhancement, improved lighting, and generally make the game look more realistic. Depending on the shader, players can customize their world to their preference. So if you want a purple sky and realistic clouds, shader packs are the way to make it happen.

Before you dive into our guide on how to install shaders in Minecraft, make sure you already have OptiFine installed. We have a helpful guide on how to do that here! Without OptiFine, the shaders won’t work, so make sure to do that and return here after!

1 – Find your file path

Before moving into the actual installation of shaders, it’s important to know where your Minecraft game is installed. To do so, follow these steps:

  1. Open the Minecraft Launcher.
  2. Make sure the launch option is the game version you plan on using.
  3. Go to the Installations tab at the top of the window.
  1. Hover your mouse over the game version you want to find and click the folder icon to the right of the Play button. See the image above for help.

2 – Create a shaders folder

Unfortunately, Minecraft doesn’t automatically create a folder to place shaders into. Inside the Minecraft folder you found in the last step, create a new folder called shaderpacks. Make sure to spell it exactly or else the game won’t recognize where you’ve placed your shaders.

3 – Choose a shader pack

There are plenty of websites out there for finding shaders, but some are safer than most. We recommend CurseForge or Shaders Mods. Alternatively, you can download directly from a developer’s website as well!

Make sure it’s compatible with your Minecraft game version and then move on to the next step!

4 – Install shaders

Download the correct game version of the shader you’ve chosen and place it within the shaders folder you made in step 2. Make sure you don’t unzip the downloaded file!

5 – Activate shaders

Now it’s time to run Minecraft and activate your shaders! Once the game has launched, follow these steps:

  1. Click Options then Video Settings.
  2. Click Shaders… as shown in the image above.
  1. In the Shaders menu, choose the shader you want to activate. A loading screen will appear and return you back to the Shaders menu when its finished rendering.

From this menu you can either click the Shader Options button on the bottom right to customize the shader pack or click Done and return to the main menu!

NEXT UP

Top 10 Enchantments in Minecraft

howchoo   (467)
March 25, 2024

The longer you play Minecraft, the more you realize that early-game tools just won’t cut it. Exploring the enchantment feature of Minecraft can be exciting, but also intimidating. Rather than worry about researching enchantments, below are the best enchantments in Minecraft! To learn how to enchant items, check out this guide! In this guide, you’ll see

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Subaru Crosstrek

How to Replace the Subaru XV Crosstrek Cabin Air Filter (2013+)

Change your Crosstrek’s cabin air filter in 5 minutes for less than $15.
howchoo   (467)
September 15, 2023
8 minutes

Share

You’ll Need 1

What you’ll need
Interests
Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.
Posted in these interests:
autos • 4 guides
subaru • 3 guides
crosstrek • 3 guides

Why pay the dealership hundreds of dollars to replace your cabin air filter when you can do it in 5 minutes for less than $15? This guide requires no tools. Just pick up a compatible cabin air filter such as this one and get started.

How often should you replace your Crosstrek cabin air filter?

Your Subaru Crosstrek’s cabin air filter should be replaced every 12 months, or 12,000 miles, whichever comes first. If you live in a particularly dusty area or one with a lot of tree debris, it would be a good idea to replace it sooner.

Subaru Crosstrek cabin air filter location

The Subaru a Crosstrek air filter is located behind the glove compartment and requires no tools to change.

Why replace your Crosstrek cabin air filter?

Your cabin air filter should be replaced regularly not only to ensure cleaner air in your car, but to reduce strain on your air conditioning components. A clogged in-cabin air filter increases strain on your A/C blower motor and even your compressor.

Also, you’ll be surprised how fresh your car will smell!

1 – Empty your glovebox

Temporarily remove all the papers and other junk that’s collected in your glove compartment over the years.

🛈 Don’t worry, you can shove it all back in there when you’re done.

2 – Remove the glovebox door

The glove box is held in place using two small stoppers: one on each side.

Gently push both sides inward until the stoppers clear the sides of the glove compartment opening.

3 – Unclip the glovebox retaining arm

Gently push the glovebox retaining arm out of the way to unclip it.

Then, slowly and carefully lower the glovebox door towards the floor. Or, in my case, the glovebox door will just fall off immediately.

4 – Locate the cabin air filter

This photo shows the location of the Crosstrek’s cabin air filter. It might be in the top left in certain model years.

The cabin air filter on the Subaru XV Crosstrek is located behind the glove compartment in the either the upper left or directly center, depending on model year. See the attached image for reference.

5 – Remove the old cabin air filter

To remove the Crosstrek’s cabin air filter, pinch the two fasteners on either side of it and pull it straight out.

🛈 If you have a vacuum handy, it’s a good idea to stick the nozzle in there and suck out any particles that might be in there.

6 – Behold how disgusting the old filter is

If you live under a thousand oak trees, as I do, your filter will be extra gross.

Bask in how truly awful the old filter is and pat yourself on the back for choosing to replace it.

7 – Replace the air filter

This is the filter I used for my 2014 XV Crosstrek and the listing includes a model year checker.

Slide the new cabin air filter into place until both of the side fasteners click.

🛈 The filter has an arrow indicating which side goes up.

8 – Reassemble everything

Carefully push the glovebox retaining arm back into place and close the glovebox.

When you close the glovebox, the two side stoppers will automatically re-seat themselves.

Finally, put all your stuff back into your glove compartment. While you’re at it, maybe toss the trillion papers you’ve accumulated or relocate them into your home.

You’re done!

Turn on your AC and smell the fresh air. You’ll be able to notice a difference immediately!

Next: Disable that awful beep

While you’re still in the car, disable the Crosstrek unlock sound in about 30 seconds of work (your ears will thank you). 🙂

NEXT UP

Build Your Own Raspberry Pi Car Computer, or “Carputer”, with AutoPi

Bring your car into the future!
howchoo   (467)
September 29, 2023

Have you ever wanted to add an entertainment system to your car, only to find that most units are expensive, come with a lackluster feature set, and feature a terrible interface? Well, now you can build your own Raspberry Pi-powered car computer with AutoPi! Monitor your car’s vitals, watch movies, play retro games wiith RetroPie, use open

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests JavaScript

How to Turn an Object into Query String Parameters in JavaScript

howchoo
howchoo   (467)
September 14, 2023
3 minutes

Share

Interests
Posted in these interests:
javascript • 4 guides
webdev • 10 guides

As a JavaScript developer, you’ll often need to construct URLs and query string parameters. One sensible way to construct query string parameters is to use a one layer object with key value pairs.

In this guide we’ll cover various ways to turn an object like this:

var params = {
    a: 1,
    b: 2,
    c: 3
};

into a query string like this:

"a=1&b=2&c=3"

1 – Using map and join

If you’re using a modern browser (or node) you can use map to create an array of strings like a=1, then use join to join them together with &.

ES6

var queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');

ES5

var queryString = Object.keys(params).map(function(key) {
    return key + '=' + params[key]
}).join('&');

2 – Using jQuery

If you’re the sort of person who uses jQuery, you’ve got a solution readily available:

var queryString = $.param(params);

3 – Using the querystring module in node

If you’re using node, you can use the querystring module:

const querystring = require('querystring');

let queryString = querystring.stringify(params);

4 – Parameter encoding

If you know you’re keys and values need to be encoded, you should use encodeURIComponent like this:

var queryString = Object.keys(params).map((key) => {
    return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
}).join('&');

It’s also possible to query by timestamp in MySQL.

NEXT UP

Make YouTube Video Embeds Responsive Using Pure HTML and CSS

howchoo   (467)
September 22, 2023

Surprisingly, normal YouTube embeds are not automatically sized to the browser window as it is resized. Luckily, you can make YouTube videos responsive and mobile-friendly with some simple HTML and CSS. 1 – The HTML Wrap your embed code in a unique video wrapper (the class name is arbitrary). I chose to use embed-youtube as the selector.

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Django

Combine Two Querysets in Django (With Different Models)

howchoo
howchoo   (467)
September 14, 2023
14 minutes

Share

Interests
Posted in these interests:
django • 3 guides
python • 18 guides

Today, I stumbled upon a use case where I needed to have a querysets that had objects from different models. Django has a neat “contenttypes framework” which is a good way to achieve this. So here are my notes on what I learned today, and I hope it will help someone in the future. NOTE: If you can design your models from scratch this is not the best approach to follow. Read my note under step 5.

1 – The Models

Let us consider the following models:

class Bmw(models.Model):
    series = models.CharField(max_length=50)
    created = models.DateTimeField()
    class Meta:
        ordering = ['-created']
    def __str__(self):
         return "{0} - {1}".format(self.series, self.created.date())
class Tesla(models.Model):
    series = models.CharField(max_length=50)
    created = models.DateTimeField()
    class Meta:
        ordering = ['-created']
    def __str__(self):
        return "{0} - {1}".format(self.series, self.created.date())

🛈 We can obviously have a parent class in this case with common properties, but we are keeping it simple for purposes of this tutorial.

2 – The Queries

We can get list of Bmw’s and Teslas separately like so:

>>> Bmw.objects.filter()
[, ]
>>> Tesla.objects.filter()
[, ]

But what if we want the two querysets combined, say we want to display all cars in our dealership page by creation date. So we want something like:

[, , , ]

How do we do that? Here are two viable approaches.

3 – Using Chain from itertools

Using itertools chain is one approach.

from itertools import chain
def get_all_cars():
    bmws = Bmw.objects.filter()
    teslas = Tesla.objects.filter()
    cars_list = sorted(
        chain(bmws, teslas),
        key=lambda car: car.created, reverse=True)
    return cars_list

Here we get the queryset for Bmws and queryset of Teslas, and pass them to the chain function which combines these two iterables and makes a new iterator. We then pass this list to the sort function and specify that we want to sort it by the created date. Finally we say that we want the order to be reversed. Here is the result:

[, , , ]

This is a good approach if the queryset is small. However if we are dealing with larger querysets and need to involve pagination, every time we need to query the entire database and sort by the created date. Even if we slice the list, then we have to manually keep track of our slice index and created date for sorting, and the whole approach could get messy.

 🛈 Notice the object types here are of type Bmw and Tesla.

4 – The contenttypes Framework

Django’s contenttypes framework is really a good option for this use case. From the docs: At the heart of the contenttypes application is the ContentType model, which lives at django.contrib.contenttypes.models.ContentType. Instances of ContentType represent and store information about the models installed in your project, and new instances of ContentType are automatically created whenever new models are installed. I would urge you to read up more on it.

5 – Content Types in our models

From the docs:

Adding a foreign key from one of your own models to ContentType allows your model to effectively tie itself to another model class.

So we add a new model to our models called car which uses the Generic Relations.

class Car(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    created = models.DateTimeField()
    class Meta:
        ordering = ['-created']
    def __str__(self):
        return "{0} - {1}".format(self.content_object.series,
                                  self.created.date())

We then update our models and define a post save handler.

def create_car(sender, instance, created, **kwargs):
    """
    Post save handler to create/update car instances when
    Bmw or Tesla is created/updated
    """
    content_type = ContentType.objects.get_for_model(instance)
    try:
        car= Car.objects.get(content_type=content_type,
                             object_id=instance.id)
    except Car.DoesNotExist:
        car = Car(content_type=content_type, object_id=instance.id)
    car.created = instance.created
    car.series = instance.series
    car.save()

And we add the post save handler to our Tesla model.

class Tesla(models.Model):
    series = models.CharField(max_length=50)
    created = models.DateTimeField()
    class Meta:
        ordering = ['-created']
    def __str__(self):
        return "{0} - {1}".format(self.series, self.created.date())
post_save.connect(create_car, sender=Tesla)

(and similarly added for Bmw model not show for brevity) So now every time an instance of Tesla or Bmw is created or updated, the corresponding Car model instance gets updated.

🛈 If you can set up your models from scratch, you can think about a better design where you store the type of a Car like ‘Tesla’ , ‘BMW’ in a separate table, and have a Foreign Key to your Cars table as a better alternative. The ‘contenttypes framework’ could come in handy, when you don’t have the liberty to change existing models a.k.a production.

6 – Query using contenttypes framework

Here is an updated query using the contentypes framework that we just set up. Notice how we have both Bmw and Tesla objects returned as Car instances.

>>> Car.objects.filter()
[, , , ]

Here we have returned car objects, so here is how we get to the actual car type a Car instance holds.

>>> car = Car.objects.first()
>>> car.content_object

>>> car.content_object.series
u'Tesla Series 2'

7 – Closing Notes

Although this approach has an overhead of an extra table, for larger query sets I feel this is a cleaner approach.

Let me know what you think or if you have any questions in the comments below.

NEXT UP

Class Vs. Instance Variables in Python 3

howchoo
howchoo   (467)
November 22, 2023

When learning object oriented programming in Python, there can be a few gotchas when it comes to distinguishing between class and instance variables. In this guide I’ll explain the difference between class and instance variables and provide examples demonstrating various use cases. 1 – Class vs. instance variables First, a quick review if you’re new

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests JavaScript

How to Pretty Print JSON in Chrome Developer Console

howchoo
howchoo   (467)
September 14, 2023
2 minutes

Share

Interests
Posted in these interests:
code • 11 guides
javascript • 4 guides
webdev • 10 guides

This short guide will show you how to pretty print a JSON object in the Chrome Developer Tools console.

1 – Output your object as a string

Wrap your object in JSON.stringify and log it to the console:

const currentlyDrinking = {
    beer: 'Yeungling',
    container: 'bottle',
    empty: true
};

console.log(JSON.stringify(currentlyDrinking));

This will result in the following minified object:

{"beer":"Yeungling","container":"bottle","empty":true}

Not exactly pretty yet, so we’ll need to format it. This is especially important for larger objects.

2 – Format the pretty-printed output

To format our object, we’ll need to specify the number of spaces we’d like:

const currentlyDrinking = {
    beer: 'Yeungling',
    container: 'bottle',
    empty: true
};

console.log(JSON.stringify(currentlyDrinking, undefined, 4)); // use 4-space tabs to format and indent the code

This results in:

{
    "beer": "Yeungling",
    "container": "bottle",
    "empty": true
}

Much better!

3 – More formatting options

For more Chrome Developer console object pretty-printing options, check out the JSON.stringify() MDN docs.

NEXT UP

Secure Your Sensitive Data with Kubernetes Secrets

Learn how to create and use Kubernetes secrets.
howchoo   (467)
November 26, 2023

Kubernetes secrets are objects that store and manage sensitive data inside your Kubernetes cluster. One mistake developers often make is storing sensitive information like database passwords, API credentials, etc in a settings file in their codebase. This is very bad practice (hopefully for obvious reasons). Most developers know this, but still choose the option because it’s easy.

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests ASUS

How to Change Your ASUS Wi-Fi Password

howchoo
howchoo (467)
September 14, 2023
3 minutes

Share

You’ll Need 1
What you’ll need
Interests
Series
Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.
Posted in these interests:
asus • 3 guides
internet • 36 guides
router • 32 guides
Changing your WiFi password is a simple way to add more security to your network—after all, it’s much harder to hack a password that keeps changing! ASUS makes it easy for users to create a new WiFi password. All you need is a computer connected to the ASUS network.

1 – Log into the ASUS router

To set a new WiFi password, you’ll need to log in to your ASUS router. This will give you access to a web-based dashboard with Wireless settings. You’ll need to have or find your network security key you intend to change if you don’t already have it.

2 – Access Wireless settings

To open the wireless settings, navigate to the following location:
  • Click Wireless on the left-hand navigation pane
  • Look under the General tab
  • Scroll until you see a field labeled Pre-shared key

3 – Set a new WiFi password

To set a new WiFi password, put it in the Pre-shared key field. Try to make a password that’s random and secure or use a password manager like 1Password.

4 – Save your changes

Save the changes and test your new WiFi password with a wireless device.
NEXT UP

How to Change Your Frontier WiFi Password

howchoo
howchoo (467)
November 25, 2023
There are a few reasons you might want to update or reset your WiFi password: making your network more secure, and making your password easier to remember and type. Improved network security You can add an extra layer of security to your network by changing the WiFi password. As long as your new password is
Continue Reading

howchoo

 467 guides
Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.