Sign In
Sign In

Cloud Service Provider
for Developers and Teams

We make it simple to get started in the cloud and scale up as you grow —
whether you have one virtual machine or ten thousand
By signing up you agree to the Terms of Service and Privacy Policy
99.9% Uptime
Our cloud service provides the ultimate in server dependability and stability
Money-back Guarantee
Experience our high-speed cloud services without any risk, assured by our money-back guarantee
Easy to Deploy
Manage your services with ease using our intuitive control panel, where deploying software is a matter of minutes
Reliable and Available
Select from 6 datacenter regions around the world based on latency or deploy across regions for redundancy

Robust cloud services for every demand

See all Products

Cloud Servers

Cutting-edge hardware for cloud solutions: powerful Intel and AMD processors, ultra-fast NVMe disks

Databases

We provide a cloud database ready to store everything you have. The best DBMSs are on deck: MySQL, Redis, Kafka, and more

App Platform

Just link your repo, pick a project to deploy, and Hostman will have it running in the cloud with just a couple of clicks from the dashboard

S3 Storage

A universal object storage compatible with the S3 protocol

Firewall

Multi-layered protection from vulnerability scanning, DDoS, and cyber-attacks

Kubernetes

Automate the management of containerized applications, from deployment and scaling to monitoring and error handling

Managed Backups

Our server and application backup feature allows for both on-demand and scheduled backup and one-click data restoration

Images

Create images for backup free of charge or deploy your own in the Hostman cloud

Hostman's commitment to simplicity
and budget-friendly solutions

1 CPU
2 CPU
4 CPU
8 CPU
Configuration
1 CPU, 1 GB RAM, 25 GB SSD
Hostman
DigitalOcean
Google Cloud
AWS
Vultr
Price
$4
$6
$6.88
$7.59
$5
Tech support
Free
$24/mo
$29/mo + 3% of
monthly charges
$29/mo or 3% of
monthly charges
Free
Backups
from $0.07/GB
20% or 30% higher
base daily/weekly fee
$0.03/GB per mo
$0.05/GB per mo
20% higher base
monthly/hourly fee
Bandwidth
Free
$0.01 per GB
$0.01 per GB
$0.09/GB first
10 TB / mo
$0.01 per GB
Live chat support
Avg. support response time
<15 min
<24 hours
<4 hours
<12 hours
<12 hours
Anup k.
Associate Cloud Engineer
5.0 out of 5

"Hostman Comprehensive Review of Simplicity and Potential"

It been few years that I have been working on Cloud and most of the cloud service...
Mansur H.
Security Researcher
5.0 out of 5

"A perfect fit for everything cloud services!"

Hostman's seemless integration, user-friendly interface and its robust features (backups, etc) makes it much easier...
Adedeji E.
DevOps Engineer
5.0 out of 5

"Superb User Experience"

For me, Hostman is exceptional because of it's flexibility and user-friendliness. The platform's ability to offer dedicated computing resources acr...
Yudhistira H.
Mid-Market(51-1000 emp.)
5.0 out of 5

"Streamlined Cloud Excellence!"

What I like best about Hostman is their exceptional speed of deployment, scalability, and robust security features. Their...
Mohammad Waqas S.
Biotechnologist and programmer
5.0 out of 5

"Seamless and easy to use Hosting Solution for Web Applications"

From the moment I signed up, the process has been seamless and straightforward...
Mohana R.
Senior Software Engineer
5.0 out of 5

"Availing Different DB Engine Services Provided by Hostman is Convenient for my Organization usecases"

Hostman manages the cloud operations...
Faizan A.
5.0 out of 5

"Hostman is a great fit for me"

Hostman is a great fit for me. What do you like best about Hostman? It was very easy to deploy my application and create database, I didn't have
Adam M.
5.0 out of 5

"Perfect website"

This website is extremely user friendly and easy to use. I had no problems so didn't have to contact customer support. Really good website and would recommend to others.
Anup K.
4.0 out of 5

"Simplifying Cloud Deployment with Strengths and Areas for Growth"

What I like best about Hostman is its unwavering commitment to simplicity...
Naila J.
5.0 out of 5

"Streamlined Deployment with Room for Improvement"

Hostman impresses with its user-friendly interface and seamless deployment process, simplifying web application hosting...

Trusted by 500+ companies and developers worldwide

Deploy a cloud server
in just a few clicks

Set up your сloud servers at Hostman swiftly and without any fees, customizing them for your business with a quick selection of region, IP range, and details—ensuring seamless integration and data flow

Code locally, launch worldwide

Our servers, certified with ISO/IEC 27001, are located in Tier 3 data
centers across the US, Europe, and Asia
🇺🇸 San Francisco
🇺🇸 San Jose
🇺🇸 Texas
🇺🇸 New York
🇳🇱 Amsterdam
🇳🇬 Lagos
🇩🇪 Frankfurt
🇵🇱 Gdansk
🇦🇪 Dubai
🇸🇬 Singapore

Latest News

Python

Break, Continue, and Pass Statements in Python Loops

When working with while and for loops, there are times when you need to forcefully exit the loop, skip part of the code, or ignore specific conditions. Python uses the break, continue, and pass statements to handle these cases. Let’s explore how these statements work through examples. Break Statement The break statement in Python is used to exit a block of code prematurely. Here’s a simple example: for j in 'applefishorange': if j == 'f': break print(j) This will produce the following output: a p p l e As soon as the program encounters the letter f in the sequence, the loop breaks in Python because of the break statement. Now let’s see how it works in a while loop: x = 0 while x < 5: print(x) x += 0.5 print('Exit') The output will look like this (truncated for brevity): 0 0.5 … 4.0 4.5 Exit Once the condition is no longer met (when x becomes equal to 5), the Python program exits the loop. Now, let’s rewrite the code using the break statement: x = 0 while True: print(x) if x >= 4.5: break x += 0.5 print('Exit') The result is the same: 0 0.5 … 4.0 4.5 Exit We assigned the value 0 to x and set the condition: as long as x is True, continue printing it. The code is slightly longer, but using break is justified in situations with complex conditions or to safeguard against infinite loops. Remove two lines from the code above: x = 0 while True: print(x) x += 0.5 print('Exit') And you'll get an endless output: 0 0.5 … 100 100.5 … 1000000 1000000.5 … And the word Exit will never be printed because the loop will never end. Therefore, using break when working with number sequences helps prevent your program from getting stuck in an infinite loop. Using Break with Else Sometimes, you need to check if the loop completed successfully or was interrupted by a break statement in Python. For this, you can use the else clause. Let’s write a program that checks a word for forbidden characters: word = input('Enter a word: ') for i in word: if i == 'z': print('Loop was interrupted, the letter "z" was found') break else: print('Loop completed successfully, no forbidden letters found') print('Check completed') If the user enters "Hello!", the output will be: Loop completed successfully, no forbidden letters found Check completed But if the input contains the letter "z", the output will be: Loop was interrupted, the letter "z" was found Check completed Explanation: The input function accepts user input (the prompt "Enter a word:" is for the user; the program would work fine with word = input() alone) and assigns it to the variable word. The for loop then iterates over each element (in this case, each letter) and checks it with the condition in the if statement. Continue Statement While break interrupts the loop, the continue statement in Python is more flexible — it skips certain elements in the sequence without ending the loop. Let’s write a program that "doesn’t like" the letter "z": word = input('Enter a word: ') for i in word: if i == 'z': continue print(i) If you enter "zebra", the output will be: e b r a This happens because we set the condition where any element with the value "z" is not printed. But the Python continue statement allows the loop to finish, printing all "allowed" elements. However, there is a small issue with the code: if the user enters "Zebra" (with an uppercase Z), the program will print the entire word because we didn’t account for the letter case: Z e b r a The most obvious solution here is to add the uppercase letter in the if block like this: word = input('Enter a word: ') for i in word: if i == 'z' or i == 'Z': continue print(i) Pass Statement The pass statement in Python allows the loop to continue regardless of any conditions. It is rarely seen in final code but is useful during development as a placeholder for code that hasn’t been written yet. For example, let’s say you need to remember to add a condition for the letter "z", but you haven't written that block yet. Here, the pass placeholder keeps the program running smoothly: word = input('Enter a word: ') for i in word: if i == 'z': pass else: print('Loop completed, no forbidden letters found') print('Check completed') Now the program will run, and pass will act as a marker to remind you to add the condition later. That’s all! We hope that break, continue, and pass in Python will soon become your reliable tools for developing interesting applications. Good luck!
11 October 2024 · 4 min to read
Python

How to Reverse a String in Python

One of the top reasons for the popularity of Python is the extensive built-in capabilities it has. It offers a lot of modules and functions that enable developers to achieve specific tasks with simplicity. A very common example of these tasks is string manipulation. String manipulation is the process in which we modify a string variable by applying some type of operation like concatenation, splitting, or reordering of the characters. This manipulation can be very handy in cases like text processing, data analysis, or problem solving. In this article we’re going to cover one fundamental string manipulation operation, which is string reversal. We’ll explore different methods to reverse a string in Python and we’ll show an example for each one. We’ll also compare the efficiency between these different methods. Reverse a String Using Slicing Slicing is the process of extracting part of a sequence object (string, list, tuple, etc). We can specify the range of elements – from the start to the end – which we want to extract from the sequence. This range of elements, also called a slice, is then returned from the slicing operation and we can store it in another variable. We can apply the slicing in Python in two different ways, using the slice() function, or with the slicing [::] operator. The slice() Function A slice() function takes three arguments which are the starting element, ending element, and a step. It returns a slice object which we can later use on our sequence to extract a part of it. For example, we can slice a string with the following code: my_string="ABCDEF" my_slice=slice(2,5,1) new_string=my_string[my_slice] print(new_string) In the above code, we have the original string which is my_string. We use the slice() function with parameters 2, 5, and 1. This means that we need to extract part of the string starting from index 2 until index 5, and moving 1 element at a time.  Now let’s run this code and check the output: As we can see, our new_string contains the sliced part which is CDE. It’s important to note that the slice begins with the starting index until the element before the ending index, but it doesn’t include the ending index itself. We can also pick the slice in the opposite direction by using a negative value for the step. Meaning that we’ll start from the bigger index until the smaller one. We can achieve this with the following code: my_string="ABCDEF" my_slice=slice(5,2,-1) new_string=my_string[my_slice] print(new_string) If we run our code we should get the slice in a reversed order: In the above image the new_string contains the elements starting from index 5 until index 2 in a reversed order. Now in order to reverse the whole string, we can use the slice() function with a reverse order starting from the last index until the first index: my_string="ABCDEF" my_slice=slice(5,None,-1) new_string=my_string[my_slice] print(new_string) In the above code, we start our slice from index 5 which is the final index in my_string, until the index None, which means the starting index including the element stored in it. We should get a reversed string by running the above code: The new_string now is the reversal of the original my_string. The slicing[::] Operator The slicing [::] operator works the same as the slice() function but provides a shorter and easier syntax. Instead of creating a slice object and pass it to the original string, we can merge these in a single step with the slicing operator: my_string="ABCDEF" new_string=my_string[5:None:-1] print(new_string) In the above example, we removed the slice() function and used the slicing operator directly on the string. We use the same parameters for the starting index, ending index, and the step: We can see our string is reversed in the same way as the slice() function. We can also improve the syntax further by replacing the starting and ending index with empty value as follows: my_string="ABCDEF" new_string=my_string[::-1] print(new_string) This automatically translates to the beginning and the end of the string: Again we get our string in a reversed order with a more elegant syntax. Reverse a String Using the reversed() Function The reversed() function is a Python built-in function that accepts an iterable as a parameter and returns an iterator in a reversed order. We can then iterate over the returned object and access its elements as we need. For example, the following code will print the elements of the returned iterator after reversing a string: iterable_string="ABCDEF" my_iterator=reversed(iterable_string) for element in my_iterator: print(element) Now let’s run our code: In the above image, we have each element in our string in a reversed order. We can utilize the reversed() function to reverse a string by using it along with the join() function. The join() function is also a Python built-in function that takes an iterable object as a parameter, it concatenates the elements of this iterable and returns a string object as a result of concatenation. Because every iterator is also an iterable, we can pass the iterator returned from the reversed() function as a parameter to the join() function: iterable_string="ABCDEF" my_iterator=reversed(iterable_string) concat_string=''.join(my_iterator) print(concat_string) In the above code, we concatenate the elements of the my_iterator (which is basically the reverse of the iterable_string) using the join() function, and we save the returned string in the concat_string. The empty string ' ' in the join() function decides the separator we want to include between our concatenated elements. Since we don’t need to separate the elements by any character we provided an empty string. Let’s check the output of our code: As we can see, the join() function converted our reversed iterator object into a string. Reverse a String Using a Loop If we want to reverse a string using the basic programming structures without utilizing a built-in function, we can achieve this with traditional Python for loop. We can use the for loop to iterate over our string in the opposite direction from the last index to the first index. Through the iteration, we can pick the element at each index and concatenate it to another empty string: my_string="ABCDEF" reversed_string='' for i in range(len(my_string)-1, -1, -1): reversed_string+=my_string[i] print(reversed_string) The len() function here is used to return the number of characters in my_string, by subtracting 1 from this number we get the last index in the string. So, the expression len(my_string)-1 will be evaluated to 5. The range() function will then return a sequence of numbers starting at 5, and decremented by 1 until it reaches 0, which is specified by the -1 and -1 parameters. At each iteration, the character at the specified index will be appended to the reversed_string. Let’s run this code and check the result: We can see the reversed_string was created by concatenating the characters from my_string in the opposite direction. Reverse a String Using Recursion Recursion is the process where a function calls itself. This can be beneficial if we want to repeat the same operation multiple times until we reach a specific condition, called a base case. To reverse a string, we can create a recursive function that takes the string as a parameter and returns a call to the same function with a substring parameter removing the first character and appending it to the end. This process continues until the substring passed to the function has a length of 1. We can implement this using the following code: def reverse_string(my_string): if len(my_string) <= 1: return my_string return reverse_string(my_string[1:]) + my_string[0] ordered_string="ABCDEF" reversed_string=reverse_string(ordered_string) print(reversed_string) Now let’s run our code: And we get our reversed string after recursively calling the function which removes the first element and appends it to the end of the string. Reverse a String Using List Comprehension List comprehension provides an easy syntax to create a new list out of an existing list. We can utilize this to reverse a string in two steps, first we’ll create a new reversed list using the list comprehension, then we’ll concatenate the elements of this reversed list using the join() function: my_string="ABCDEF" reversed_list=[my_string[i] for i in range(len(my_string)-1, -1, -1)] reversed_string=''.join(reversed_list) print(reversed_string) In the above code, we’re again using the range(len(my_string)-1, -1, -1) expression as in the for loop scenario to iterate over our string in a reversed direction. However, this time instead of appending the element in the index directly to a new string, we’re creating a new list out of the elements. Once we get our reversed list, we pass it to the join() function to return a string from the concatenated elements of the list. Let’s run our code: We can see our string is reversed by creating a new reversed list and concatenating its elements. Comparing the Efficiency of Each Method Besides the difference in simplicity for each method, we also need to consider their performance in terms of the execution time. We can measure the execution time for each method by using the time() function. The time() function is part of the time module and it returns the current time in seconds. We can simply add the time() function at the beginning and at the end of the code that we want to measure, then we subtract both values. Let’s apply this to some of the previous methods and compare the results: Here we compared the slicing method with the list comprehension method, and we can see that the slicing method is more efficient by taking less execution time. Conclusion Python offers great control for programmers when it comes to string manipulation. It provides built-in modules and functions that support a wide range of use cases from text processing to data analysis. In this article, we covered a common string manipulation task which is string reversal. We explored some of the methods for reversing a string in Python including slicing, recursion, for loops, and list comprehension.
10 October 2024 · 8 min to read
C

How To Implement a Stack in C Programming

In computer science, a stack is an abstract data structure that follows the Last In, First Out (LIFO) principle. It is widely used in algorithm design and programming for tasks like evaluating expressions, managing function calls, and performing undo operations. This tutorial will guide users through implementing a stack in C using arrays, providing clear examples of common stack operations such as push, pop, and peek. By the end of this tutorial, users will understand how to efficiently manage stacks in C and apply this data structure in real-world scenarios. What is a Stack in Programming? A stack in programming is a collection of elements with two main operations: Push: Adds an element to the top of the stack. Pop: Removes the element from the top of the stack. Other useful operations include: Peek: Retrieves the top element without removing it. isFull: Checks if the stack is full (in cases of fixed-size stacks). isEmpty: Checks if the stack is empty. In this tutorial, a C implementation of the stack will be created using an array, covering the push, pop, and peek operations. Stack Data Structure Overview A stack follows a simple concept: Think of a stack like a stack of plates. You can only add (push) a plate at the top or remove (pop) the plate at the top.  The stack operates under the LIFO principle, meaning the last item added is the first one to be removed. In C, stacks can be implemented using arrays or linked lists. This tutorial will focus on using an array-based implementation. Why Use Stacks? Stacks are used in various real-world applications, including: Function call management (recursive function calls are placed on the call stack). Expression evaluation (infix, postfix, and prefix expressions). Backtracking algorithms (for example, the depth-first search algorithm). Stack Operations Push: Adds an element to the stack. Pop: Removes the topmost element. Peek: Looks at the topmost element without removing it. isFull: Checks if the stack has reached its maximum capacity. isEmpty: Checks if the stack is empty. These operations will be explained and implemented step-by-step in the sections below. Implementing a Stack Using Arrays To implement stack operations effectively, it's important to start by setting up the underlying data structure. This will ensure that the stack can handle various operations like pushing and popping elements. Defining the Stack Structure In C, a stack can be represented using an array with fixed capacity. To manage the stack, you'll need to keep track of the current top element and define the size of the stack. #include <stdio.h> #include <stdlib.h> #define MAX 5 // Stack structure definition struct Stack { int items[MAX]; // Array to store stack elements int top; // To track the top element }; // Function to initialize the stack void initStack(struct Stack* s) { s->top = -1; // Set top to -1, meaning the stack is initially empty } Implementing the Push Operation The push operation adds a new element to the top of the stack, provided the stack isn't full. // Function to push an element to the stack void push(struct Stack* s, int value) { if (s->top == MAX - 1) { printf("Stack is full. Cannot push %d\n", value); } else { s->top++; s->items[s->top] = value; printf("Pushed %d to stack\n", value); } } Implementing the Pop Operation The pop operation removes and returns the topmost element of the stack. If the stack is empty, the pop operation should notify the user. // Function to pop an element from the stack int pop(struct Stack* s) { if (s->top == -1) { printf("Stack is empty. Cannot pop.\n"); return -1; // Return -1 as an indicator of error } else { int poppedValue = s->items[s->top]; s->top--; printf("Popped %d from stack\n", poppedValue); return poppedValue; } } Implementing the Peek Operation The peek operation returns the top element without removing it. It’s useful when you want to view the topmost element without modifying the stack. // Function to peek at the top element of the stack int peek(struct Stack* s) { if (s->top == -1) { printf("Stack is empty. No top element.\n"); return -1; } else { printf("Top element is %d\n", s->items[s->top]); return s->items[s->top]; } } Checking if the Stack is Full or Empty For completeness, two utility functions, isFull and isEmpty, are often implemented to check the stack’s state. // Function to check if the stack is full int isFull(struct Stack* s) { return s->top == MAX - 1; } // Function to check if the stack is empty int isEmpty(struct Stack* s) { return s->top == -1; } Example Code for Stack Implementation Below is a complete example that demonstrates how to use the stack operations. #include <stdio.h> #include <stdlib.h> #define MAX 5 // Stack structure definition struct Stack { int items[MAX]; int top; }; // Function declarations void initStack(struct Stack* s); void push(struct Stack* s, int value); int pop(struct Stack* s); int peek(struct Stack* s); int isFull(struct Stack* s); int isEmpty(struct Stack* s); int main() { struct Stack myStack; initStack(&myStack); push(&myStack, 10); push(&myStack, 20); push(&myStack, 30); peek(&myStack); pop(&myStack); peek(&myStack); return 0; } // Function definitions void initStack(struct Stack* s) { s->top = -1; } void push(struct Stack* s, int value) { if (isFull(s)) { printf("Stack is full. Cannot push %d\n", value); } else { s->top++; s->items[s->top] = value; printf("Pushed %d to stack\n", value); } } int pop(struct Stack* s) { if (isEmpty(s)) { printf("Stack is empty. Cannot pop.\n"); return -1; } else { int poppedValue = s->items[s->top]; s->top--; printf("Popped %d from stack\n", poppedValue); return poppedValue; } } int peek(struct Stack* s) { if (isEmpty(s)) { printf("Stack is empty. No top element.\n"); return -1; } else { printf("Top element is %d\n", s->items[s->top]); return s->items[s->top]; } } int isFull(struct Stack* s) { return s->top == MAX - 1; } int isEmpty(struct Stack* s) { return s->top == -1; } Common Stack Use Cases Stacks are employed in various areas in computer programming: Function Call Management: The call stack tracks function calls and returns. Expression Evaluation: Stacks are used in parsing algorithms like converting infix to postfix expressions. Undo Operations: In many applications, such as text editors, stacks manage the undo functionality. Backtracking Algorithms: Stacks are used in depth-first search (DFS) algorithms and puzzle-solving. Conclusion In this tutorial, the stack data structure was introduced, along with a step-by-step guide to implementing a stack in C. The tutorial covered how to define a stack using arrays, perform basic operations such as push, pop, and peek, and use utility functions to check if the stack is full or empty. Stacks are essential tools in programming, and mastering their use can significantly enhance one’s ability to write efficient and maintainable code.
10 October 2024 · 6 min to read
Linux

How to Mount File Systems in Linux

File system mounting is a fundamental operation in Linux, allowing users to access and manage different file systems from various storage devices. Whether connecting a hard drive, USB drive, or network share, mounting is necessary to make these resources available to your system.  This tutorial will guide you through the process of mounting file systems in Linux, including mounting manually with the mount command, automating mounts using /etc/fstab, and troubleshooting common issues. Common File Systems in Linux Linux supports a variety of file systems, each suited for different needs. Some of the most commonly used file systems include: ext4: The default file system for many Linux distributions. NTFS: Typically used for Windows systems. FAT32/exFAT: Used for USB drives and other portable storage. XFS: Ideal for large data storage solutions. Understanding the type of file system is crucial when mounting storage devices, as the necessary options and commands may differ. Mounting a File System with the mount Command The mount command is used to manually mount file systems in Linux. The basic syntax is as follows: sudo mount [OPTIONS] <source> <mount_point> <source>: The device or file system to be mounted, such as /dev/vdc1. <mount_point>: The directory where the file system will be mounted, such as /mnt. On Hostman servers, disk names follow the format vd*, where * is replaced by a letter from a to z. The letter corresponds to the disk’s number in the system. The primary disk always contains the operating system and is named vda. The second disk, vdb, is reserved for cloud-init. So, in this guide, we will focus on working with the vdc disk.  If you are using this guide for virtual machines from another provider, make sure to verify the correct disk names beforehand. Identify the File System First, you need to identify the available disks and partitions. You can use the following command to list them: lsblk This command displays the block devices along with their mount points, helping you identify the target device. Create a Partition If you need to create a new partition, you can do so using fdisk. Replace /dev/vdc with your target disk: sudo fdisk /dev/vdc Follow the prompts to create a new partition (for instance, /dev/vdc1). You will typically use the following commands within the fdisk utility: n: to create a new partition p: to select primary Specify the partition number and size as required w: to write changes to the disk Create a File System Once the partition is created, format it with a file system. Here’s how to create an ext4 file system on the newly created partition: sudo mkfs.ext4 /dev/vdc1 Mount the File System To mount the file system, use the following command, specifying the mount options: sudo mount -o barrier=0 /dev/vdc1 /mnt/mydrive/ Verify the Mount Finally, check if the file system has been mounted successfully by using the df command: df -h This command displays all mounted file systems and their disk usage, allowing you to confirm that your new file system is correctly mounted. Unmounting a File System To unmount a file system, use the umount command followed by the mount point or device name: sudo umount /mnt/mydrive Automating Mounts with /etc/fstab Mounting file systems manually every time you boot can be tedious. Fortunately, Linux provides a way to automate the process through the /etc/fstab file. The /etc/fstab file contains information about disks and partitions that should be automatically mounted at boot. 1. Open the /etc/fstab File: Use a text editor to open the /etc/fstab file: sudo nano /etc/fstab 2. Add a New Entry: Add an entry to the file in the following format: <device> <mount_point> <file_system_type> <options> <dump> <pass>     Example: echo “/dev/vdc1 /mnt/mydrive ext4 barrier=0 0 0 1” >> /etc/fstab <device>: The partition, for example, /dev/vdc1. <mount_point>: The directory where the file system will be mounted. <file_system_type>: The type of file system, for example, ext4. <options>: Mount options, for example, defaults. <dump>: Used for backups, typically set to 0. <pass>: The file system check order during boot. 3. Test the New Entry: After saving the file, test the changes by using the mount command to mount all file systems in /etc/fstab: sudo mount -a Example /etc/fstab Entry: /dev/vdc1 /mnt/mydrive ext4 defaults 0 2 This entry mounts the ext4 partition /dev/vdc1 to /mnt/mydrive at boot. Checking Mounted File Systems To view all currently mounted file systems, use the following commands: df: This command provides information about disk usage and mounted file systems: df -h mount: Displays a list of all mounted file systems: mount | grep "^/dev" Both commands can be useful for verifying whether a file system is properly mounted and accessible. Troubleshooting File System Mounting Issues Mounting issues can arise due to various factors, such as incorrect device paths, unsupported file systems, or permission problems. Here are some common issues and troubleshooting tips: mount: wrong fs type, bad option, bad superblock This error can occur if the wrong file system type is specified. Verify the correct file system type with lsblk -f and try mounting again: sudo mount -t ext4 /dev/vdc1 /mnt/mydrive Permission Denied Ensure you have the necessary permissions to mount the device. Use sudo to gain administrative privileges: sudo mount /dev/vdc1 /mnt/mydrive Device Not Found If the device cannot be found, verify its path using lsblk or fdisk -l. The device name may change based on how the storage is connected. Automated Mounting Fails If file systems fail to mount automatically at boot, verify the /etc/fstab entry for syntax errors. Run the following to test the /etc/fstab file: sudo mount -a If the issue persists, review system logs using dmesg for more detailed error messages. Conclusion Mounting file systems in Linux is an essential task for accessing storage devices. By mastering the mount command, automating mounts with /etc/fstab, and troubleshooting common issues, users can efficiently manage their file systems. This tutorial covered all the necessary steps for mounting a file system, from basic commands to troubleshooting errors. 
08 October 2024 · 5 min to read
CSS

How to Change a CSS Background Image’s Opacity

In web design, achieving the desired visual effect often involves manipulating CSS properties. One common requirement is adjusting the opacity of a background image. Whether you’re a seasoned developer or just starting your design journey, mastering background opacity will empower you to craft stunning visuals that not only look great but also resonate with your audience. This article provides a comprehensive guide on how to achieve this, including various methods and best practices. Introduction to CSS Backgrounds CSS backgrounds are fundamental for creating visually appealing web pages. They can enhance the aesthetics of a website by adding images, colors, and patterns.  Key Components Background Color: You can pick any color to fill the background of an element (like a box or a whole page). For example, if you want a bright blue background, you’d use: background-color: blue; Background Image: Instead of just a plain color, you can use a picture as your background. This is like putting up a poster or a mural. You specify the image you want to use: background-image: url('your-image.jpg'); Background Size: This controls how the background image fits. You can make it cover the entire space or repeat like a pattern. For example: background-size: cover; /* Makes the image fill the entire space */ Background Position: This determines where the background image sits. You can center it, move it to the top, or place it wherever you like: background-position: center; Background Opacity: This controls how transparent or solid your background is. It’s like adjusting the brightness of a lamp. We’ll talk more on this in the next section. Understanding CSS Opacity Opacity is a CSS property that controls the transparency of an element. It can take a value between 0 (completely transparent) and 1 (completely opaque). When applied, this property affects both the element and its contents. Opacity refers to the transparency level of an element. It is defined using a value between 0 and 1: 0 means fully transparent (invisible). 1 means fully opaque (completely solid). Values between 0 and 1 create varying degrees of transparency. For example: .canvas { opacity: 0.2; /* 20% transparent */ } This can be useful for layering elements or softening backgrounds without completely obscuring them. Applying Opacity to an Entire Element The simplest way to change the opacity of a background image is by applying the opacity property directly to the element containing the background.  Be warned! It’s a naive approach. It’s quite limiting. Here’s how: <div class="container"> <h1>Mastering CSS Opacity</h1> <p>This text will also have reduced opacity.</p> </div> <style> .container { background-image: url('https://images.unsplash.com/photo-1470252649378-9c29740c9fa8?q=80&w=1470&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'); /* Set the background size and position */ background-size: cover; background-position: center; /* Set the opacity of the entire element, including the background image */ opacity: 0.6; /* Set the padding to create some space around the text */ padding: 20px; width: 500px; height: 300px; } .container h1 { color: white; font-size: 36px; } .container p { color: white; font-size: 18px; } </style> This method will set the opacity for the entire element, including any text or content within it. This can be problematic if you want text to remain fully opaque. Use an img element This method allows you to achieve a layered effect while maintaining control over the image transparency. In this example, we will include a separate <img> tag inside a container. <div class="image-container"> <img src="https://images.unsplash.com/photo-1554322662-f8dc2222f79f?q=80&w=1574&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="Descriptive Text" class="background-image"> <div class="content"> <h1>Make Waves and Ride the Tide</h1> <p>Escape to the Endless Horizon.</p> </div> </div> <style> .image-container { position: relative; width: 100%; height: 400px; /* Adjust height as needed */ overflow: hidden; /* Ensures no overflow */ } .background-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; /* Ensures the image covers the entire container */ opacity: 0.7; /* Adjust the opacity here */ } .content { position: relative; /* Keeps content above the image */ z-index: 1; /* Ensures this content is on top */ color: blue; text-align: center; padding: 20px; } </style> As you can see, the image opacity is 70% but the text is fully opaque. Interestingly, this approach overcomes the limitation of first method. Set Background Opacity with Pseudo-elements CSS pseudo-elements enable you to insert content before or after an element's actual content, providing a way to enhance your design with additional visual elements or text.  How It Works Layering Backgrounds: By using ::before or ::after, you can create an additional layer behind your main content. This layer can be styled with a background color or image and adjusted for opacity, providing a visually appealing backdrop. Content Insertion: The content property allows you to insert text or other elements dynamically, enhancing the design while ensuring that the main content remains unaffected. <div class="hero"> <h1>How to adjust css background image opacity</h1> </div> <style> .hero { position: relative; /* Establishes a positioning context */ text-align: center; color: black; Height: 50vh; } .hero::before { content: ""; /* Required for pseudo-elements */ position: absolute; /* Positions the background layer */ top: 0; left: 0; right: 0; bottom: 0; background-image: url('https://images.unsplash.com/photo-1705668403533-3c17914a497a?q=80&w=1506&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'); background-size: cover; /* Ensure the image covers the area */ opacity: 0.5; /* Adjusts the opacity of background css */ z-index: 0; /* Places it behind the content */ } .hero h1 { position: relative; z-index: 1; /* Text appears on top */ padding: 20px; } </style> That’s the benefit you can get using pseudo-elements. You can achieve complex designs without adding extra divs or elements to your HTML, keeping your markup minimal and organized. Explanation Positioning: The .hero class is set to relative, which creates a positioning context for the pseudo-element. The ::before pseudo-element is absolutely positioned to cover the entire .hero container. Background Layer: The ::before pseudo-element contains a background image with adjusted opacity. This creates a semi-transparent effect, allowing the background image to be visible but softened. Text Visibility: The heading (h1) is given a higher z-index to ensure it appears above the semi-transparent background, making it easy to read. Best Practices When working with CSS background opacity, keep the following best practices in  mind: Utilize ::before and ::after pseudo-elements. Avoid using opacity on elements with text or other content, as it can affect readability. If you’re working with solid colors, consider using RGBA (Red, Green, Blue, Alpha) values for transparency. This allows for fine-tuned control over color and opacity without affecting other properties. background-color: rgba(255, 0, 0, 0.5); /* Red with 50% opacity */ Use viewport units (like vh or vw) to make backgrounds responsive. This ensures that backgrounds scale appropriately on different screen sizes. Test your design in different browsers and devices to ensure com Final Thoughts Incorporating CSS background opacity effectively can transform your design, making it not only visually appealing but also functional. By leveraging transparency, you can create a polished and professional look that enhances user experience and engagement.
07 October 2024 · 7 min to read
Python

Understanding HTTP Requests: Structure, Methods & Examples

HTTP is a key to communication on the internet. Methods of HTTP protocols allow clients to send requests to the servers and servers to send responses. Every website on the World Wide Web uses HTTP requests. So, it's necessary to understand them. This article explores the concept of HTTP requests, its structure, common methods, and real-life examples. This helps in understanding the functioning of the web.  What is an HTTP Request An HTTP request is a message where a client, such as a web browser, asks the host located on the server for a specific resource. Clients use URLs in HTTP requests which show the resources they want to access from the server.  Components of an HTTP Request Every HTTP request comprises three components namely; request line, headers and message body. Request Line  A request line is the start line in an HTTP request command. It is used to initialize an action on the server. A request line would also indicate what kind of method and version of HTTP protocol the client is using. Apart from the HTTP method, a request line also consists of a URI or URL to the path or protocol.  Request line example: GET /index.html HTTP/1.1 Headers Headers are right behind the request line. They offer client’s additional information to the server. Headers include data about the host, client’s user agent, language preferences and more. Server leverages this information to identify the browser and OS version of the client. HTTP request headers are case-sensitive, followed by a colon (:) and a value.  HTTP request Headers example:  Host: example.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Accept: application/json, text/plain, */* Accept-Language: en-US,en;q=0.9 Accept-Encoding: gzip, deflate, br Connection: keep-alive Message body The message body in an HTTP request is used to send data to the server. They are optional. So, not every HTTP request will have a message body. It depends on the HTTP request types the client uses. The HTTP requests that do have a message body, usually leverage POST to send information. Mainly, the server uses the message body to provide the requested data to the client.  Common HTTP Methods An HTTP request is a way to connect the client with the server. There can be many reasons for pursuing this connection. It might be to retrieve specific resources or delete certain information on the server. The most common HTTP request methods used daily include:  GET: To Retrieve Resources The biggest use case of an HTTP request is to ask the server for a specific set of data or resources. And that is done using the GET method. Every time a user wants to go to a website or any web page, the client browser first sends a request to retrieve the required data to load that page.  The GET in HTTP is a cacheable, safe, and idempotent method. However,, using a GET method multiple times can still impact server performance. The GET Method can only bring existing data from the server to the client. It can’t make any changes to it. So, the data or the resources would be in a read-only format.  POST: To Send Data When a client wants to retrieve any information, they use the GET method, but when providing some information to the server, the client uses the HTTP POST request. Let’s say users need to submit a form or upload a file. In this case, the client’s browser has to execute the POST method in HTTP to send the data to the server.  The message body in an HTTP request contains the data. When a client browser sends a POST request, the server processes the data. Using a POST method multiple times would result in the creation of different resources on the server.  PUT: To Update Resources Similar to the POST method, the PUT method also allows the client to add some information to the server. The only difference between both methods is that in POST, users submit new data whereas in PUT, they update the existing data.  When implementing the PUT request, the client has to specify the resource’s URL that it wants to update. The request also includes the updated representation of the resource in its message body. The server would simply replace the old representation with the new one.  The PUT method is idempotent so there is no harm in implementing multiple identical PUT requests as it would yield the same result.  DELETE: To Remove Resources As the name suggests, the DELETE method helps the client delete any specific resource from the server. Employing the DELETE request helps the client instruct the server to delete the resource mentioned in the request.  Upon the DELETE request of the client, when the server successfully deletes the specified resource, it sends back a confirmation to the client. Sending multiple identical DELETE requests would yield the same result.  What is an HTTP Response? When the server sends back a response to an HTTP request, it is called an HTTP response. The server acts upon the request it receives from the client browser. The HTTP response would then either consist of the requested resource or valuable information regarding the requested operation.  So, like an HTTP request, an HTTP response is also made up of three components with a slight difference. The response starts with a status line, and a request starts with a request line.  Status Line: As the request line does in an HTTP request, the status line in the HTTP response also indicates which version of HTTP is used along with the status code and the message specifying the outcome of the request.  Headers: Headers in the HTTP response offer additional information like the date and time of response, the type of content that is sent in the message body, details of the server and instructions on how to cache the content.  Body: The actual message or response data that the server sends to the client browser is placed in the message body. The content could be anything from XML, JSON or HTML for the web page, an image, or any other kind of requested resource. Status Codes and Their Meanings HTTP status codes represent the status of the client’s HTTP requests. They come as a part of an HTTP server response. Every status code consists of three digital numbers where the first digit of the code indicates the class or category of the response. There are five types of code groups. Status code group  Description  1xx Informational responses, continuing processing. 2xx Success responses, requests are processed, understood and accepted. 3xx Redirecting responses, suggests further action to complete the request. 4xx Error responses, show what’s wrong with the request on client-side. 5xx Error responses, state what went wrong with processing request on server-side. HTTP Headers and Their Importance HTTP headers provide additional information about requests and responses. This information is critical for communication between client and server. Headers are fundamental for web browsing and app functionality. They play an important role in the following web operations:  Host Identification Headers bear the identification of a server’s domain that is hosting the resources. It is helpful in scenarios where a server hosts multiple domains.  CachingHeaders like Expires and Cache-Control handle how browsers cache responses and intermediate proxies. It helps minimize loading time and server requests by determining how long a response needs to be stored.  Cookie ManagementHeaders like Set-Cookie and Cookie help save and send cookies respectively. They assist in tracking user behavior and maintain user sessions.  Security Headers also play a critical role in securing web applications. An Authorization header helps with user authentication whereas a Content-Security-Policy is used for mitigating XSS and other security risks.  Response ControlHeaders like Status inform whether the request was a success or a failure. It also provides the necessary details so the client can manage responses appropriately.  Practical Examples of HTTP Requests Here are a few real-life examples of how different HTTP requests are commonly used in day-to-day operations. All the examples are in Python with the use of the requests library. GET From entering a simple URL for the website to asking for a specific record from the web server, fetching data requires an HTTP GET request. Let’s say, the client wants to get the weather data of London. The implementation of GET requests in this use case would look like:  import requests response = requests.get("https://api.example.com/data", params={"param1": "value1", "param2": "value2"}) # Print the response print(response.status_code) print(response.json()) # Assuming the response is in JSON format POST When a user wants to create a new user in a hypothetical API. And wants to send the following JSON data: { "username": "newuser", "email": "[email protected]", "password": "securepassword" } The following Python code sends a POST request with the specified data: import requests url = "https://api.example.com/users" data = { "username": "newuser", "email": "[email protected]", "password": "securepassword" } # Make the POST request response = requests.post(url, json=data) if response.status_code == 201: print("User created successfully:", response.json()) else: print("Error:", response.status_code, response.text) PUT When a client wants to update the information of a user with a specific ID.  import requests url = "https://api.example.com/users/123" data = { "username": "updateduser", "email": "[email protected]" } # Make the PUT request response = requests.put(url, json=data) if response.status_code == 200: print("User updated successfully:", response.json()) else: print("Error:", response.status_code, response.text) DELETE When a client wants to delete a specific user. Here’s how it will look like in Python. import requests url = "https://api.example.com/users/123" # Make the DELETE request response = requests.delete(url) if response.status_code == 204: print("User deleted successfully.") else: print("Error:", response.status_code, response.text) Conclusion HTTP requests play a critical role in web interactions. Hence, it is essential to understand various request methods and how they work. However, the key to seamless communication lies in picking a suitable method. This also enhances the efficiency of web applications.  
04 October 2024 · 9 min to read
Python

How to Read Excel Files in Python using Pandas

Excel files are commonly used to organize, sort, and analyze data in a tabular format with rows and columns. They are widely applied in industries like data analysis, finance, and reporting. Using Python, the pandas library allows for efficient manipulation of Excel files, enabling operations like reading and writing data. This article will cover how to use the read_excel function from pandas to read Excel files. Installing Pandas To begin, install pandas by running the following command: pip install pandas This will install pandas along with the required dependencies in your work environment. Additionally, the openpyxl module is needed for reading .xlsx files. Why OpenPyXL? Excel files come in different formats and extensions. To ensure compatibility when working with these files, pandas allows you to specify the engine you want to use. Below is a list of supported engines for reading Excel files: OpenPyXL: Used for reading and writing .xlsx files (Excel 2007+). XlsxWriter: Primarily used for writing .xlsx files. xlrd: Used for reading older .xls files (Excel 97-2003). Pyxlsb: Used for reading .xlsb (binary Excel format) files. OpenPyXL also supports Excel-specific features, such as formatting and formulas. OpenPyXL is already installed as a dependency of pandas, but you can install it using the following command: pip install openpyxl While OpenPyXL can be used on its own to read Excel files, it is also integrated as an engine within pandas for reading and writing .xlsx files. We will work with an Excel file that you can download here. Download the file and move it into your working environment. Basic Usage of read_excel Function The Excel file we are working with has the following structure: It also has three worksheets: Orders, Returns, and Users. To read this file, the read_excel function from pandas will be used. The read_excel function in pandas is used to import data from Excel files into a pandas DataFrame, a powerful structure for analyzing and manipulating data. This function is highly versatile, allowing users to read data from specific sheets, columns, or ranges. Here is how to use this function while specifying the engine: import pandas as pd df = pd.read_excel('SuperStoreUS-2015.xlsx') print(df) This code imports the pandas library and uses the read_excel function to read the SuperStoreUS-2015.xlsx Excel file into a pandas DataFrame. The print(df) statement outputs the DataFrame contents, displaying the data from the Excel file. Below is the resulting output: Row ID Order Priority Discount Unit Price Shipping Cost ... Ship Date Profit Quantity ordered new Sales Order ID 0 20847 High 0.01 2.84 0.93 ... 2015-01-08 4.5600 4 13.01 88522 1 20228 Not Specified 0.02 500.98 26.00 ... 2015-06-15 4390.3665 12 6362.85 90193 2 21776 Critical 0.06 9.48 7.29 ... 2015-02-17 -53.8096 22 211.15 90192 3 24844 Medium 0.09 78.69 19.99 ... 2015-05-14 803.4705 16 1164.45 86838 4 24846 Medium 0.08 3.28 2.31 ... 2015-05-13 -24.0300 7 22.23 86838 The read_excel function is highly flexible and can be adapted to various usage scenarios. Next, we will explore how to use it for reading specific sheets and columns. Reading Specific Sheets and Columns Excel files can come with multiple sheets and as many columns as possible. The read_excel function takes the sheet_name argument to tell pandas which sheet to read. By default, read_excel will load all worksheets. Here is how you can use the sheet_name argument: df = pd.read_excel('SuperStoreUS-2015.xlsx', sheet_name="Returns") print(df) This will read the Returns sheet, and here is an example output: Order ID Status 0 65 Returned 1 612 Returned 2 614 Returned 3 678 Returned 4 710 Returned ... ... ... 1629 182681 Returned 1630 182683 Returned 1631 182750 Returned 1632 182781 Returned 1633 182906 Returned [1634 rows x 2 columns] The sheet_name argument also takes integers that are used in zero-indexed sheet positions. For instance, using pd.read_excel('SuperStoreUS-2015.xlsx', sheet_name=1) will load the Returns sheet as well. You can also choose to read specific columns from the Excel file. The read_excel function allows for selective column reading using the usecols parameter. It accepts various formats: A string for Excel column letters or ranges (e.g., "A:C"). A list of integers for column positions. A list of column names. Here is an example using column names: import pandas as pd df = pd.read_excel('SuperStoreUS-2015.xlsx', usecols=['Row ID', 'Sales']) print(df) In this case, the usecols parameter specifies that only columns Row ID and Sales from the Excel file should be imported into the DataFrame. The code below does the same thing, but using Excel column letters: import pandas as pd df = pd.read_excel('SuperStoreUS-2015.xlsx', usecols='A,X') print(df) Here is the output: Row ID Sales 0 20847 13.01 1 20228 6362.85 2 21776 211.15 3 24844 1164.45 4 24846 22.23 ... ... ... 1947 19842 207.31 1948 19843 143.12 1949 26208 59.98 1950 24911 135.78 1951 25914 506.50 You can also use range selection to read columns by their position. In the code below, we are reading from Order Priority to Customer ID. df = pd.read_excel('SuperStoreUS-2015.xlsx', usecols='B:F') Here is an example output when reading columns B to F: Order Priority Discount Unit Price Shipping Cost Customer ID 0 High 0.01 2.84 0.93 3 1 Not Specified 0.02 500.98 26.00 5 2 Critical 0.06 9.48 7.29 11 3 Medium 0.09 78.69 19.99 14 4 Medium 0.08 3.28 2.31 14 Additionally, you can provide a callable that evaluates column names, reading only those for which the function returns True. Handling Missing Data in Excel Files In Excel files, missing data refers to values that are absent, often represented by empty cells. When reading an Excel file into a pandas DataFrame, missing data is automatically identified and handled as NaN (Not a Number), which is pandas placeholder for missing values. Pandas offers several methods to handle missing data, such as: dropna(): Removes rows or columns with missing values. fillna(): Replaces missing values with a specified value (e.g., 0 or the mean of the column). isna(): Detects missing values and returns a boolean DataFrame. For example, using fillna on our Excel file will replace all missing values with 0: df = pd.read_excel('SuperStoreUS-2015.xlsx') df_cleaned = df.fillna(0) Handling missing data is essential to ensure accurate analysis and prevent errors or biases in data-driven decisions. Reading and Analyzing an Excel File in Pandas Let’s make a pragmatic use of the notion we have learned. In this practical example, we will walk through reading an Excel file, performing some basic analysis, and exporting the manipulated data into various formats.  Specifically, we’ll calculate the sum, maximum, and minimum values for the Profit column for the year 2015, and export the results to CSV, JSON, and a Python dictionary. Step 1: Loading the Excel File The first step is to load the Excel file using the read_excel function from pandas: import pandas as pd df = pd.read_excel('SuperStoreUS-2015.xlsx', usecols=['Ship Date', 'Profit']) print(df.head()) This code reads the SuperStoreUS-2015.xlsx file into a pandas DataFrame and displays the first few rows, including the Ship Date and Profit columns. Step 2: Calculating Profit for June 2015 Next, we will filter the data to include only records from June 2015 and calculate the total, maximum, and minimum profit for that month. Since the date format in the dataset is MM/DD/YYYY, we will convert the Ship Date column to a datetime format and filter by the specific month: df['Ship Date'] = pd.to_datetime(df['Ship Date'], format='%m/%d/%Y') df_june_2015 = df[(df['Ship Date'].dt.year == 2015) & (df['Ship Date'].dt.month == 6)] # Calculate the sum, max, and min for the Profit column profit_sum = df_june_2015['Profit'].sum() profit_max = df_june_2015['Profit'].max() profit_min = df_june_2015['Profit'].min() print(f"Total Profit in June 2015: {profit_sum}") print(f"Maximum Profit in June 2015: {profit_max}") print(f"Minimum Profit in June 2015: {profit_min}") The output will be something like: print(f"Total Profit in June 2015: {round(profit_sum, ndigits=2)}") print(f"Maximum Profit in June 2015: {round(profit_max, ndigits=2)}") print(f"Minimum Profit in June 2015: {round(profit_min, ndigits=2)}") Step 3: Exporting the Manipulated Data Once the profit for June 2015 has been calculated, we can export the filtered data to different formats, including CSV, JSON, and a Python dictionary. # Export to CSV df_june_2015.to_csv('SuperStoreUS_June2015_Profit.csv', index=False) # Export to JSON df_june_2015.to_json('SuperStoreUS_June2015_Profit.json', orient='records') # Convert to Dictionary data_dict = df_june_2015.to_dict(orient='records') print(data_dict[:5]) In this step, the data is first exported to a CSV file and then to a JSON file. Finally, the DataFrame is converted into a Python dictionary, with each row represented as a dictionary. Conclusion In this article, we have learned how to use the read_excel function from pandas to read and manipulate Excel files. This is a powerful function with the ability to simplify data filtering for a better focus on the rows or columns we want.
03 October 2024 · 8 min to read
Python

How to Convert String to Float in Python

Python variables provide an easy way to store and access data in a program. They represent the memory addresses that contain the required data values. Each variable has a specific data type which reflects the kind of data it can store like an int, float, or a string. In some scenarios, we might need to convert one data type to another in order to be used in a later operation in our program. For example, if we receive an integer number from a user like this x = input(“Please enter a number:”) this input variable will be automatically stored as a string. So, if we’re to do a numeric operation on it we’ll need to convert it to an int first. This process of converting between data types is called type casting or type conversion. It is a fundamental concept in programming that offers compatibility and flexibility in our programs. In this article, we will cover a common example of type casting in Python which is converting a string to a float. We will also look at handling conversion errors that might appear in some scenarios. Type Casting Categories There are mainly two kinds of type casting, explicit casting and implicit casting. Explicit Casting In the explicit casting the developer manually declares the conversion and writes it inside the code. This is usually done by using a conversion function for a specific data type. For example, we can convert a float to an int with the following code: x=1.5 # float variable y=int(x) # convert to integer with the int() function To determine the data type of y we can use the type() function as follows: print(type(y)) Now the output should print the type of y as int:  The explicit casting gives the programmer control over when and how to execute the conversion. Implicit Casting In the implicit casting the interpreter automatically converts between data types without the need for the developer to declare it in the code. This is usually done to allow for compatibility in an operation and prevent data loss. For example, when performing addition operation between a float and an int as follows: x=1.5 y=1 z= x+y In the above example, Python will automatically convert the integer value 1 to a float: print(type(z)) print(z) Now the output should print the type of z and its value: As we can see from the image, the variable z which is the result of the addition has a data type of float. Converting Strings to Floats Using float() function To convert a string to a float in Python we use a function called float(). It is a built-in function that takes an argument (whether a string or an int) and constructs a floating-point number from it. For example, the following code will convert the value of the my_string variable to a float: my_string="10.267" my_float=float(my_string) We can then check the type and value of the my_float variable with the following code: print(type(my_float)) print(my_float) Now if we run the above example we’ll get the type of my_float variable as a float with the same value constructed from the converted string: By converting the string to a float we can now execute the numeric operations we need on the converted variable: In the above image we performed an addition operation on our variable (my_float+10) and it was executed successfully. When we use the float() function, what happens under the hood is that it calls an object method named __float__(). This __float__() method implements the float() function and executes the logic for the conversion. In other words, when we write float(x) it is translated into x.__float__(). Handling Conversion Errors with try/except We might encounter a scenario where a string value isn’t applicable for conversion to a float. For example, if the user inputs a string that doesn’t match a valid float number format (contains letters, special characters, etc). To handle such cases, we need to implement a validation logic that checks if the input is applicable for conversion. A common implementation for this logic can be done using the Python try/except block. First let’s test the scenario without error handling using the following code: invalid_string="abc10.5" my_float=float(invalid_string) Now let’s try to run our code: As we can see in the above image, the code produced a ValueError because the invalid_string variable contained an improper float value format. To handle such error, we can use a try/except block as follows: invalid_string="abc10.5" try: my_float=float(invalid_string) except ValueError: print("Please enter a valid string value") In the above code we are executing our conversion inside the try block, then we’re using the except block to check if the conversion throws a ValueError exception. Let’s run our code again: As we can see in the above image, because this conversion throws a ValueError the code inside the except block gets executed and prints our output message. Converting Lists of Strings to Floats We can also apply the type casting process to a list of objects instead of a single variable. In that case we’ll be converting each item in the list to a different data type. So, we can extend upon our previous example and convert a list of strings to floats. Let’s explore a couple of ways in which we can achieve this: Using List Comprehension List comprehension is a very handy way to create a new list out of an existing list in Python. It provides a simpler and shorter syntax in which you can apply specific logic or operations on the existing list items to produce the new list. We can convert a list of strings to floats using list comprehension with the following code: string_list=["10.1", "10.2", "10.3", "10.4"] float_list=[float(item) for item in string_list] In the above code, we create the float_list from the string_list by iterating over each item in the string_list and executing the float() function. We can then print the new float_list and the type of each item inside it with the following code: print(float_list) for x in float_list: print(type(x)) Now let’s run our code and check the output: As we can see in the above image, the float_list was populated by the items from the string_list, but the type of each item was converted to a float. Using the map() function Another way for converting a list of strings to floats is by using the map() function. The map() function returns a map object after taking two arguments, the first is a function that we want to execute, and the second is an iterable (list, tuple, etc) where we want to execute the first function on each item. Let’s explain this on our scenario using the following code: string_list=["10.1", "10.2", "10.3", "10.4"] float_list=list(map(float, string_list)) Again we’ve our existing string_list and we want to create a new float_list from it after conversion. The map() function here is taking two arguments which are float and string_list. This means we want to apply the float() function on each item in the string_list. Since the map() function returns a map object, we’re passing it to the list() function to convert the return object into a list which will be stored in the float_list object. Let’s run our code and check the output: We can see the float_list is again created from the string_list by converting the string items to floats. Using Traditional for loop We can also convert our list of strings to floats using our good friend, the Python for loop as follows:  string_list=["10.1", "10.2", "10.3", "10.4"] float_list=[] for item in string_list: float_list.append(float(item)) In the above code, we iterate over the string_list and append each item into the float_list after converting it to a float. Now let’s run our code: Again we’ve our float_list here is populated from the string_list and the items are converted from strings to floats. Conclusion Python type casting is a fundamental concept that involves converting one data type to another. It provides compatibility and flexibility for programmers in their code. In this article we’ve covered a common example of type casting which is converting a string to a float using the float() function. We also used the try/except block to handle conversion errors when the input string format is not valid.
02 October 2024 · 7 min to read
Python

How to Install Python on Windows

Python is one of the most talked-about programming languages today, widely used by developers and administrators alike. This language is found everywhere. Even for those who are not software engineers, it is important to understand how to install Python on Windows and start using it.  This article will walk users through the entire process of installing Python on Windows. Let’s dive in and explore it together. Introduction to Python Python is a robust, high-level, interpreted programming language that makes the code readability easy and simple. Its syntax allows developers to express their concepts in fewer lines of code unlike other languages, such as Java or C++. Python also supports multiple programming methods, like object-oriented, functional programming or procedural. This makes it an ideal choice for the programmer to do various types of projects with ease.  Downloading Python for Windows To perform Python installation on Windows, first download the installer file from the official website using the following steps: Step 1: Navigate to the Python Download Page Open any browser on the Windows system.  Then, visit the official Python download page. Step 2: Download Python Click on the “Download Python” button to download the latest version of Python for Windows. The users can also scroll down and select the desired Python version to download on their Windows systems.  After completing these steps, an .exe file will be downloaded. This file is the main installer for Python. The whole process is often referred to as a Python language download. Running the Python Installer After downloading the installer, follow these steps to install Python from the file: Step 1: Run the Installer File Locate the downloaded installer file (.exe), usually found in the Downloads folder.  After finding the installer file, simply double-click on it to run it.  Step 2: Complete the Installation In the installer window, check the box that says “Add python.exe to PATH” to make it easier to run Python from the command line.  To make sure the installation has the necessary permissions, also check the box that suggests “Use admin privileges when installing py.exe”.  Once done, click the “Install Now” button to begin the installation.  Step 3 (Optional): Customize the Installation Users can customize the Python setup for Windows by selecting the “Customize installation” option. Doing this allows them to tailor the installation process to their specific needs. Go with all features, including the one with the install py launcher to make it easier to start Python.  Click “Next” after making the desired selections. In the Advanced Options, users can check the boxes to download debugging symbols and binaries. This is useful for developers who need to debug their Python applications.  Apart from that, a different location can also be selected for Python.  Once done, click the “Install” button. Step 4: Wait for Installation Wait for the installation to complete, since it might take a few minutes. Verifying the Installation Once the installation is complete, verify that Python is installed correctly by following these steps: Open Command Prompt from the Start Menu by simply searching for “cmd” in the search box. In the window of the Command Prompt, enter the following command: python --version After executing the command, the user will see the version of the Python that was installed on the system.  If the above steps have been followed carefully, the user will be able to use Python on Windows without any issues. If an error message appears, it means that Python was not installed correctly. This may occur if the user forgets to check the box that says “Add python.exe to PATH”. If this happens, an additional method, “Setting Up Python in Windows PATH” must be followed which is given below.  Setting Up Python in Windows PATH To set up Python in Windows PATH manually, follow the steps provide below: Step 1: Run Environment Variables From the Start Menu, search for “Environment Variables”.  Then click on the “Edit the system environment variables” option: This will open the System Properties Advanced tab: Step 2: Open Environment Variables Window In the System Properties Advanced tab, click on the “Environment Variables” button. Step 3: Locate the Path Variable In the Environment Variables window, navigate to the “Path” variable in the “System variables” section and select it. Step 4: Edit the Path Variable Double-click on the Path option or select the Path option, click on “Edit” to open the Edit environment variables window.  Once done, simply select the “New” button to add a new entry. Step 5: Add Python Installation Directory In the New entry box, enter the path to the Python installation directory. For example “C:\Users\personal_username\AppData\Local\Programs\Python\Python312\”.  Once done, click the “OK” button to save the changes. Use the “where python” command on Command Prompt to know where is Python installed on the system. Testing the Python Installation To ensure the system completes the Python programming setup, let’s run a simple test. Open Command Prompt from the Start Menu. Enter the following command to run Python interactive shell: python At the interactive shell, the user can now type Python commands or execute codes to see the output. Bonus Tips on Python Installation for Windows The following are some additional tips that can be useful during the installation process: For an instant Python download, the users can use Microsoft Store to quickly install the InstantPython tool. This tool allows them to develop and execute simple Python programs. If the command python3 doesn't work on Windows, it is likely due to the way Python is installed and configured on the system. The simple solution is to move to the Python installation directory and rename the python.exe file to python3.exe. This will fix the issue, and the user will be able to run the python3 command. For users who prefer using PowerShell, the process to download python or python3 for Windows powershell is straightforward. Simply open the PowerShell as administrator and use the following command: Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.12.6/python-3.12.6-amd64.exe" -OutFile "python-3.12.6-amd64.exe" Summary Python installation on Windows is a straightforward process that opens up a world of programming possibilities. By following the steps provided in this guide, users can ensure that Python is installed correctly and ready to use. Whether developing web applications, exploring AI, or analyzing data, Python is a must on Windows to enhance productivity and capabilities.
01 October 2024 · 6 min to read
Linux

How to Use the tail Command in Linux

Linux is a family of open-source Unix-like operating systems, such as Debian, Ubuntu, CentOS, and many others. When working with these OSes, we would usually use commands to operate the system and perform tasks like reading, writing, or viewing files, creating, and managing folders. System administrators often need to check system log files or read specific files, and the command tail is one of the essential tools for this purpose. UNIX tail Command The tail command in Linux complements the cat and head commands used for reading files. While these commands start reading files from the beginning, the tail command reads or monitors files from the end or bottom. Syntax The basic syntax to use the tail command in Linux is as follows: tail [Option] [File Name] Options The following are a few options that can be used with the Linux tail command: Option Description -c Show the output depending on the number of bytes provided. -f, --follow Continue to show output as the file grows, follow the output -n, --lines Output the last specified number of lines instead of 10. --pid Terminate output after process ID when used with the -f option. -q, --quiet Skip the header that shows the file name. -s, --sleep-interval Add sleep intervals between iterations. -v, --verbose Add a header that contains the file name. --help Open help information related to the command. Let’s move forward to check the practical administrative uses of this command. Basic Use of Linux tail Command The tail command Linux is commonly used by administrators to monitor the system logs, debug the system by reading the debug.log file, and check the authorization or authentication through the auth.log file. Here are some basic practical examples of using this command in Linux. For demonstration, this blog uses cities.txt and countries.txt files. Read File In Linux, files are normally read using the cat command. However, the cat command simply reads and displays the complete file content from the start: cat cities.txt In contrast, the command tail in Linux reads the file from the end or bottom. By default, it displays the last 10 rows of the file. To use this command, execute the tail <file-name>: tail cities.txt Read File From Specific Line To start reading a file from the desired line number, simply use +NUM with the command: tail +60 cities.txt Here, the result displays the entries from line 60 and onward: Read File with -n Option To read or display specified numbers of lines from the tail or bottom, utilize the -n <number of lines> argument with the command as shown below: tail -n 15 cities.txt The output displays the last 15 lines of the cities.txt file: Read Multiple Files Users can also monitor multiple files through the Linux tail command. For this purpose, utilize tail <file1-name> <file2-name> <file3-name> command: tail cities.txt countries.txt This command displays the last 10 entries of provided files and also adds the filename in headers before displaying file entries: Let’s check out the advanced administrative uses of the tail in Linux through the below section. Advanced Uses of tail Command in Linux The tail Linux command is more than just viewing the last few lines of the file. It is used for real-time monitoring, managing the output based on bytes, processes, and sleep time intervals. These all advanced options are used to monitor logs and manage the application behaviors. Let’s check some advanced practical illustrations of the command. tail Command with -c Option To get the output by providing the number of the bytes, use the -c <number of bytes> option:  tail -c 50 cities.txt The below output shows the specified number of bytes from the bottom instead of lines: tail Command with -v Option The -v or --verbose option is used to add the header while displaying the result. The header contains the file name. For demonstration, use the tail -v <file-name> command: tail -v cities.txt Monitoring Logs with tail -f Administrators are often needed to monitor the system in real-time, check application behavior, or debug errors. For this purpose, they usually need to view system logs. In Linux, all log files are located in the /var/log directory. To open and view the log directory, utilize the following commands: cd /var/logls To monitor the logs in real-time, use the -f or --follow argument with the tail: tail -f /var/log/syslog As files or logs grow, these are displayed on the screen continuously as shown below: tail Command with -s Option Use the -s <time-interval> argument to add the sleep interval between the iteration while monitoring the logs or file in real-time: tail -f -s 5 /var/log/syslog tail Command with -q Option To read or monitor the file in quiet mode or to skip the header while viewing multiple files, utilize the -q option: tail -q cities.txt countries.txt Here, the output shows the last 10 lines of the cities.txt and countries.txt files but skips the headers of the files: tail Command with Pipe(|) Operator The Pipe (|) operator enables us to pass the output of the first command to the second command. It permits the users to use multiple commands at one time. Similarly, the tail Linux can also be used with some other commands such as the grep command to search specific logs or the sort command to sort the order. Moreover, users can use the tail command with Docker logs to see the latest logs from a Docker container. Let’s go through the following examples for demonstration. Example 1: Search for the Specific Word From the End To search the specific words from the end of the file or a specified number of files from the bottom, use the following command: tail -n 20 cities.txt | grep "Bangor" In this command, the tail extracts the last 20 lines from the file, and then the output is piped out through the pipe operator, and the grep command filters the specified word from the output: Example 2: Sort the Output in Reverse Order To sort the output produced from the tail in reverse order, utilize the following command: tail -n 6 cities.txt | sort -r Example 3: Monitor the System Logs of Specific Date To check the logs of a specific date from the log file, first, extract the logs and then filter the log of the date through the grep command: tail /var/log/syslog | grep "2024-09-22" Conclusion The tail command in Linux is a powerful tool for system administrators and Linux users, providing both basic and advanced functionalities for reading and monitoring files. This command reads or monitors the file or system logs from the tail or bottom. The tail command supports options like -f, -c, --verbose, and -q for advanced functionality. It can also be combined with other commands like grep, sort, df, or cat using the pipe (|) operator for extended functionality. By mastering this command, the users can efficiently manage and troubleshoot their Linux systems. 
30 September 2024 · 6 min to read

Answers to Your Questions

What is Hostman used for, and what services do you offer?

Hostman is a cloud platform where developers and tech teams can host their solutions: websites, e-commerce stores, web services, applications, games, and more. With Hostman, you have the freedom to choose services, reserve as many resources as you need, and manage them through a user-friendly interface.

Currently, we offer ready-to-go solutions for launching cloud servers and databases, as well as a platform for testing any applications.

 

  • Cloud Servers. Your dedicated computing resources on servers in Poland and the Netherlands. Soon, we'll also be in the USA, Singapore, Egypt, and Nigeria. We offer 25+ ready-made setups with pre-installed environments and software for analytics systems, gaming, e-commerce, streaming, and websites of any complexity.

  • Databases. Instant setup for any popular database management system (DBMS), including MySQL, PostgreSQL, MongoDB, Redis, Apache Kafka, and OpenSearch.

  • Apps. Connect your Github, Gitlab, or Bitbucket and test your websites, services, and applications. No matter the framework - React, Angular, Vue, Next.js, Ember, etc. - chances are, we support it.

Can I have confidence in Hostman to handle my sensitive data and cloud-based applications?

Your data's security is our top priority. Only you will have access to whatever you host with Hostman.

Additionally, we house our servers in Tier IV data centers, representing the pinnacle of reliability available today. Furthermore, all data centers comply with international standards: 

  • ISO: Data center design standards

  • PCI DSS: Payment data processing standards

  • GDPR: EU standards for personal data protection

What are the benefits of using Hostman as my cloud service provider?

User-Friendly. With Hostman, you're in control. Manage your services, infrastructure, and pricing structures all within an intuitive dashboard. Cloud computing has never been this convenient.

 

Great Uptime: Experience peace of mind with 99.99% SLA uptime. Your projects stay live, with no interruptions or unpleasant surprises.

 

Around-the-Clock Support. Our experts are ready to assist and consult at any hour. Encountered a hurdle that requires our intervention? Please don't hesitate to reach out. We're here to help you through every step of the process.

 

How does pricing work for your cloud services?

At Hostman, you pay only for the resources you genuinely use, down to the hour. No hidden fees, no restrictions.

Pricing starts as low as $4 per month, providing you with a single-core processor at 3.2 GHz, 1 GB of RAM, and 25 GB of persistent storage. On the higher end, we offer plans up to $75 per month, which gives you access to 8 cores, 16 GB of RAM, and 320 GB of persistent storage.

For a detailed look at all our pricing tiers, please refer to our comprehensive pricing page.

Do you provide 24/7 customer support for any issues or inquiries?

Yes, our technical specialists are available 24/7, providing continuous support via chat, email, and phone. We strive to respond to inquiries within minutes, ensuring you're never left stranded. Feel free to reach out for any issue — we're here to assist.

Can I easily scale my resources with Hostman's cloud services?

With Hostman, you can scale your servers instantly and effortlessly, allowing for configuration upsizing or downsizing, and bandwidth adjustments.

Please note: While server disk space can technically only be increased, you have the flexibility to create a new server with less disk space at any time, transfer your project, and delete the old server

What security measures do you have in place to protect my data in the cloud?

Hostman ensures 99.99% reliability per SLA, guaranteeing server downtime of no more than 52 minutes over a year. Additionally, we house our servers exclusively in Tier IV data centers, which comply with all international security standards.

 

How can I get started with Hostman's cloud services for my business?

Just sign up and select the solution that fits your needs. We have ready-made setups for almost any project: a vast marketplace for ordering servers with pre-installed software, set plans, a flexible configurator, and even resources for custom requests.

If you need any assistance, reach out to our support team. Our specialists are always happy to help, advise on the right solution, and migrate your services to the cloud — for free.

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us