Normal view

There are new articles available, click to refresh the page.
Yesterday — 1 June 2025python

Git Reset – A tool to correct your (commited) mistakes.

1 June 2025 at 05:43

Terminologies

  1. Work Tree: Your working tree are the files that you are currently working on. Your local folder.
  2. Git Index/Staging Area: The git “index” is where you place files you want commit to the git repository. The index is also known as cache, directory cache, current directory cache, staging area, staged files. Before you “commit” (checking) files to the git repository, you need to first place the files in the git “index”.

The index is not the working directory, you can type a command such as git status, and git will tell you what files in your working directory have been added to the git index (for example, by using the git add filename command).

In simple words, git reset is to correct your mistakes. Consider a scenario, where you have mistakenly did some wrong code and commited it too. Everything started to fall apart. Now you want to go back to the previous stable state (or previous commit). This is the scenario, where git reset helps you. In this blog post you will understand the usage of git reset in 3 different ways.

Visualization of Working Folder, Staging, Local Repository

Git Reset

In general, git reset’s function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. Git reset helps you in two broad categories.

  1. To remove changes from staging area.
  2. To undo commits at repository level.

Scenario #1 : To remove changes from staging area

Workground setup

  1. Create a new folder.
  2. Initialize git in the folder (git init)
  3. Create a text file (eg: sample.txt)
  4. Add some content inside it.
  5. Add the file to the staging area. git add sample.txt

Checking the stage area

Now the file is been added to the staging area (but not commited). But now you realize that you have a wrong content inside it. So inorder to remove it from the staging area, you just need to execute git reset <filename>.

Now you can see that the file is been moved from the staging area to working directory. and the contents inside the file is preserved.

Some of the possible scenarios,

  1. If there are many files in the staged area, then you can simply use git reset.
  2. There is also another command to unstage files, git restore. git restore --staged .

Scenario #2 – To Undo commits at repository level

Workground setup

  1. Create a new folder.
  2. Initialize git in the folder (git init)
  3. Create a text file (eg: file.txt)
  4. Add some content inside it.
  5. Add the file to the staging area. git add file1.txt
  6. Create a text file (eg: file2.txt)
  7. Add some content inside it.
  8. Add the file to the staging area. git add file2.txt
  9. Create a text file (eg: file3.txt)
  10. Add some content inside it.
  11. Add the file to the staging area. git add file3.txt
image.png

There are 3 modes to reset a commit from the local reposity.

Once any file or folder is committed, we won’t have the concept of resetting the file. It will be resetting the commits only.

All these 3 modes, will move the HEAD to a specified commit, and all the remaining recent commits will be removed. The mode will decide whether these changes are going to remove from staging area and working directory or not.

Mixed Method (Default)

Command: git reset --mixed <commit-id>

Functionality: It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status.

Use this when you realize you made some bad commits, but you want to keep all the work you’ve done so you can fix it up and recommit. In order to commit, you’ll have to add files to the index again (git add …).

Hands On: Our working directory will look like this,

We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --mixed 002aa06

Now we can see the HEAD moved to the commit which we specified. And the file3.txt is removed from the local repository and staging.

But the contents inside the file is preserved in the working directory. We can check using the git status to see the file under Untracked files.

Soft Method

Command: git reset --soft <commit-id>

Functionality: All your files are intact as with –mixed, but all the changes show up as changes to be committed with git status (i.e. checked in in preparation for committing). Use this when you realize you’ve made some bad commits, but the work’s all good all you need to do is recommit it differently.

The index is untouched, so you can commit immediately if you want the resulting commit will have all the same content as where you were before you reset.

Hands On: Our working directory will look like this,

We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --soft f8d7c74

Now we can see the HEAD moved to the commit which we specified. And the file2.txt is removed from the commit, but staging.

The contents in the file are preserved and its already present in the staging. We can check this using the git status to see the file under Added files.

Hard Method

Command: git reset --hard <commit-id>

Functionality: This is the easiest to understand, probably. All of your local changes get clobbered.

One primary use is blowing away your work but not switching commits: git reset --hard means git reset --hard HEAD, i.e. don’t change the branch but get rid of all local changes.

The other is simply moving a branch from one place to another, and keeping index/work tree in sync. This is the one that can really make you lose work, because it modifies your work tree. Be very very sure you want to throw away local work before you run any reset --hard.

Hands On: Our working directory will look like this,

We can add one more commit (so that we will have some commits to test).

so now we have 2 files in commit, and one file in working directory (untracked file – file3.txt). We can try resetting the last commit (so we need to specify the previous commit to point it there),

git reset --hard f8d7c74

Now we can see the HEAD moved to the commit which we specified. Also the file2.txt is been removed from the local repository, staging and the working directory.

It removed the files that were present in the commit. This is the one that can really make you lose work, because it modifies your work tree.

The Strange Notation

When you are searching for the working for git reset, you might noticed people using HEAD^ and HEAD~1. These are just the shorthand or specifying commits, without having to use a hash name like f8d7c74.

It’s fully documented in the “specifying revisions” section of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean different things

  • HEAD~ is short for HEAD~1 and means the commit’s first parent. HEAD~2 means the commit’s first parent’s first parent. Think of HEAD~n as “n commits before HEAD” or “the nth generation ancestor of HEAD”.

  • HEAD^ (or HEAD^1) also means the commit’s first parent. HEAD^2 means the commit’s second parent. Remember, a normal merge commit has two parents – the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).

  • The ^ and ~ operators can be strung together, as in HEAD~3^2, the second parent of the third-generation ancestor of HEAD, HEAD^^2, the second parent of the first parent of HEAD, or even HEAD^^^, which is equivalent to HEAD~3.

In this blog post we understood the working of different ways to reset a commit. I am having one question for you. When we are resetting to a different commit, (i.e) pointing the head to a different commit, what will happen to the removed commits ? Is there any way to go back to it ?

Let’s Build a Bank Account Simulation

26 May 2025 at 14:50

Problem Statement

🧩 Overview

Build a bank system to create and manage user accounts, simulate deposits, withdrawals, interest accrual, and overdraft penalties.

🎯 Goals

  • Support multiple account types with different rules
  • Simulate real-world banking logic like minimum balance and interest
  • Track user actions securely

🏗 Suggested Classes

  • BankAccount: account_number, owner, balance, deposit(), withdraw()
  • SavingsAccount(BankAccount): interest_rate, apply_interest()
  • CheckingAccount(BankAccount): minimum_balance, penalty
  • User: name, password, accounts[]

📦 Features

  • Create new accounts (checking/savings)
  • Deposit money to account
  • Withdraw money (with rules):
    • Checking: maintain minimum balance or pay penalty
    • Savings: limit to 3 withdrawals/month
  • Apply interest monthly for savings
  • Show account summary

🔧 OOP Concepts

  • Inheritance: SavingsAccount and CheckingAccount from BankAccount
  • Encapsulation: Balance, account actions hidden inside methods
  • Polymorphism: Overridden withdraw() method in each subclass

🔌 Optional Extensions

  • Password protection (simple CLI input masking)
  • Transaction history with timestamp
  • Monthly bank statement generation

Let’s Build a Library Management System With OOPS

26 May 2025 at 14:40

Problem Statement

🧩 Overview

Design a command-line-based Library Management System that simulates the basic operations of a library for both users and administrators. It should manage books, user accounts, borrowing/returning of books, and enforce library rules like book limits per member.

🎯 Goals

  • Allow members to search, borrow, and return books.
  • Allow admins to manage the library’s inventory.
  • Track book availability.
  • Prevent double borrowing of a book.

👤 Actors

  • Admin
  • Member

🏗 Suggested Classes

  • Book: ID, title, author, genre, is_available
  • User: username, role, user_id
  • Member(User): borrowed_books (max 3 at a time)
  • Admin(User): can add/remove books
  • Library: manages collections of books and users

📦 Features

  • Admin:
    • Add a book with metadata
    • Remove a book by ID or title
    • List all books
  • Member:
    • Register or login
    • View available books
    • Borrow a book (limit 3)
    • Return a book
  • Library:
    • Handles storage, availability, and user-book mappings

🔧 OOP Concepts

  • Inheritance: Admin and Member inherit from User
  • Encapsulation: Book’s availability status and member’s borrow list
  • Polymorphism: Different view_dashboard() method for Admin vs Member

🔌 Optional Extensions

  • Track borrowing history (borrow date, return date)
  • Due dates and overdue penalties
  • Persistent data storage (JSON or SQLite)

📊 Learn PostgreSQL in Tamil: From Zero to 5★ on HackerRank in Just 10 Days

25 May 2025 at 12:42

 

PostgreSQL is one of the most powerful, stable, and open-source relational database systems trusted by global giants like Apple, Instagram, and Spotify. Whether you’re building a web application, managing enterprise data, or diving into analytics, understanding PostgreSQL is a skill that sets you apart.

But what if you could master it in just 10 days, in Tamil, with hands-on learning and a guaranteed 5★ rating on HackerRank as your goal?

Sounds exciting? Let’s dive in.

🎯 Why This Bootcamp?

This 10-day PostgreSQL Bootcamp in Tamil is designed to take you from absolute beginner to confident practitioner, with a curriculum built around real-world use cases, performance optimization, and daily challenge-driven learning.

Whether you’re a

  • Student trying to get into backend development
  • Developer wanting to upskill and crack interviews
  • Data analyst exploring SQL performance
  • Tech enthusiast curious about databases

…this bootcamp gives you the structured path you need.

🧠 What You’ll Learn

Over 10 days, we’ll cover

  • ✅ PostgreSQL installation & setup
  • ✅ PostgreSQL architecture and internals
  • ✅ Writing efficient SQL queries with proper formatting
  • ✅ Joins, CTEs, subqueries, and advanced querying
  • ✅ Indexing, query plans, and performance tuning
  • ✅ Transactions, isolation levels, and locking mechanisms
  • ✅ Schema design for real-world applications
  • ✅ Debugging techniques, tips, and best practices
  • ✅ Daily HackerRank challenges to track your progress
  • ✅ Solve 40+ HackerRank SQL challenges

🧪 Bootcamp Highlights

  • 🗣 Language of instruction: Tamil
  • 💻 Format: Online, live and interactive
  • 🎥 Daily live sessions with Q&A
  • 📊 Practice-oriented learning using HackerRank
  • 📚 Notes, cheat sheets, and shared resources
  • 🧑‍🤝‍🧑 Access to community support and mentorship
  • 🧠 Learn through real-world datasets and scenarios

Check our previous Postgres session

📅 Details at a Glance

  • Duration: 10 Days
  • Language: Tamil
  • Format: Online, hands-on
  • Book Your Slot: https://topmate.io/parottasalna/1558376
  • Goal: Earn 5★ in PostgreSQL on HackerRank
  • Suitable for: Students, developers, DBAs, and tech enthusiasts

🔥 Why You Shouldn’t Miss This

  • Learn one of the most in-demand database systems in your native language
  • Structured learning path with practical tasks and daily targets
  • Build confidence to work on real projects and solve SQL challenges
  • Lifetime value from one affordable investment.

Will meet you in session !!!

Redis Strings – The Building Blocks of Key Value Storage

23 May 2025 at 00:12

Redis is famously known as an in-memory data structure store, often used as a database, cache, and message broker. The simplest and most fundamental data type in Redis is the string. This blog walks through everything you need to know about Redis strings with practical examples.

What Are Redis Strings?

In Redis, a string is a binary-safe sequence of bytes. That means it can contain any kind of data text, integers, or even serialized objects.

  • Maximum size: 512 MB
  • Default behavior: key-value pair storage

Common String Commands

Let’s explore key-value operations you can perform on Redis strings using the redis-cli.

1. SET – Assign a Value to a Key

SET user:1:name "Alice"

This sets the key user:1:name to the value "Alice".

2. GET – Retrieve a Value by Key

GET user:1:name
# Output: "Alice"

3. EXISTS – Check if a Key Exists

EXISTS user:1:name
# Output: 1 (true)

4. DEL – Delete a Key

DEL user:1:name

5. SETEX – Set Value with Expiry (TTL)

SETEX session:12345 60 "token_xyz"

This sets session:12345 with value token_xyz that expires in 60 seconds.

6. INCR / DECR – Numeric Operations

SET views:homepage 0
INCR views:homepage
INCR views:homepage
DECR views:homepage
GET views:homepage
# Output: "1"

7. APPEND – Append to Existing String

SET greet "Hello"
APPEND greet ", World!"
GET greet
# Output: "Hello, World!"

8. MSET / MGET – Set or Get Multiple Keys at Once

MSET product:1 "Book" product:2 "Pen"
MGET product:1 product:2
# Output: "Book" "Pen"

Gotchas to Watch Out For

  1. String size limit: 512 MB per key.
  2. Atomic operations: INCR, DECR are atomic – ideal for counters.
  3. Expire keys: Always use TTL for session-like data to avoid memory bloat.
  4. Binary safety: Strings can hold any binary data, including serialized objects.

Use Redis with Python

import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('user:1:name', 'Alice')
print(r.get('user:1:name').decode())

💾 Redis Is Open Source Again – What that means ?

11 May 2025 at 02:32

Imagine you’ve been using a powerful tool for years to help you build apps faster. Yeah its Redis, a super fast database that helps apps remember things temporarily, like logins or shopping cart items. It was free, open, and loved by developers.

But one day, the team behind Redis changed the rules. They said

“You can still use Redis, but if you’re a big cloud company (like Amazon or Google) offering it to others as a service, you need to play by our special rules or pay us.”

This change upset many in the tech world. Why?

Because open-source means freedom you can use it, improve it, and even share it with others. Redis’s new license in 2024 took away some of that freedom. It wasn’t completely closed, but it wasn’t truly open either. It hurts AWS, Microsoft more.

What Happened Next?

Developers and tech companies didn’t like the new rules. So they said,

“Fine, we’ll make our own open version of Redis.”

That’s how a new project called Valkey was born, a fork (copy) of Redis that stayed truly open-source.

Fast forward to May 2025 — Redis listened. They said

“We’re bringing back the open-source spirit. Redis version 8.0 will be under a proper open-source license again: AGPLv3.”

What’s AGPLv3?

It’s a type of license that says:

  • ✅ You can use, change, and share Redis freely.
  • 🌐 If you run a modified Redis on a website or cloud service, you must also share your changes with the world. (still hurts AWS and Azure)

This keeps things fair: no more companies secretly benefiting from Redis without giving back.

What Did Redis Say?

Rowan Trollope, Redis’s CEO, explained why they had changed the license in the first place:

“Big cloud companies were making money off Redis but not helping us or the open-source community.”

But now, by switching to AGPLv3, Redis is balancing two things:

  • Protecting their work from being misused
  • And staying truly open-source

Why This Is Good News

  • Developers can continue using Redis freely.
  • The community can contribute and improve Redis.
  • Fair rules apply to everyone, even giant tech companies.

Redis has come full circle. After a detour into more restricted territory, it’s back where it belongs in the hands of everyone. This shows the power of the developer community, and why open-source isn’t just about code, it’s about collaboration, fairness, and freedom.

Checkout this blog from Redis https://redis.io/blog/agplv3/

Before yesterdaypython

GIT configure in VSCode

16 May 2025 at 15:23

Create a Github account:
https://github.com/pradeep-xxx

Create a repository and choose the generated link:
https://github.com/pradeep-xxx/python_workouts.git

Use in VS code Terminal:
PS C:\Users\para\Documents\PYTHON> git init
PS C:\Users\para\Documents\PYTHON> git config --global user.name "Pradeep xxx"
PS C:\Users\para\Documents\PYTHON> git config --global user.email "pradeep.xxxx@gmail.com"

PS C:\Users\para\Documents\PYTHON> git remote add origin https://github.com/pradeep-xxx/python_works.git

PS C:\Users\para\Documents\PYTHON> git add . [OR]
git add ToDoList.py ToDoList2.py todotask.txt todotask2.txt

PS C:\Users\para\Documents\PYTHON> git commit -m "Initial Commit" [OR]
PS C:\Users\para\Documents\PYTHON> git commit -m "Add selected Python and text files" [OR]
PS C:\Users\para\Documents\PYTHON> git commit -m "Add ToDoList.py, ToDoList2.py, todotask.txt, and todotask2.txt"

PS C:\Users\para\Documents\PYTHON> git push --set-upstream origin master [OR -1st time]
PS C:\Users\para\Documents\PYTHON> git push

Redis for Python - via Docker - No direct WSL

16 May 2025 at 15:19

Redis doesn’t officially support native Windows installations anymore. Instead of setting up WSL (Windows Subsystem for Linux), Docker is the easier and more modern way to run Redis on a Windows machine.

Installing Docker Desktop gives you a full environment where you can run Redis (and many other tools) without friction.

🔹 Step 1: Install Docker Desktop
Download and install Docker Desktop from:
https://www.docker.com/products/docker-desktop/

Once installed:
Make sure Docker is running (look for the whale icon in your system tray).
Enable WSL2 integration if prompted during installation.

🔹 Step 2: Pull and Run Redis
Open PowerShell or Command Prompt and run:

docker run --name my-redis -p 6379:6379 -d redis
docker ps

🔹 Step 3: Connect to Redis
docker exec -it my-redis redis-cli
set name "DockerRedis"
get name
ping

Install RedisInsight and connect to:
https://redis.io/insight/
Host: localhost
Port: 6379

To find out whether your Windows PC uses an ARM64 or AMD64 (also called x64) architecture, follow these
from Command Prompt you can run:

C:\Users\pepsara>echo %PROCESSOR_ARCHITECTURE%

AMD64

C:\Users\pepsara>docker version
Client:
Version: 28.0.4
API version: 1.48
Go version: go1.23.7
Git commit: b8034c0
Built: Tue Mar 25 15:07:48 2025
OS/Arch: windows/amd64
Context: desktop-linux

Server: Docker Desktop 4.40.0 (187762)
Engine:
Version: 28.0.4
API version: 1.48 (minimum version 1.24)
Go version: go1.23.7
Git commit: 6430e49
Built: Tue Mar 25 15:07:22 2025
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.7.26
GitCommit: 753481ec61c7c8955a23d6ff7bc8e4daed455734
runc:
Version: 1.2.5
GitCommit: v1.2.5-0-g59923ef
docker-init:
Version: 0.19.0
GitCommit: de40ad0

C:\Users\pepsara>docker info

✅ Step-by-Step: Use Redis with Python in VS Code
🔧 1. Install Redis client for Python
In your terminal (inside VS Code), run:
pip install redis

🧪 2. Test Redis Connection in Python
Create a new Python file, e.g., redis_test.py, and add the following code:
import redis

Connect to Redis

r = redis.Redis(host='localhost', port=6379, db=0)

Set a key

r.set('mykey', 'Hello Redis!')

Get the key

value = r.get('mykey')
print(value.decode('utf-8')) # Output: Hello Redis!

Then run it: python redis_test.py
You should see: Hello Redis!

Task 6: Tuple

27 April 2025 at 03:50

1.Create a tuple containing the names of three fruits. Print the tuple and its type.

Image description

2.Given a tuple t = ("apple", "banana", "cherry"), access and print the second element.

Image description

3.Unpack the tuple t = (1, 2, 3) into variables a, b, and c, and print the variables.

Image description

4.Concatenate two tuples t1 = (1, 2) and t2 = (3, 4) and print the result.

Image description

5.Create a tuple t = ("repeat",) and repeat it three times. Print the resulting tuple.

Image description

6.Given a tuple t = (1, 2, 3, 2, 2, 4), count the number of times the number 2 appears.

Image description

7.Given a tuple t = ("a", "b", "c", "d"), find the index of the element "c".

Image description

8.Check if the element 5 is present in the tuple t = (1, 2, 3, 4)

Image description

9.Find and print the length of the tuple t = ("one", "two", "three").

Image description

10.Slice the tuple t = (0, 1, 2, 3, 4, 5) to obtain a sub-tuple containing only the elements from index 2 to 4.

Image description

11.Create a nested tuple representing a 2D point (x, y) = ((1, 2), (3,
4)). Access and print the second coordinate of the second point.

Image description

12.Try to change the value of the first element in the tuple t = (1, 2, 3) and observe what happens.

Image description

13.Convert a list l = [1, 2, 3] to a tuple and print the result. Then convert a tuple t = (4, 5, 6) to a list and print the result.

Image description

14.Create a tuple with a single item 5 and verify its type is a tuple.

Image description

15.Iterate over the tuple t = ("ParottaSalna", "is", "good") and print each element.
16.Convert the string "hello" into a tuple of characters.
17.Convert a dictionary d = {"one": 1, "two": 2} into a tuple of its items.
18.Write a function that takes a tuple of numbers and returns the sum of the numbers.
19.Use tuples as keys in a dictionary to represent points on a grid. For example, grid = {(0, 0): "origin", (1, 2): "point A"}.

Task 5: Python Function

26 April 2025 at 05:32

1.Write a function greet that takes a name as an argument and prints a greeting message.

Image description

2.Write a function sum_two that takes two numbers as arguments and returns their sum.

Image description

3.Write a function is_even that takes a number as an argument and returns True if the number is even, and False if it is odd.

Image description

4.Write a function find_max that takes two numbers as arguments and returns the larger one.

Image description

5.Write a function multiplication_table that takes a number n and prints the multiplication table for n from 1 to 10.

Image description

Image description

6.Write a function celsius_to_fahrenheit that takes a temperature in Celsius and returns the temperature in Fahrenheit.

Image description

7.Write a function power that takes two arguments, a number and an exponent, and returns the number raised to the given exponent. The exponent should have a default value of 2.

Image description

TASK 4: Python Lists

26 April 2025 at 02:10

1.Create a list of five delivery items and print the third item in the list. eg: [“Notebook”, “Pencil”, “Eraser”, “Ruler”, “Marker”]

Image description

2.A new delivery item “Glue Stick” needs to be added to the list. Add it to the end of the list and print the updated list.

Image description

3.Insert “Highlighter” between the second and third items and print the updated list.

Image description

4.One delivery was canceled. Remove “Ruler” from the list and print the updated list.

Image description

5.The delivery man needs to deliver only the first three items. Print a sublist containing only these items.

Image description

6.The delivery man has finished his deliveries. Convert all item names to uppercase using a list comprehension and print the new list.

Image description

7.Check if “Marker” is still in the list and print a message indicating whether it is found.

Image description

8.Print the number of delivery items in the list.

Image description

9.Sort the list of items in alphabetical order and print the sorted list.

Image description

10.The delivery man decides to reverse the order of his deliveries. Reverse the list and print it.

Image description

11.Create a list where each item is a list containing a delivery item and its delivery time. Print the first item and its time.

12.Count how many times “Ruler” appears in the list and print the count.

Image description

13.Find the index of “Pencil” in the list and print it.

Image description

14.Extend the list items with another list of new delivery items and print the updated list.

Image description

15.Clear the list of all delivery items and print the list.

Image description

16.Create a list with the item “Notebook” repeated three times and print the list.

Image description

17.Using a nested list comprehension, create a list of lists where each sublist contains an item and its length, then print the new list.

Image description

18.Filter the list to include only items that contain the letter “e” and print the filtered list.

Image description

19.Remove duplicate items from the list and print the list of unique items.

Image description

TASK 3: Slicing & Indexing

20 April 2025 at 07:42

1.Write a function that takes a string and returns a new string consisting of its first and last character.

Image description

2.Write a function that reverses a given string.

Image description

3.Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).

Image description

4.Write a function that returns every second character from a given string.

Image description

5.Write a function that replaces the middle third of a string with asterisks. If the length of the string is not divisible by 3, adjust the middle third accordingly.

6.Write a function that checks if a given string is a palindrome (reads the same backward as forward).

7.Given an email address, extract and return the domain.
Ans: How to find incase there are multiple occurrences? Loop?
Image description

Image description

8.Write a function that returns every third character from a given string.

Image description

9.Write a function that extracts and returns characters at even indices from a given string.

Image description

10.Write a function that skips every second character and then reverses the resulting string.

Image description

TASK 2: Constants and Variables

20 April 2025 at 04:14

1.Create a variable named name and assign your name to it. Then print the value of the variable.

Image description

2.Create a variable age and assign your age to it. Later, reassign the variable with a new value and print the new value.

Image description

3.Assign the values 5, 10, and 15 to three variables a, b, and c in a single line. Print their values.
Ans:TypeError on 4th statement, because we're trying to concatenate integers (a, b, c) with strings

Image description

4.Swap the values of two variables x and y without using a third variable. Print their values before and after swapping.

Image description

5.Define constants PI with appropriate values and print them.
Ans: constants are typically written in all uppercase letters with underscores separating words. However, Python does not enforce this, so constants are not truly immutable. You can still override.

Image description

6.Write a program that calculates the area of a circle using the constant PI and a variable radius. Print the area.
Ans: ** is Squared

Image description

7.Define constants for the length and width of a rectangle. Calculate and print the area.

Image description

8.Define a constant for π (pi) and a variable for the radius. Calculate and print the circumference of the circle.

Image description

TASK 1: Python – Print exercises

20 April 2025 at 02:26

1.How do you print the string “Hello, world!” to the screen?
Ans: Using sep and end Parameters is preferred way.
Image description

2.How do you print the value of a variable name which is set to “Syed Jafer” or Your name?
Ans: Note the Variable is case sensitive

Image description

3.How do you print the variables name, age, and city with labels “Name:”, “Age:”, and “City:”?
Ans: Using keyword sep="," brings in , between the Variable Name and Value itself, so avoid

Image description

4.How do you use an f-string to print name, age, and city in the format “Name: …, Age: …, City: …”?
Ans: To insert variables directly into the string used f-string
Also, you can assign values to multiple variables in a single line as seen in 1st line

Image description

5.How do you concatenate and print the strings greeting (“Hello”) and target (“world”) with a space between them?
Ans: + is used to concat the items

Image description

6.How do you print three lines of text with the strings “Line1”, “Line2”, and “Line3” on separate lines?****

Image description

7.How do you print the string He said, "Hello, world!" including the double quotes?
Ans: To print quotes inside a string, you can use either single or double quotes to enclose the string and the other type of quotes inside it.

Image description

8.How do you print the string C:\Users\Name without escaping the backslashes?
Ans: you can also use a literal backslash "\" when using Concat or Try with 'r' to treat backslashes as literal characters

Image description

9.How do you print the result of the expression 5 + 3?

Image description

10.How do you print the strings “Hello” and “world” separated by a hyphen -?

Image description

11.How do you print the string “Hello” followed by a space, and then print “world!” on the same line?

Image description

12.How do you print the value of a boolean variable is_active which is set to True?

Image description

13.How do you print the string “Hello ” three times in a row?

Image description

14.How do you print the sentence The temperature is 22.5 degrees Celsius. using the variable temperature?

Image description

15.How do you print name, age, and city using the .format() method in the format “Name: …, Age: …, City: …”?

Image description

16.How do you print the value of pi (3.14159) rounded to two decimal places in the format The value of pi is approximately 3.14?
Ans: pi is the variable & .2f formats it as a floating-point number with 2 digits after the decimal

Image description

17.How do you print the words “left” and “right” with “left” left-aligned and “right” right-aligned within a width of 10 characters each?

Image description

How to Manage Multiple Cron Job Executions

16 March 2025 at 06:13

Cron jobs are a fundamental part of automating tasks in Unix-based systems. However, one common problem with cron jobs is multiple executions, where overlapping job runs can cause serious issues like data corruption, race conditions, or unexpected system load.

In this blog, we’ll explore why multiple executions happen, the potential risks, and how flock provides an elegant solution to ensure that a cron job runs only once at a time.

The Problem: Multiple Executions of Cron Jobs

Cron jobs are scheduled to run at fixed intervals, but sometimes a new job instance starts before the previous one finishes.

This can happen due to

  • Long-running jobs: If a cron job takes longer than its interval, a new instance starts while the old one is still running.
  • System slowdowns: High CPU or memory usage can delay job execution, leading to overlapping runs.
  • Simultaneous executions across servers: In a distributed system, multiple servers might execute the same cron job, causing duplication.

Example of a Problematic Cron Job

Let’s say we have the following cron job that runs every minute:

* * * * * /path/to/script.sh

If script.sh takes more than a minute to execute, a second instance will start before the first one finishes.

This can lead to:

✅ Duplicate database writes → Inconsistent data

✅ Conflicts in file processing → Corrupt files

✅ Overloaded system resources → Performance degradation

Real-World Example

Imagine a job that processes user invoices and sends emails

* * * * * /usr/bin/python3 /home/user/process_invoices.py

If the script takes longer than a minute to complete, multiple instances might start running, causing

  1. Users to receive multiple invoices.
  2. The database to get inconsistent updates.
  3. Increased server load due to excessive email sending.

The Solution: Using flock to Prevent Multiple Executions

flock is a Linux utility that manages file locks to ensure that only one instance of a process runs at a time. It works by locking a specific file, preventing other processes from acquiring the same lock.

Using flock in a Cron Job

Modify the cron job as follows

* * * * * /usr/bin/flock -n /tmp/myjob.lock /path/to/script.sh

How It Works

  • flock -n /tmp/myjob.lock → Tries to acquire a lock on /tmp/myjob.lock.
  • If the lock is available, the script runs.
  • If the lock is already held (i.e., another instance is running), flock prevents the new instance from starting.
  • -n (non-blocking) ensures that the job doesn’t wait for the lock and simply exits if it cannot acquire it.

This guarantees that only one instance of the job runs at a time.

Verifying the Solution

You can test the lock by manually running the script with flock

/usr/bin/flock -n /tmp/myjob.lock /bin/bash -c 'echo "Running job..."; sleep 30'

Open another terminal and try to run the same command. You’ll see that the second attempt exits immediately because the lock is already acquired.

Preventing multiple executions of cron jobs is essential for maintaining data consistency, system stability, and efficiency. By using flock, you can easily enforce single execution without complex logic.

✅ Simple & efficient solution. ✅ No external dependencies required. ✅ Works seamlessly with cron jobs.

So next time you set up a cron job, add flock and sleep peacefully knowing your tasks won’t collide. 🚀

Write a video using open-cv

By: krishna
11 March 2025 at 13:30

Use open-cv VideoWriter function to write a video

Source Code

import cv2

video = cv2.VideoCapture("./data/video.mp4")
fourcc = cv2.VideoWriter.fourcc(*'FMP4')
writeVideo = cv2.VideoWriter('./data/writeVideo.mp4',fourcc,24,(1080,720))

while(video.isOpened()):
    suc, frame = video.read()
    if(suc):
        frame = cv2.resize(frame,(1080,720))
        cv2.imshow("write video",frame)
        writeVideo.write(frame)
        if(cv2.waitKey(24)&0xFF == ord('q')):
            break
    else:
        break

writeVideo.release()
video.release()
cv2.destroyAllWindows()

Video

Pre-Required Knowledge

If you know OpenCV, you can use it to open a video. If you don’t know this, visit this open video blog.

Functions

Explain Code

Import open-cv Library import cv2
Open a Video Using videoCapture Function

fourcc

The fourcc function is used to specify a video codec.
Example: AVI format codec for XVID.

VideoWriter

The videoWriter function initializes the writeVideo object. it specify video properties such as codec, FPS, and resolution.
There are four arguments:

  1. Video Path: Specifies the video write path and video name.
  2. fourcc: Specifies the video codec.
  3. FPS: Sets an FPS value.
  4. Resolution: Sets the video resolution.

The read() function is used to read a frame.

After reading a frame, resize() it.
Note: If you set a resolution in writeVideo, you must resize the frame to the same resolution.

write

This function writes a video frame by frame into the writeVideo object.

The waitKey function is used to delay the program and check key events for program exit using an if condition.

Release objects

Once the writing process is complete, release the writeVideo and video objects to finalize the video writing process.

Additional Link

github code

❌
❌