How to free up space in Mac

In this article, we will show you how you can free up some space in your Mac. If you are running low on space, this is for you.

My Mac was running on 5-6 GB and it keeps getting lower as I work more. So I did the following actions and now my Mac has 37 GB of free space.

1. Goto “home”.

2. Enable hidden files by pressing Command + shift + dot

3. If you do not do iOS development, then it is safe to remove the “.cocoapods” folder.

4. After that, you need to check each folder and see if there is any cache folder in it. You can safely remove all cache folders inside each folder.

4. Then you need to go to “Library”.

5. Remove the “Caches” folder.

6. When you uninstall an app, its files remain there in the “Library” folder. So check all the apps/software that you have uninstalled or no longer use, and delete their folders too.

If you follow the above steps, it will free up a lot of space in your Mac.

Check if time is passed – Python

In this tutorial, you will learn how to check if the time is passed in Python.

First, we will get the future time in UTC. In order to get this, first we will get the current time in UTC.

Then we will add 24 hours in it.

After that, we will get time_struct object from it. This will be used to get the Unix timestamp.

Then we will the Unix timestamp using the time_struct object.

Same can be done for getting the current time in UTC but without adding 24 hours in it.

delta is the difference between future Unix timestamp and current one.

Then we will convert the seconds into minutes by dividing it to 60 since each minute has 60 seconds.

And again dividing that to 60 since each hour has 60 minutes. This will return the number of hours since the time is passed.

Finally, we will check if the delta is less than or equal to zero. If it is, it means that the time is passed. If not, it means that the time is not passed yet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from datetime import datetime, timezone, timedelta
import time
 
future_time = datetime.now(timezone.utc)        # current datetime in UTC
future_time = future_time + timedelta(hours=24) # current time + 24 hours
future_time = future_time.timetuple()           # instance of time.struct_time
future_time = time.mktime(future_time)          # Unix timestamp
 
current_time = datetime.now(timezone.utc)       # current datetime in UTC
current_time = current_time.timetuple()         # instance of time.struct_time
current_time = time.mktime(current_time)        # Unix timestamp
 
delta = future_time - current_time              # difference between future datetime and current datetime (in seconds)
delta = delta / 60 / 60                         # convert seconds into hours
 
if delta <= 0:                                  # check if the time is passed
    print("Time passed")
else:
    print("Time not passed")

You can check the real-world example of this in the URL shortener app we created in Python.

Convert UTC to local timezone – Python

Here’s how you can get the date and time in UTC and convert it to user’s local timezone in Python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from fastapi import FastAPI
from datetime import datetime, timezone as timezone_module
from dateutil import tz
 
app = FastAPI()
 
utc = datetime.now(timezone_module.utc)
 
# Hardcode zones:
from_zone = tz.gettz("UTC")
to_zone = tz.gettz("Asia/Karachi")
 
# you can get user's local timezone in Javascript using following code:
# Intl.DateTimeFormat().resolvedOptions().timeZone
 
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
 
# Convert time zone
local = utc.astimezone(to_zone)
 
# get in readable format
local = local.strftime("%b %d, %Y %H:%M:%S")
 
print(local)

Comments has been added with each line for explanation. You can check its real-world example in a URL shortener app we created in Python.

How to fix CORS error in FastAPI Python

If you are developing an application and getting CORS error in Python FastAPI, then you can fix it by first importing the CORS middleware from FastAPI module. Then you need to add that middleware in your FastAPI “app” instance. Allow all origins, all credentials, and all methods and headers.

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI
 
from fastapi.middleware.cors import CORSMiddleware
 
app = FastAPI()
 
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

It will fix CORS error in your Python FastAPI. Learn how to create a URL shortener app in Python.

Replace all occurrences in a string – Javascript

To replace all the occurrences in a string in Javascript, we will use the following method.

For example, you have the following string variable.

1
let string = "adnan_tech_com"

And you want to replace all underscores with a white space.

You can use the following code to replace all occurrences of underscores with a whitespace.

1
string = string.split("_").join(" ") // adnan tech com

Explanation

First, you need to split the string by underscore. It will return an array.

1
2
3
let string = "adnan_tech_com"
 
string = string.split("_") // ["adnan", "tech", "com"]

Then we can join the array by whitespace.

1
2
3
4
5
let string = "adnan_tech_com"
 
string = string.split("_")
 
string = string.join(" ") // adnan tech com

Don’t use replace()

You should not use “replace” function because it will replace only the first occurrence in a string.

1
2
3
let string = "adnan_tech_com"
 
string = string.replace("_", " ") // adnan tech_com

Checkout our more tutorials on Javascript.

How to fix CORS error in Socket IO NodeJS

In this short tutorial, I will show you how you can fix CORS error in socket IO in NodeJS.

First, you need to use the socket IO import statement in following way:

1
2
3
4
5
const socketIO = require("socket.io")(http, {
    cors: {
        origin: "*"
    }
})

Then, with your Express app instance, you can set the following headers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Add headers before the routes are defined
app.use(function (req, res, next) {
 
    // Website you wish to allow to connect
    res.setHeader("Access-Control-Allow-Origin", "*")
 
    // Request methods you wish to allow
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")
 
    // Request headers you wish to allow
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,Authorization")
 
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader("Access-Control-Allow-Credentials", true)
 
    // Pass to next layer of middleware
    next()
})

Create middleware for specific route – Python

If you are creating an API in Python, and came across a problem where you have to create a middleware but for only specific route. For example, you are creating a user authentication system and want to create a middleware that checks if the user is logged-in. But you want to use that middleware for only few routes, not for all routes. Then this tutorial is for you.

This can be done by creating subapps in Python. To create a subapp in Python, first we need to create a file where we will save the global variable of our subapp.

Create a file, let’s say config.py, and write the following code in it.

1
2
3
4
5
# config.py
 
from fastapi import FastAPI
 
my_middleware_app = FastAPI()

Now create a file for our middleware, I am naming it my_middleware.py. Following will be the code of this file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from fastapi import Request
from config import my_middleware_app
 
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
 
@my_middleware_app.middleware("http")
async def my_func(request: Request, call_next):
    if "Authorization" in request.headers:
        print(request.headers["Authorization"])
 
        request.state.name = "Adnan"
        response = await call_next(request)
        return response
    else:
        return JSONResponse(content=jsonable_encoder("Authorization header not provided."))

Explanation:

  1. First, it imports the subapp “my_middleware_app” from “config” module.
  2. Then it imports “JSONResponse” and “jsonable_encoder” from “fastapi” modules. They will be required to send the response back to the client.
  3. Then we are creating a middleware using our subapp “my_middleware_app”.
  4. In this, we are checking if the request has “Authorization” header provided.
    • To learn more about authorization in Python, check our tutorial on user authentication.
  5. If not, then we are sending an error.
  6. If provided, then we are attaching a “name” variable with the request and pass it to the route.

Now let me show you, how the route can use this middleware and how route can access the “name” variable.

Following will be the content of our main.py file where the route will be created.

1
2
3
4
5
6
7
8
9
10
11
12
13
# main.py
 
from fastapi import FastAPI, Request
from config import my_middleware_app
import my_middleware
 
app = FastAPI()
 
@my_middleware_app.post("/my-route")
def my_route(request: Request):
    return request.state.name
 
app.mount("/", my_middleware_app)

We first imported the subapp module and the middleware.

Then we created an instance of FastAPI (the main app).

After that, we are creating a post route using our subapp. In this route, we are using the “name” variable we created in our middleware.

To send value from middleware to route, we can use request.state object.

And lastly, we are mounting the subapp to our main app.

Creating a middleware and using it just for specific route in Python is a bit confusing sometimes. So if you face any problem in following this, please do not hesitate to get in touch with me.

Create global variable between modules – Python

In this tutorial, we will show you how you can create global variable and access them in different modules in Python.

First, you need to create a file, let’s say “config.py“. And write all your global variables in it.

1
2
3
# config.py
 
my_name = "Adnan"

Here, I have created a global variable my_name. In order to access it in any other module, simply import it. Then you can use them as normal variables.

1
2
3
4
5
6
7
# any_other_module.py
 
# method 1
 
from config import my_name
 
print(my_name)

There is another method to import the module.

1
2
3
4
5
6
7
# any_other_module.py
 
# method 2
 
import config
 
print(config.my_name)

That is how you can create global variable and use it in multiple modules in Python. Kindly let me know if you face any problem in following this.

Get age from date of birth – Javascript

Suppose you are given a date of birth of any user and you have to get his age from it. You can do it in Javascript using the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const date = new Date("1993-07-27")
const current_date = new Date()
 
let age = current_date.getTime() - date.getTime()
// 948161820692
 
age = new Date(age)
// 2000-01-18T02:17:18.105Z
 
age = age.getFullYear()
// 2000
 
age = age - 1970
// 30