Sitemap
A list of all the posts and pages found on the site. For you robots out there is an XML version available for digesting as well.
Pages
Posts
How to Recover SSH Access to an AWS EC2 Ubuntu Instance After Enabling Firewal?
Published:
Introduction
I recently ran into an interesting problem with one of my AWS EC2 instances. I had a small Ubuntu server running on an EC2t3.micro instance with an 8 GB EBS volume. Everything was working perfectly, and I could connect to the server using SSH and my private key. I decided to increase the EBS storage from 8 GB to 16 GB. This seemed like a straightforward operation, and I didn’t expect it to cause any problems. However, shortly afterward, I discovered that I could no longer connect to my server. Initially, I suspected that increasing the disk size had somehow broken the instance. After investigating, I discovered something much simpler: I had enabled the firewall, i.e., UFW (Uncomplicated Firewall) without allowing SSH connections first. This blog post documents how I diagnosed the problem and recovered access to my original Ubuntu installation without losing data or rebuilding the EC2 instance.1. The Initial Problem
My original EC2 configuration was:| Component | Configuration |
|---|---|
| Cloud provider | AWS |
| Instance type | t3.micro |
| Operating system | Ubuntu |
| Original EBS volume | 8 GB |
| Updated EBS volume | 16 GB |
| Connection method | SSH with private key |
| SSH username | ubuntu |
ssh -i your-key.pem ubuntu@EC2_PUBLIC_IP
- The instance was running.
- Both EC2 status checks passed (3/3).
- The EBS volume had been successfully increased to 16 GB.
2. Diagnosing the SSH Connection Problem
The next step was to enable verbose SSH logging. I ran:ssh -vvv -i your-key.pem ubuntu@EC2_PUBLIC_IP
OpenSSH_9.6p1 Ubuntu-3ubuntu13.20, OpenSSL 3.0.13
debug1: Connecting to EC2_PUBLIC_IP port 22.
debug3: set_sock_tos: setting socket options
3. Understanding How UFW Can Block SSH
UFW stands for Uncomplicated Firewall. It is a frontend for managing Linux firewall rules and is commonly used on Ubuntu servers. One important thing to understand is that enabling UFW without first allowing SSH can block incoming SSH connections. For example, this command enables the firewall:sudo ufw enable
sudo ufw allow 22/tcp
sudo ufw enable
sudo ufw status verbose
sudo ufw allow from YOUR_PUBLIC_IP to any port 22 proto tcp
4. Attempting to Recover Access Through EC2 Serial Console
AWS provides a feature called EC2 Serial Console. It allows administrators to access an instance through a serial connection, independently of its normal network connectivity. I tried:- Opening the EC2 console.
- Selecting my instance.
- Clicking Connect.
- Choosing EC2 Serial Console.
Failed to connect to your instance
SendSerialConsoleSSHPublicKey failed.
Try again later.
- Serial Console access must be enabled at the AWS account level.
- The IAM user or role must have the required permissions.
- Any applicable AWS Organizations restrictions must permit access.
- The AWS Region and instance must support the feature.
5. Understanding the Ubuntu EC2 Default Credentials
Even if the serial connection succeeds, Ubuntu may still require an operating-system username and password. A common question when using EC2 Serial Console is: What are the default Ubuntu credentials? For standard Ubuntu EC2 images: Username:ubuntu
ubuntu user. Therefore, even if I managed to establish a serial console connection, I would potentially need to recover or configure a password before logging in. That is, default username is known but password was not set and I could not login. I needed a different recovery method.6. Recovering the Instance Using a Temporary EC2 Instance
The solution was to use another EC2 instance as a recovery machine. This approach allows you to access the original Ubuntu filesystem by attaching its EBS volume to another Linux instance. The advantage is that you don’t need to reinstall Ubuntu or delete your existing data.Step 6.1: Create a temporary Ubuntu EC2 instance
I created a new EC2 instance with the following configuration:| Setting | Value |
|---|---|
| Name | ubuntu-recovery |
| AMI | Ubuntu Server |
| Instance type | t3.micro |
| Availability Zone | Same as original instance |
| SSH access | Restricted to my public IP |
Step 6.2: Stop the original instance
Before detaching its root EBS volume, I stopped the original EC2 instance. I then opened: AWS Console → EC2 → Volumes. I identified the original 16 GB EBS volume. As an additional precaution, I created an EBS snapshot before modifying anything. This provided a recovery point in case something went wrong.Step 6.3: Detach the original EBS volume
I selected the original volume and chose: Actions → Detach volume. Once the volume was detached, I attached it to the temporary Ubuntu recovery instance. Both instances needed to be in the same Availability Zone for this attachment. I selected a secondary device name, such as/dev/sdf. An important detail: AWS device names and Linux device names don’t always match. On Nitro-based instances, an attached EBS volume commonly appears as an NVMe device.Step 6.4: Identify the original disk
After connecting to the temporary instance through SSH, I executed:lsblk -f
nvme0n1
├─nvme0n1p1 ext4 cloudimg-rootfs ... /
├─nvme0n1p13 ext4 BOOT ... /boot
├─nvme0n1p14
└─nvme0n1p15 vfat UEFI ... /boot/efi
nvme1n1
├─nvme1n1p1 ext4 cloudimg-rootfs
├─nvme1n1p13 ext4 BOOT
├─nvme1n1p14
└─nvme1n1p15 vfat UEFI
/dev/nvme0n1: The temporary recovery instance’s own disk./dev/nvme1n1: The original EC2 instance’s disk.
/dev/nvme1n1p1
Step 6.5: Mount the original filesystem
I tried mounting the disk:sudo mkdir -p /mnt/recovery
sudo mount /dev/nvme1n1p1 /mnt/recovery
ls /mnt/recovery
bin
boot
dev
etc
home
lib
root
usr
var
7. Using chroot to Access the Original Ubuntu Installation
Another useful Linux feature ischroot. It allows you to change the apparent root directory of a process. In this situation, it allowed me to execute commands within the original Ubuntu filesystem while running the recovery instance. Before entering the chroot environment, I mounted the necessary virtual filesystems:sudo mount --bind /dev /mnt/recovery/dev
sudo mount --bind /proc /mnt/recovery/proc
sudo mount --bind /sys /mnt/recovery/sys
sudo mount --bind /run /mnt/recovery/run
sudo chroot /mnt/recovery
cat /etc/ufw/ufw.conf
cat /mnt/recovery/etc/ufw/ufw.conf
/.8. Disabling UFW on the Original Installation
Once inside the chroot environment, I checked the UFW configuration:cat /etc/ufw/ufw.conf
ENABLED=yes
ufw disable
sed -i 's/^ENABLED=yes/ENABLED=no/' /etc/ufw/ufw.conf
An additional step: Set an Ubuntu password
Since I was already inside the original Ubuntu installation, I also had the opportunity to set a password for the Ubuntu user:passwd ubuntu
9. Exiting chroot and Unmounting the Original Filesystem
After completing the changes, I exited the chroot environment:exit
sudo umount /mnt/recovery
umount: /mnt/recovery: target is busy
- A terminal whose current working directory is inside the mounted filesystem.
- A process running inside the mounted filesystem.
- Filesystems such as
/dev,/proc,/sys, and/runstill mounted beneath/mnt/recovery.
findmnt -R /mnt/recovery
sudo fuser -vm /mnt/recovery
cd /
sudo umount /mnt/recovery/run
sudo umount /mnt/recovery/sys
sudo umount /mnt/recovery/proc
sudo umount /mnt/recovery/dev
sudo sync
sudo umount /mnt/recovery
10. Reattaching the Original Volume
Once the original filesystem is safely unmounted:- Open EC2 → Volumes.
- Select the original 16 GB EBS volume.
- Detach it from the temporary recovery instance.
- Attach it to the original EC2 instance.
- Restore its original root device mapping.
- Start the original EC2 instance.
11. Testing SSH Again
After the original instance starts, check its current public IPv4 address. If the instance was stopped and started, its public IP may have changed unless it uses an Elastic IP. That was the case. Then try:ssh -i your-key.pem ubuntu@EC2_PUBLIC_IP
12. Lessons Learned
This experience taught me several useful lessons about AWS EC2 and Linux server administration. Let me mention a few here:A) Always allow SSH before enabling UFW
This is probably the most important lesson. Before enabling UFW again, explicitly allow SSH. No, I am not talking about enabling SSH in SecurityGroup. I am talking about UFW. It is like making sure, when you leave home, you have your house keys before you slam the door behind you. To enable UFW, use:sudo ufw allow from YOUR_PUBLIC_IP to any port 22 proto tcp
sudo ufw enable
B) EBS volume resizing and filesystem resizing are different operations
Increasing an EBS volume from 8 GB to 16 GB does not automatically mean that Ubuntu will use all the additional space.C) AWS status checks don’t guarantee SSH connectivity
This sounds obvious but important and I overlooked it. An instance can pass all AWS status checks and still be inaccessible over SSH. Status checks primarily monitor the health of the instance and its underlying infrastructure. They don’t guarantee that your firewall, SSH daemon, or network configuration is correct.D) Keep an alternative recovery method available
AWS provides several ways to recover an inaccessible EC2 instance:- EC2 Serial Console.
- AWS Systems Manager Session Manager.
- EBS volume attachment to another instance.
E) Never modify an EBS volume without a backup
This is also somewhat obvious but important. Before making significant changes to an instance’s root disk, create an EBS snapshot. It provides an additional layer of protection if a recovery operation goes wrong.Conclusion
What initially looked like a problem caused by increasing an EBS volume turned out to be a firewall configuration issue. The recovery process involved creating a temporary Ubuntu instance, attaching the original EBS volume, mounting the original root partition, entering the installation using chroot, and checking the UFW configuration. Even when the original operating system is inaccessible, AWS’s EBS architecture gives you a practical way to recover the filesystem and repair the installation without rebuilding the server. And, most importantly, always remember: Allow SSH before enabling firewall on a remote Ubuntu server! Read moreGoogle Adsens
Published:
You can add both Google AdSense (to display advertisements and earn revenue) and Google Analytics 4 (GA4, to track website visitors and traffic) to your website hosted on GitHub Pages using the AcademicPages template. The good news is that AcademicPages is built with Jekyll, so you generally don’t need to modify the template’s core code. You can add Google’s tracking and advertising scripts through the Jekyll layout files. I’ll explain how to do both.
1. Add Google Analytics 4 (GA4)
GA4 / Google Analytics 4 Migration & Transition by Tinderpoint* Google Analytics Tracks visitors, page views, traffic sources, geographic statistics, and user engagement. Free serviceStep 1: Create a Google Analytics account
- Go to Google Analytics.
- Sign in with your Google account.
- Create an account for your website.
- Create a GA4 property.
- Add a Web data stream.
- Enter your website URL, for example:
https://yourusername.github.io - Google will provide a Measurement ID similar to:
G-XXXXXXXXXX
Step 2: Find the correct AcademicPages file
In your GitHub repository, locate:_config.yml AcademicPages normally supports Google Analytics configuration through this file. Look for a section similar to: yamlanalytics:
provider: false
analytics:
provider: "google-gtag"
google:
tracking_id: "G-XXXXXXXXXX"
anonymize_ip: true
G-XXXXXXXXXX with your actual Measurement ID. Save and commit the changes. Important: If your version of AcademicPages has a different analytics configuration, check its _includes/analytics/ directory and existing configuration before adding another tracking script. You don’t want Analytics installed twice.Step 3: Verify that Analytics works
- Wait a few minutes after deploying your website.
- Open Google Analytics.
- Navigate to Reports → Realtime.
- Open your website in another browser tab.
2. Add Google AdSense (to earn money from advertisements)
| Monetize Your Content with Google AdSense | Earn Revenue from Ads |
Step 1: Register your website
- Visit Google AdSense.
- Sign in using your Google account.
- Add your website URL.
- Complete the registration process.
- Google will provide an AdSense verification code.
Step 2: Add the AdSense code to AcademicPages
In your GitHub repository, look for:_includes/head/custom.html If this file doesn’t exist, create it. Paste the AdSense code provided by Google into this file. It will look similar to: HTMLWrap linesCopy codePreview<script async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
crossorigin="anonymous">
</script>
Step 3: Enable automatic advertisements
Once Google approves your website:- Open your AdSense account.
- Go to Ads → By site.
- Select your website.
- Enable Auto ads.
- Save your settings.
Step 4: Add ads.txt
Google may ask you to publish anads.txt file. Create a plain-text file named: ads.txt Place it in the root directory of your GitHub repository, alongside files such as index.html and _config.yml. It will contain a line similar to: textgoogle.com, pub-XXXXXXXXXXXXXXXX, DIRECT, f08c47fec0942fa0
https://yourusername.github.io/ads.txt3. Important: A correction for AcademicPages Analytics configuration
After checking the AcademicPages repository, I found that its configuration supportsgoogle-analytics-4 as the provider. So, for the standard AcademicPages template, I recommend using this configuration in _config.yml instead of the google-gtag example I gave earlier: yamlanalytics:
provider: "google-analytics-4"
google:
tracking_id: "G-XXXXXXXXXX"
4. Important considerations for a website hosted in Germany
Since your website may receive visitors from Germany and other EU countries, pay attention to privacy requirements.- Add a privacy policy (Datenschutzerklärung) explaining your use of Google Analytics and AdSense.
- Configure appropriate cookie consent before activating non-essential tracking technologies.
- For personalized advertising to EEA visitors, Google requires a Google-certified consent management platform (CMP) integrated with the IAB Transparency and Consent Framework. Google AdSense Help +1
5. Recommended GitHub repository structure
After integrating both services, your AcademicPages repository could look like this: textyour-website/
│
├── _config.yml
│
├── _includes/
│ ├── head/
│ │ └── custom.html
│ └── analytics.html
│
├── _layouts/
│
├── _pages/
│
├── assets/
│
├── ads.txt
│
└── index.html
How Generative AI Could Bring Families Together for Unforgettable Moments
Published:
On one lazy Sunday, I started contemplating how smartphones (dis)connected us at home, i.e., connected the far but disconnected the near. While exploring how this could be reversed, I came to know that generative AI can offer something truly special for people looking to enhance their time together. In this article, I am going show you how you can dive into a world of creativity, learning, and fun together, with just a voice command. It is a low-cost system that can blend technology and imagination, transforming everyday moments into extraordinary memories. First, let us see a hypothetical scenario that elucidates what I meant by dis(connected).
Scenario
Let us have a look at a scenario where this project could be applied to – a family evening lost in their devices.It’s a cozy Friday evening, and the living room of the Johnson household is filled with soft, warm lighting. The smell of freshly popped popcorn drifts through the air as the TV is playing quietly in the background, almost unnoticed. Instead of gathering together to chat, watch a movie, or share stories, each family member is lost in their own digital world.
Dad, sitting on the comfy armchair, is absorbed in his tablet, scrolling through news articles and checking work emails. Despite it being the weekend, he’s still glued to his device, trying to catch up on things he missed during the week. Every now and then, he taps the screen to close a notification or reply to a message, his eyes never leaving the glowing device.
Mom, lounging on the sofa, is deep into an online shopping spree. She’s comparing prices for the latest home décor and reading reviews for a vacuum cleaner she’s been eyeing. Every so often, she pauses to flick through social media, liking photos from friends and catching up on posts. Her focus is so intense that she doesn’t even notice the cat jumping up beside her, meowing for attention.
Teenage Daughter, sitting cross-legged on the rug, is hunched over her phone, scrolling through TikTok videos. She occasionally bursts out laughing or grins at a funny meme but doesn’t engage with anyone else in the room. Her phone seems like an extension of her hand, and the world around her, including her family, fades into the background.
Does this scenario sound familiar?Young Son, in the corner, is glued to his gaming console. With headphones on, he’s navigating a virtual world, immersed in a fast-paced game where he’s battling enemies and leveling up. He occasionally mutters under his breath, reacting to the game’s challenges, but not once does he look up to see what’s happening in the room around him.
How Voice-Controlled Image Generation Could Change this Scenario
The soft hum of technology fills the room as each person stays wrapped in their digital bubble. The TV, once the centerpiece of family evenings, is now a mere background noise, occasionally offering up scenes that no one is paying attention to. The sound of the popcorn popping seems like a distant memory, drowned out by the constant ping of notifications and the quiet clicks of fingers on touchscreens. There’s a sense of disconnect, even though everyone is physically in the same room. The cozy atmosphere and shared space feel almost hollow as each person retreats into their own digital world. While the furniture is filled, the space feels eerily empty. Conversation has been replaced by the flicker of screens, and the family, in this moment, is scattered, mentally and emotionally, across the vast internet instead of together in the living room. It’s the perfect example of how technology, while useful and entertaining, can also create a subtle divide between people—turning shared family time into isolated moments, even when everyone is physically present. The living room, once a place for gathering and connection, is now more like a silent digital sanctuary for each family member.In today’s fast-paced world, finding ways to connect and bond with our loved ones is more important than ever. While technology often gets a bad rap for isolating us, there’s a shining example of how it can actually bring us closer together: the marriage of Generative AI, Your TV and Raspberry Pi to create a fun, interactive experience in the living room. Imagine this: you issue a voice command, and within seconds, a unique image generated by AI appears on your TV screen. Sounds exciting, right? Everyone in the room can be mesmerized by the stunning image and scenery generated by AI and displayed on TV. One can also see some flaws after a deeper look into the generated image. Then laughter errupts. Let’s dive into how this setup can redefine family time and spark creativity in every household.
With the power of Generative AI at your fingertips, you can now create and experience personalized images at the mere sound of their voices. Using a Raspberry Pi, this project turns everyday moments into extraordinary ones, in an affordable way. The AI listens to your voice command, interprets it, and generates an image on the spot. Want to see a majestic sunset over a mountain range? Just ask! Curious about how a spaceship would look flying through a galaxy made of candy? It’s on the screen in seconds! This voice-controlled interaction is more than just a gimmick—it’s an entirely new way for people to engage with technology. Whether you’re huddled around the TV after dinner, enjoying a lazy weekend morning, hosting a family get-together, or a party, this system provides an experience that’s both fun and unique in that it offers:
A) Endless Possibilities for Creative Fun
Generative AI opens up a world of creative possibilities that can bring families together in new and exciting ways. Here are a few ways families can use this system to spark their imagination:- Personalized Artwork: Whether you’re looking to see a family portrait recreated as a painting or an abstract piece of art that represents the spirit of your family, the AI can generate one-of-a-kind images based on simple descriptions. Imagine a family member describing their favorite memory—like a summer trip to the beach—and the AI visualizing it in an artistic style.
- Interactive Storytelling: Kids and adults alike can come together to create stories. By simply providing a prompt, such as “a dragon flying over a city,” the AI can generate images that illustrate the story. As you watch the AI bring these scenes to life, you can continue building the narrative, turning it into a collaborative storytelling adventure.
- Family Games and Challenges: Take family game night to the next level! Use voice commands to generate riddles, puzzles, or even trivia challenges, with the AI producing images or clues based on each family member’s input. AI can also create custom word puzzles or visual challenges to keep everyone entertained and engaged.
B) Building Deeper Connections
In an age where many of us are caught up in the digital world, it’s easy to forget the power of shared experiences. The generative AI system provides a unique opportunity to reconnect with each other. Here’s how it fosters deeper bonds:- Hands-On Fun: The ability to control the system with voice commands gives everyone in the family a chance to participate, no matter their age. Parents, kids, and even grandparents can get involved, making it a great way to build stronger connections across generations.
- Shared Creativity: As you collaborate to create stories, images, or games, everyone in the family contributes their ideas, which fosters creativity and teamwork. This shared process helps bond family members through shared goals and fun.
- Accessible for Everyone: The simplicity of voice commands makes this system accessible for all ages and abilities. Even younger children or older relatives who aren’t as tech-savvy can easily interact with the system, ensuring everyone can join in on the fun.
C) Bringing Fun into Learning
Learning together as a family doesn’t have to be a dull experience. With AI-generated content, your family can enjoy educational activities that are as engaging as they are informative. Imagine learning about history by having AI generate visual depictions of historical events or creating scientific experiments with AI-generated diagrams and illustrations. Here are some ways you can turn learning into a shared family experience:- Interactive Learning: Ask the AI to explain complex topics like the solar system, dinosaurs, or ancient civilizations, and let it generate images that help illustrate the concepts. This can make learning more interactive and visually exciting.
- Creative Problem Solving: Use the AI to generate visual challenges or brainteasers that stimulate critical thinking. This encourages family members to work together, think creatively, and come up with solutions in a collaborative way.
D) Simple Setup with Raspberry Pi
One of the most exciting parts of this project is that it runs on a Raspberry Pi—a low-cost, energy-efficient computer that’s incredibly versatile. Not only does this make the setup affordable for anyone, but it also ensures that the system is easy to maintain and can run without consuming a lot of energy. The Raspberry Pi serves as the perfect platform for this project, offering enough power to run the necessary software while remaining compact and portable.Hands-on …
So, what are you waiting for? Start generating and let the family fun begin! Clone the project from the GitHub repository, follow the steps and enjoy it! Read moreIntroduction to Programming with Python
Published:
- Introduction to Programming
- Flow Control in Programming
- Functions
- Basic Data Structures
- Practical Examples
- Summary
- What is Next?
Introduction to Programming
Programming is the process of giving a set of instructions to a computer to perform a specific task. Programming languages are used to write these instructions. Python is one of the most popular programming languages due to its:- Readable Syntax: Python’s syntax is simple and easy to understand, making it ideal for beginners.
- Versatility: Python is used in web development, data analysis, artificial intelligence, machine learning, automation, and more.
- Large Community: Python has a vast community, providing plenty of resources for learning.
Flow Control in Programming
Flow control refers to the order in which individual statements, instructions, or function calls are executed in a program. There are three main types of flow control:Linear Flow
Linear flow means the program runs from the top to the bottom, executing one instruction after another without any branching or looping as show in the example below:# Linear Flow Example
print("Start of program")
x = 10
y = 5
sum = x + y
print("The sum is:", sum)
Conditional Statements (Making Decisions)
Conditional statements allow a program to make decisions based on whether a condition is true or false. The most common conditional statements are if, elif, and else.if Statement
The if statement evaluates a condition and executes a block of code if the condition is true.
age = 20
if age >= 18:
print("You are an adult.")
else Statement
The else statement executes a block of code if the condition in the if statement is false.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
elif Statement
The elif (i.e., short form of else if) statement allows you to check multiple conditions.
age = 25
if age < 18:
print("You are a minor.")
elif age < 21:
print("You are an adult, but not yet 21.")
else:
print("You are 21 or older.")
Looping (Iteration)
Loops allow us to repeat a block of code multiple times. There are two common types of loops: for loops and while loops.for Loop
A for loop is used to iterate over a sequence (like a list, tuple, or string). It executes a block of code for each item in the sequence. For loop is a powerful tool for automating repetitive tasks.
# Iterating through a list using a for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
fruits is the name of the variable containing the list above whereas fruit is the name of the variable that will hold the items in the list during the iteration.while Loop
A while loop repeatedly executes a block of code as long as a condition is True.
# Using a while loop to print numbers from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1 # Increment count by 1
When to use for Loop or while Loop?
Now that you understand for loop and while loop, you may have a question: “when is for loop preferred over while loop? when is while loop preferred over for loop?” A for loop is typically preferred over a while loop when:- Number of Iterations is Known or Finite: If you know in advance how many times you need to iterate, a for loop is often more appropriate. For example, iterating over a list or a fixed range of numbers as in the example below:
for i in range(10): # Iterates 10 times print(i) - Iterating Over a Sequence or Collection: When you need to iterate over items in a sequence like a list, tuple, string, or dictionary, the for loop is cleaner and more readable.
my_list = [1, 2, 3, 4] for item in my_list: print(item) - Clear Loop Boundaries: When the loop has well-defined start and end conditions, for loops help make the boundaries explicit, improving readability and reducing the chance of infinite loops.
for i in range(0, 100, 10): # Looping from 0 to 90 in steps of 10 print(i) - Iteration with Known Step Size: When you need to iterate through a range with a specific step size (e.g., incrementing or decrementing by a set number), a for loop is typically easier to use.
for i in range(0, 20, 2): # i goes 0, 2, 4, 6, ..., 18 print(i)
# Continue until a valid user input is provided
while True:
user_input = input("Enter a number: ")
if user_input.isdigit():
break
range() function is commonly used to generate a sequence of numbers. It provides an easy way to iterate a specific number of times or over a defined sequence of values. The basic syntax of range() is as follows:range(start, stop, step)
- start: The starting value of the sequence (inclusive). If not specified, it defaults to 0.
- stop: The ending value of the sequence (exclusive). This value is not included in the sequence.
- step: The difference between each number in the sequence. This is optional, and if not specified, it defaults to 1. Have a look at the following examples on the use of
range()function:
- Basic range without start or step:Output:
for i in range(5): # This will loop from 0 to 4 (not including 5) print(i)0 1 2 3 4 - Range with start and stop:Output:
for i in range(2, 6): # This will loop from 2 to 5 (not including 6) print(i)2 3 4 5 - Range with step:Output:
for i in range(1, 10, 2): # This will loop from 1 to 9, with a step of 2 print(i)1 3 5 7 9 - Negative step:Output:
for i in range(10, 0, -2): # This will loop from 10 to 2 (not including 0), stepping by -2 print(i)10 8 6 4 2
Key points about range() function:
startis inclusive, butstopis exclusive. So, the loop will stop just before reaching thestopvalue.- If
startis greater thanstopand the step is positive, the loop won’t run. Similarly, if the step is negative andstartis less thanstop, the loop won’t run.
break, continue and pass Statements
In python, there are three statements that are used to change the behavior of loops:- break: Exits the loop prematurely. It is used to end the loop when some condition is satisfied. For example, if a loop is searching an item in a list, it should exit as soon as it gets the time.
- continue: Skips the rest of the current iteration and moves to the next one.
- pass is a statement that does nothing. It is often used as a placeholder or to intentionally ignore certain code blocks.
# Using break and continue for i in range(10): if i == 5: break # Stop the loop when i equals 5 if i % 2 == 0: continue # Skip the rest of the loop if i is even print(i)
Nested loops
There is also another variant of loop where you have loops inside loops (called nested loops). In Python, you can nest any type of loop (like afor loop or a while loop) inside another loop. Nested loops are commonly used when you need to perform more complex iterations, like working with 2D arrays, matrices, or iterating through multiple dimensions. Basic Structurefor outer_item in outer_sequence:
for inner_item in inner_sequence:
# Do something with outer_item and inner_item
- The outer loop runs first and controls how many times the inner loop will execute.
- The inner loop will complete all of its iterations for each single iteration of the outer loop. Have a look at the examples below:
for Loop with a List of Lists (2D list) Imagine you have a 2D list (a list of lists), and you want to loop through each row and each element in the row.matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix: # Outer loop (iterates over each row)
for element in row: # Inner loop (iterates over each element in the row)
print(element, end=" ")
print() # Move to a new line after each row
1 2 3
4 5 6
7 8 9
- the outer loop goes over each row of the matrix.
- the inner loop goes through each element in that row and prints it.
- the
end=" "keeps the output on the same line, andprint()without arguments moves to the next line after completing one row.
Example 2: Nested Loops for Multiplication Table
A common example of a nested loop is generating a multiplication table. Here’s how you can do it with two nestedfor loops:for i in range(1, 6): # Outer loop for the first number (1-5)
for j in range(1, 6): # Inner loop for the second number (1-5)
print(f"{i} x {j} = {i * j}", end="\t")
print() # Move to a new line after each row
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15
4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
Example 3: Nested Loops with a Condition
You can also combine nested loops with conditions. For example, let’s print the elements of a 2D list but only if they are even:matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
if element % 2 == 0: # Check if the element is even
print(element, end=" ")
print() # Move to a new line after each row
2
4 6
8
Example 4: Nested while Loop
You can also nest while loops. Here’s an example of nested while loops that print a pattern:i = 1
while i <= 3: # Outer while loop
j = 1
while j <= 3: # Inner while loop
print(f"i={i}, j={j}")
j += 1
i += 1
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
Key Points:
- Outer loop runs once for each item in its sequence, and for every iteration, the inner loop runs through its entire sequence.
- Performance considerations: Nested loops can become slow if the sequences you’re iterating over are large because the time complexity increases with the depth of nesting. For example, two nested loops over lists of length
nresult in a time complexity ofO(n^2). - Indentation: In Python, proper indentation is critical. The body of each loop must be indented.
Conclusion:
Nested loops are a powerful tool when dealing with multi-dimensional data structures or when you need to perform repetitive tasks with multiple layers of iteration. Just remember that the deeper you nest loops, the more computationally expensive it becomes!Functions
Functions are reusable blocks of code that perform a specific task. Functions allow you to avoid repetition of codes and make your code more organized and readable. Functions allow you to break your program into smaller, manageable pieces, making it easier to read, maintain, and test.Defining and calling a function
You define a function in Python using thedef keyword.# Defining a function
def greet(name):
print(f"Hello, {name}!")
# calling the function
greet("Alice")
greet("Bob")
greet is the name of the function and name is the parameter. The function prints greeting text for the given parameter. The output of the above code will be:Hello, Alice!
Hello, Bob!
Function with Return Value
Functions can return values using the return keyword. This allows you to use the result of the function in other parts of the program.
def add(x, y):
return x + y
result = add(5, 10)
print("Sum:", result)
add returns the sum of the numbers given to it as input and returns their sum.Data Structures
Data structures are containers used to store and organize data. Python has several built-in data structures:Lists
A list is an ordered collection of items. Lists are mutable, meaning you can change their content.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add a new item to the list
print(fruits[0]) # Accessing the first item
Tuples
A tuple is similar to a list but immutable. Once created, you cannot change the values in a tuple.
coordinates = (10, 20)
print(coordinates[0]) # Accessing the first value in the tuple
Dictionaries
A dictionary is a collection of key-value pairs. Each key is unique, and it maps to a corresponding value.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"]) # Accessing a value by key
Sets
A set is an unordered collection of unique items. Sets do not allow duplicates.
fruits = {"apple", "banana", "cherry"}
fruits.add("orange") # Adding an item to the set
print(fruits)
Summary
In this tutorial, you have learned:- Basic programming concepts: What programming is, why Python is a great language to start with.
- Flow control: Linear flow, decision making with if, elif, and else, and iterations using for and while loops.
- Functions: How to define and use functions for reusable code blocks.
- Data structures: Working with lists, tuples, dictionaries, and sets to store and organize data.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y if y != 0 else "Cannot divide by zero!"
# Test the calculator
print("Addition:", add(10, 5))
print("Subtraction:", subtract(10, 5))
print("Multiplication:", multiply(10, 5))
print("Division:", divide(10, 5))
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
num = 7
print(f"{num} is {check_even_odd(num)}.")
What is Next?
Before deliving into advanced topics:- Practice the examples and modify them to fit your needs.
- Solve problems on coding platforms like w3schools, LeetCode, Codewars, or HackerRank to improve your skills.
Now that you have read the article till the end, did you find this blog post useful? Drop me your comment as a message on LinkedIn Read more
Step-by-step guide to Developing a Simple Flask Application that Generates QR Codes
Published:
QR codes have become an essential part of many digital interactions, offering an easy way to link offline and online worlds. Whether for business, marketing, or personal use, their ability to store information quickly and be easily scanned makes them a valuable tool.
Table of content
This article provides an overview of QR Code and a simple python application to generate a QR Code. The first part offers inroduction to QR code and the second part walks you through the steps to the implementation of QR generator in python. If you are interested only to the implementation, you can directly jump to the section Generating QR Code. The full code is available here.Part I: What is QR Code?
What exactly are QR Codes? A QR code (short for Quick Response code) is a type of two-dimensional barcode that can store a variety of data such as text, URLs, contact information, and other data types. Unlike traditional barcodes, which are one-dimensional and only store information in a single line, a QR code can store much more data due to its two-dimensional structure, allowing for both horizontal and vertical information storage. Key Features of QR Codes- Matrix Barcode: A QR code consists of a grid (matrix) of black and white squares arranged in a square shape. This grid can vary in size, with larger grids storing more data.
- Data Capacity: QR codes can store much more data than traditional barcodes. For example: A basic QR code can hold around 3,000 characters or 7,000 numeric digits. Depending on the error correction level, it can store text, URLs, phone numbers, or even binary data.
- Error Correction: QR codes incorporate error correction techniques that allow them to remain readable even if they are partially damaged. This is achieved by using a feature known as the Reed-Solomon error correction algorithm. Different levels of error correction can be applied (from L to H), with higher levels allowing for more damage but reducing the data capacity.
- Speed and Efficiency: QR codes are designed for quick scanning. Unlike traditional barcodes, which require a scanner to move along the code to read it, QR codes can be scanned from any angle and can be read almost instantly.
- Static QR Codes: These are QR codes whose data cannot be changed once they are created. They can store URLs, text, or other types of information.
- Dynamic QR Codes: These allow for the data to be changed after the code has been printed or distributed. For example, a dynamic QR code might redirect to different URLs based on the context or tracking information.
- Positioning Patterns: A QR code has three large squares at three corners, which are used to help the scanner locate and orient the code.
- Alignment Patterns: These help the scanner read the QR code even when it’s tilted or distorted.
- Timing Patterns: These help the scanner detect the size of the QR code matrix and ensure it’s scanned correctly.
- Data and Error Correction Area: The majority of the QR code consists of data and error correction bits. This is where the actual information is encoded.
- Quiet Zone: A quiet zone is a border of white space surrounding the QR code, ensuring that the scanner can correctly identify the edges of the code.
- URL Links: A common use is to encode URLs (web addresses). When scanned, a user is directed to the website.
- Payment Systems: QR codes are widely used in mobile payment systems, such as WeChat Pay, Alipay, or Apple Pay.
- Event Tickets: QR codes are often used on event tickets, boarding passes, or coupons.
- Product Tracking and Information: Manufacturers can use QR codes for inventory management, shipment tracking, and product information.
- Contact Information: vCards (electronic business cards) can be encoded in QR codes, making it easy for users to scan and save contact info.
- Marketing: QR codes are frequently used in marketing campaigns, advertisements, and posters to link to special offers or promotions.
- High Data Capacity: QR codes can store much more data compared to traditional barcodes.
- Fast and Easy to Scan: QR codes can be scanned quickly and easily from almost any direction.
- Versatility: They can store various types of data, from simple text to complex URLs or other information.
- Error Tolerance: QR codes can still be read even if they are partially damaged or obscured.
Generating QR Code
Now that you understand what a QR code is, let us go through a python application that generates it. We will use a simple Flask application that generates QR codes using theqrcode library along with Flask. Below is a step-by-step guide to creating the app: Step 1: Install dependencies First, you need to install the necessary libraries. Open your terminal or command prompt and run the following commands: pip install Flask qrcode[pil] Flask is the web framework and qrcode[pil] is the library used to generate QR codes with support for images (Pillow is included in this package). Step 2: Create the Flask application Now, let’s write the Flask application. Create a file called app.py and paste the following code inside it:from flask import Flask, render_template, request, redirect, url_for
import qrcode
from io import BytesIO
from flask import send_file
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate_qr():
# Get the data from the form input
qr_data = request.form.get('qr_data')
# Generate the QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(qr_data)
qr.make(fit=True)
# Create an image from the QR Code instance
img = qr.make_image(fill='black', back_color='white')
# Save the QR code to a BytesIO object
img_io = BytesIO()
img.save(img_io, 'PNG')
img_io.seek(0)
# Return the image as a response
return send_file(img_io, mimetype='image/png')
if __name__ == '__main__':
app.run(debug=True)
The '/' route displays the homepage where users can input data for the QR code. The '/generate' route is where the QR code is generated when the form is submitted. It uses the qrcode library to generate the QR code, then returns the image as a PNG file. The qrcode.QRCode class is used to create a QR code object, and we add the data to be encoded using add_data(). We generate the QR code image using make_image(), which we then save to a BytesIO object and send back as an image response. Step 3: Create the HTML template Create a folder named templates in the same directory as your app.py, and inside it, create a file named index.html. This will be the homepage where users can input the data to generate the QR code. Here is the content of index.html:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Generator</title>
</head>
<body>
<h1>QR Code Generator</h1>
<form action="" method="POST">
<label for="qr_data">Enter data for QR code:</label>
<input type="text" id="qr_data" name="qr_data" required>
<button type="submit">Generate QR Code</button>
</form>
</body>
</html>
This simple HTML form sends a POST request to the Flask application with the text input (the data you want to encode in the QR code). Step 4: Run the application Now, go back to your terminal and run the Flask app with this command: python app.py Your Flask application should be running at http://127.0.0.1:5000/. When you visit that URL, you will see a form where you can input some text, and the app will generate a QR code for that text when you submit the form.Congratulations! You have created a Flask application that generates QR codes! The QR code is dynamically generated and sent back as an image in response to a form submission. You want to create your QR code or connect with me, scan the QR code below.
Read moreSend Emails with Python: Customizing Sender Email
Published:
In this blog post, we will explore how to send emails using Python, with a special focus on customizing the “From” header to display a different email address or name, while the actual sender email address remains unchanged. This is useful when you want to send an email from one address but have the From field show a different email or name, creating a more personalized or professional appearance. Prerequisites Before we dive into the code, let’s make sure you have the required tools:
- Python 3.x installed on your system. smtplib and email.mime libraries are included in the Python standard library, so you don’t need to install anything extra.
- Access to an SMTP server. For this example, we’ll use Gmail’s SMTP server, but you can modify the code to work with any SMTP provider.
From Header? You might want to send an email from your address but show a different “From” name or email address for various reasons:- Marketing Emails: You may want the email to appear as if it’s coming from a company or a support team, even though it’s sent from your personal email.
- Multiple Email Aliases: If you use aliases for different purposes (e.g., support@company.com but the email is sent from your_email@example.com), you can display the alias in the header.
- Professional Appearance: Customize the display name to appear more formal or specific to your communication, like “Customer Support” or “John Doe” instead of your actual email.
From Header Step 1: Set Up the Email Message We will use Python’s built-in smtplib to send the email and email.mime to construct the email message. Let us first import the necessary libraries.import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
sender_email = "your_email@example.com" # Email that will send the email
receiver_email = "receiver_email@example.com"
password = "your_email_password" # TIP: security consideration
smtp_server = "smtp.gmail.com"
smtp_port = 587
From field Now let us create the email message and customize it. Here is where you can customize the From field.msg = MIMEMultipart()
msg['From'] = "Custom Name <your_email@example.com>" # The 'From' field will show this name
msg['To'] = receiver_email
msg['Subject'] = "Test Email from Python"
# Email body content
body = "Hello, this is a test email sent from Python!"
# Attach the email body to the message
msg.attach(MIMEText(body, 'plain'))
msg['From'] field, you can change both the name and the email address. By default, the From header will show the email address. If you make it show a different name or alias, the recipient will see “Custom Name” in their inbox, but the email will still be sent from your_email@example.com. Step 3: Log In to the SMTP Server and Send Now that we have set up the email message, let’s log in to the SMTP server and send the email:try:
# Set up the SMTP server connection
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Start TLS encryption for secure email sending
# Log in to the SMTP server with your credentials
server.login(sender_email, password)
# Send the email
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
finally:
# Close the server connection
server.quit()
smtplib.SMTP to connect to the SMTP server. For Gmail, the server is smtp.gmail.com and the port is 587. We also use starttls() to encrypt the connection, ensuring that our credentials and email content are secure. The server.login() function logs into the server using your sender email and password. If you’re using Gmail and have two-factor authentication (2FA) enabled, you’ll need to generate an App Password instead of using your regular Gmail password. This is a security measure to prevent unauthorized access. Follow the instruction on how to create App Password to get one. The try block ensures that any issues during the email sending process are caught, and the exception is displayed if there’s a problem. Security Considerations Never hard-code your email password in your scripts. Consider using environment variables or a credentials manager to securely store your login credentials. If you’re using Gmail, remember to either enable Less Secure Apps or generate an App Password if two-factor authentication is enabled. Conclusion Sending emails programmatically with Python is a powerful feature, especially when you need to customize the header or automate the email sending process, e.g., if you are sending marketing emails, notifications, or personal messages, this approach provides you with the flexibility to display any name or email address in the header, even if the actual sender email is different. Read moreCreating a Virtual Environment in Python
Published:
In the world of Python development, managing dependencies effectively is crucial. One of the best ways to do this is by using virtual environments. Virtual environments allow you to create isolated environments for different projects, ensuring that each project has its own set of dependencies, independent of other projects or system-wide packages. This helps avoid conflicts between different versions of libraries and ensures that your projects remain portable and reproducible. In this article, we will go through the process of creating and using virtual environments in Python, covering both venv (the built-in Python module) and virtualenv (a popular third-party tool). What is a Virtual Environment? A virtual environment is a self-contained directory tree that contains the Python installation for a particular version of Python, as well as additional packages. This isolation prevents the installed libraries in one project from affecting other projects or the system-wide Python installation. Benefits of Using Virtual Environments
- Dependency Management: Each project can have its own dependencies, even if they conflict with dependencies in other projects.
- Clean Development Setup: No more version conflicts or dependency issues across projects.
- Reproducibility: It makes it easier to recreate a project setup from scratch on another system.
- Experimentation: You can safely experiment with different versions of libraries without affecting other projects.
python --version
python3 --version If Python is not installed, you can follow the installation instructions for your operating system from the official Python website. A) Virtual Environment Using `venv` (Built-in Python Module) Step 2: Create a Virtual Environment Using venv Python 3.3+ includes a built-in module called venv that can be used to create a virtual environment. To create virtual environment using venv, you need to navigate to the directory, create the virtual environment and activate it.- Navigate to Your Project Directory
mkdir my_project
cd my_project
- Create the Virtual Environment
python3 -m venv .venv
.venv in your project folder. The .venv directory contains a copy of the Python interpreter, along with the standard Python libraries.- Activate the Virtual Environment
| OS | Code to activate virtual environment |
|---|---|
| Windows | .\env\Scripts\activate |
| macOS | source env/bin/activate |
| Linux | source env/bin/activate |
(env) C:\path\to\my_project>
pip install requests and you can now use requests within your project, but it won’t interfere with any other projects you might be working on. Step 4: Deactivate the Virtual Environment When you’re done working in your virtual environment, you can deactivate it by running the deactivate command as follows:(env) C:\path\to\my_project>deactivate
requirements.txt file. This file lists all the packages currently installed in your environment. This ensures reproduceability and portability of your application. You can generate a requirements.txt file automatically using a handy tool called freeze as follows:pip freeze > requirements.txt
requirements.txt. To install the same packages later (or on a different machine), use:pip install -r requirements.txt
.venv directory. Simply remove it like any other directory:| OS | Code to activate virtual environment |
|---|---|
| Windows | rmdir /S /Q .venv |
| macOS | rm -rf .venv |
| Linux | rm -rf .venv |
venv is built into Python 3, you may want to use virtualenv, a popular third-party tool that provides some additional features, like compatibility with Python 2. Step 1: Install virtualenv If you don’t already have virtualenv installed, you can install it globally using pip:pip install virtualenv
virtualenv .venv
.venv directory. Step 3: Activate and Deactivate the Environment The activation and deactivation steps are the same as with venv. After activation, you can install packages using pip just like before. Conclusion Creating and managing virtual environments is an essential practice for any Python developer. By using venv or virtualenv, you ensure that your projects remain isolated and that dependencies don’t conflict with each other or with the base system. This isolation simplifies the development process, allows for easier dependency management, and enhances reproducibility, making it easier to share your projects with others. Remember to use a requirements.txt file to document your project’s dependencies and make it easy to recreate the environment on another machine. If you’re working on multiple projects, adopting the practice of using virtual environments will help you maintain cleaner, more manageable codebases. Remember to also add .venv into your .gitignore file to exclude the syncronization the virtual environment to your git repository (avoid unnecessary bandwidth usage).Now that you have read the article till the end, did you find this blog post useful? Drop me your comment as a message on LinkedIn Read more
Automating Folder Management in outlook
Published:
Folder management can be daunting, especially when you need to keep folders in multiple systems in sync. I have always been creating folders under subfolder in Inbox folder in outlook. As shown in the example structure below, every time I start working on a project or proposal, I create a folder in initation. As the developement process continues and its status changes, I move the folder to a corresponding folder. For example, if the proposal is in its initial discussion phase, it will have a folder under Initiation; if the proposal development continues, the folder is moved to Preparation and if it is submitted, the folder is moved to Submitted and follow up; if it is rejected, the folder is moved to Rejected; if it is accepted, it does not belong to proposal category any more and the folder is moved to Running projects. I do this in my email folder (then create rules for email routing), in my file system (to organize files) as well as browser bookmark (to organize relevant websites). Doing it manually is a bit tidious and error prone. As a result, I decided to automate the entire workflow. This blog post explains how I automate the creating of folders in my outlook mail box.
user_name@domain.com
Inbox
Projects
1_Proposal
11_Initiation
<project_names>
12_Preparation
13_Submitted and follow up
14_Rejected
2_Running
<project_names>
3_Completed
pywin32 library, which allows Python to interact with the Outlook application through COM (Component Object Model) automation. So, the first step is to install the pywin32 library using pip install pywin32. The code below shows the implementation of creating a subfolder under a given parent folder.import win32com.client
def create_subfolder_under_subfolder(parent_folder_name, subfolder_name):
'''
Description: Function to create a subfolder under an existing subfolder in Inbox.
Inputs: the subfolder you want to create and the parent folder in which you want to create your subfolder
Usage: create_subfolder_under_subfolder(parent_folder_name, subfolder_name)
'''
# Initialize the Outlook application
outlook = win32com.client.Dispatch("Outlook.Application")
# Get the Namespace object (MAPI)
namespace = outlook.GetNamespace("MAPI")
# Get the Inbox folder
inbox = namespace.GetDefaultFolder(6) # 6 is the constant for Inbox
# Find the parent subfolder under Inbox
try:
parent_folder = inbox.Folders[parent_folder_name]
except KeyError:
print(f"Subfolder '{parent_folder_name}' does not exist under Inbox.")
return
# Create the new subfolder under the parent folder
subfolder = parent_folder.Folders.Add(subfolder_name)
print(f"Subfolder '{subfolder_name}' created under '{parent_folder_name}'.")
# Example usage
parent_folder_name = "subfolder_name" # Name of the existing subfolder under Inbox
subfolder_name = "NewSubFolder" # Name of the new subfolder to be created
create_subfolder_under_subfolder(parent_folder_name, subfolder_name)
- The function will initialize Outlook Application with
win32com.client.Dispatch("Outlook.Application"), allowing access to its functionality. - Namespace (MAPI): We access the MAPI interface, which gives us the ability to interact with Outlook data such as emails, folders, etc.
- Get Inbox Folder: The
GetDefaultFolder(6)method retrieves the Inbox folder (6 is the default constant for the Inbox). - Create Subfolder: The
Folders.Add(folder_name)method adds a new folder with the specified name under the Inbox.
- Outlook is installed and running on your system.
- The script will create the folder within the Outlook profile that is currently logged in.
If you have questions or comments, you can reach me via LinkedIn. Read more
Creating Issues for Projects in GitLab
Published:
Creating issues en mass in GitLab (using the web interface) is sometimes tidious or may require unnecessary context switching. This post is to show how you can create bulk of issues using python. The code below is for a single issue but you can easily create list of issues and iterate over them to create multiple issues.
Requirements
1) You need to install python-gitlab library in order to perform more complex logic during issue creation 2) You need to create a project and get its id. 3) You need to have personal access token.pip install python-gitlabSteps
It takes three steps to automate the creation of issues in GitLab projects: Authentication, Project selection and issue creation.i) Authentication
Provide your personal access token and the Gitlab instance url. You can generate a token with the necessary scopes (e.g., API) from your GitLab profile settings.ii) Project Selection
Provide the ID of the project where you want to create the issue. You can find the project ID in the project’s URL (see screenshot below).iii) Creating the Issue
The new issue uses dictionary and defines the title, description, and labels for the new issue. You can customize these fields as needed. Once the dictionary is populated with the necessary information, the project.issues.create(new_issue) method creates the issue and returns an Issue object. The full code for creating a new issue is shown below.Code
# import required library
import gitlab
# GitLab Authenticate
gl = gitlab.Gitlab('https://your_gitlab_instance_url', private_token='your_private_token')
# Project Selection
project = gl.projects.get(project_id='your_project_id')
# New Issue Creation
new_issue = {
'title': 'New Issue Title',
'description': 'This is a new issue description.',
'labels': ['bug', 'frontend']
}
issue = project.issues.create(new_issue)
print(f"New issue created: {issue.title}")
Figure 1: Screenshot showing how to get project id You can extend the above code by incorporating the following:
- Error Handling: Consider adding error handling mechanisms to handle exceptions like authentication failures, API rate limits, or network errors.
- Asynchronous Operations: For large-scale operations, you might want to explore asynchronous programming techniques to improve performance.
- Advanced Features: The gitlab library offers many more features, such as assigning issues to users, setting due dates, and closing issues. Refer to the library’s documentation for detailed usage.
If you have questions or comments, you can reach me via LinkedIn. Read more
portfolio
Portfolio item number 1
Published:
Short description of portfolio item number 1
Read more
Portfolio item number 2
Published:
Short description of portfolio item number 2
Read more
publications
A Data Warehousing System for Knowledge-Based Structural Health Monitoring of Wind Power Plant
Published in IEEE EIT, 2016
SHM for Wind Turbine Read more
Recommended citation: Sisay A. Chala, Fazel Ansari and Madjid Fathi.(2016). A Data Warehousing System for Knowledge-Based Structural Health Monitoring of Wind Power Plant. In: 2016 IEEE International Conference on Electro/Information Technology. May 19-21, 2016, Grand Forks, North Dakota, USA
Towards Implementing Context-aware Dynamic Text Field for Web-based Data Collection
Published in International Journal of Human Factors and Ergonomics, 2016
Data collection for job matching Read more
Recommended citation: Sisay A. Chala, Fazel Ansari, and Madjid Fathi. (2016). Towards Implementing Context-aware Dynamic Text Field for Web-based Data Collection. International Journal of Human Factors and Ergonomics
Automated Use Case Diagram Generation from Textual User Requirement Documents
Published in IEEE, 2017
NLP for Software Engineering Read more
Recommended citation: Sandeep Vimuri, Sisay A. Chala and Madjid Fathi. (2017). Automated Use Case Diagram Generation from Textual User Requirement Documents. The 30th annual IEEE Canadian conference on electrical and computer engineering, Toronto, Canada
Knowledge Extraction from Online Vacancies for Effective Job Matching
Published in IEEE, 2017
Vacancy Analysis Read more
Recommended citation: Sisay A. Chala, Scott Harrisson and Madjid Fathi. (2017). Knowledge Extraction from Online Vacancies for Effective Job Matching. The 30th annual IEEE Canadian conference on electrical and computer engineering, Toronto, Canada
Job seeker to vacancy matching using social network analysis
Published in IEEE IES, 2017
Social network analysis for job matching Read more
Recommended citation: Sisay A. Chala and Madjid Fathi. (2017). Job seeker to vacancy matching using social network analysis. 18th Annual International Conference on Industrial Technology, IEEE Industrial Electronics Society (IES), Toronto, Canada
Semantic matching of job seeker to vacancy: a bidirectional approach
Published in International Journal of Manpower,39(8),1047-1063, Emerald Publishing Limited, 2018
Bi-directional Job Matching Read more
Recommended citation: Chala, Sisay Adugna; Ansari, Fazel; Fathi, Madjid; Tijdens, Kea. (2018) Semantic matching of job seeker to vacancy: a bidirectional approach,International Journal of Manpower,39(8),1047-1063, Emerald Publishing Limited
Bidirectional Job Matching through Unsupervised Feature Learning
Published in University of Siegen, 2018
Dissertation Read more
Recommended citation: Sisay A. Chala. (2018). Bidirectional job matching through unsupervised feature learning. University of Siegen, Germany
Incremental Deep-Learning for Continuous Load Prediction in Energy Management Systems
Published in IEEE PES PowerTech Conference 2019, Milan, Italy, 2019
Incremental Deep-Learning for Continuous Load Prediction in Energy Management Systems Read more
Recommended citation: Gustavo Aragon, Harsh Puri, Alexander Grass, Sisay Chala, and Christian Beecks. (2019). Incremental Deep-Learning for Continuous Load Prediction in Energy Management Systems. IEEE PES PowerTech Conference 2019, Milan, Italy
An Interactive Interface for Bulk Software Deployment in IoT
Published in Association for Computing Machinery (ACM) IoT 2019, 2019
An Interactive Interface for Bulk Software Deployment in IoT Read more
Recommended citation: Farshid Tavakolizadeh, Sisay A. Chala, Hanbing Zhang. (2019). An Interactive Interface for Bulk Software Deployment in IoT. ACM IOT 2019: 38:1-38:4
Download Paper
Human-AI Interaction for Semantic Knowledge Enrichment of AI Model Output
Published in Artificial Intelligence in Manufacturing, 2023
AI Model Building with Human-in-the-loop Read more
Recommended citation: Chala, S. A., & Grass, A. (2023). Human-AI Interaction for Semantic Knowledge Enrichment of AI Model Output. In Artificial Intelligence in Manufacturing: Enabling Intelligent, Flexible and Cost-Effective Production Through AI (pp. 43-54). Cham: Springer Nature Switzerland.
talks
Dynamic textfield for Job seeker data collection
Published:
A conference presentation on utilizing dynamic text field for better data collection in job matching Read more
Social Network Analysis for Effective Job Matching
Published:
A conference presentation about the study on social network analysis for job matching Read more
Multi-Lingual Systems Development
Published:
More information here The talk was about development of multilingual system through machine translation Read more
Scalable Mobile Application Framework for Privacy-aware LBS
Published:
A talk on scalable Mobile Application Framework for Privacy-aware location based services (LBS) to discuss location data analysis for improved mobility behaviour and health Read more
A Knowledge Graph for Query-Induced Analyses of Hierarchically Structured Time Series Information
Published:
A conference presentaiton on combining knowledge graph methods and timeseries data Read more
teaching
Introduction to Artificial Intelligence
Undergraduate course, Haramaya University, Department of Computer Science, 2005
Internet Programming
Undergraduate Course, Haramaya University, Department of Computer Science, 2006
Programming with Java
Undergraduate Course, Haramaya University, Department of Computer Science, 2006
Object-Oriented Programming with C++
Undergraduate Course, Haramaya University, Department of Computer Science, 2007
Networking and System Administration
Undergraduate Course, Haramaya University, Department of Computer Science, 2009
Software Engineering for Mechatronics
Graduate Course for Masters Mechatronics International Program, WS 2014/2015, WS 2015/2016, WS 2016/2017, University of Siegen, 2014
Cloud-Native AI and Machine Learning on AWS Cloud
Professional Course, IBB, 2016
DevOps on AWS Cloud
Professional Course, IBB, 2016
