Sign In
Sign In

Cloud Servers

Prices from $4/ mo, unlimited traffic. Locations in the US, Europe and Asia
Contact Sales
3.3 GHz Processors
and NVMe Disks
Increase productivity with our 3.3 GHz processors and fast NVMe drives for rapid data handling and smooth performance
200 Mbit Channels with
Unlimited Traffic
Enjoy seamless connectivity with our 200 Mbit channels, providing unlimited traffic with no overage fees
Guaranteed
100% CPU Share
Enjoy reliable, top-notch performance with a 100% CPU share committed to handling your most demanding tasks
Free Tech
Support
Get support from our experts at any hour – they’re available to help 24/7, no matter the time

Simple and Predictable Pricing

New York
1 x 3 GHz CPU
CPU
1 x 3 GHz
1 GB RAM
RAM
1 GB
25 GB NVMe
NVMe
25 GB
200 Mbps Bandwidth
Bandwidth
200 Mbps
Public IP
$4
 /mo
1 x 3 GHz CPU
CPU
1 x 3 GHz
2 GB RAM
RAM
2 GB
40 GB NVMe
NVMe
40 GB
200 Mbps Bandwidth
Bandwidth
200 Mbps
Public IP
$5
 /mo
2 x 3 GHz CPU
CPU
2 x 3 GHz
2 GB RAM
RAM
2 GB
60 GB NVMe
NVMe
60 GB
200 Mbps Bandwidth
Bandwidth
200 Mbps
Public IP
$6
 /mo
2 x 3 GHz CPU
CPU
2 x 3 GHz
4 GB RAM
RAM
4 GB
80 GB NVMe
NVMe
80 GB
200 Mbps Bandwidth
Bandwidth
200 Mbps
Public IP
$8
 /mo
4 x 3 GHz CPU
CPU
4 x 3 GHz
8 GB RAM
RAM
8 GB
160 GB NVMe
NVMe
160 GB
200 Mbps Bandwidth
Bandwidth
200 Mbps
Public IP
$17
 /mo
8 x 3 GHz CPU
CPU
8 x 3 GHz
16 GB RAM
RAM
16 GB
320 GB NVMe
NVMe
320 GB
200 Mbps Bandwidth
Bandwidth
200 Mbps
Public IP
$37
 /mo
CPU
RAM
Gb
NVMe
Gb
Public IP
$0
 /mo

Deploy any software in seconds

Select the desired OS or App and install it in one click
OS Distributions
Pre-installed Apps
Custom Images
Ubuntu
Debian
CentOS

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

Efficient tools for your convenient work

See all Products

Backups, Snapshots

Protect your data with regular backups and snapshots, ensuring you never lose crucial information

Firewall

Enhance your security measures with our robust firewall protection, safeguarding your infrastructure against potential threats

Load Balancer

Ensure optimal performance and scalability by evenly distributing traffic across multiple servers with our load balancer feature

Private Networks

Establish secure and isolated connections between your servers with private networks, shielding sensitive data and enhancing network efficiency

Trusted by 500+ companies and developers worldwide

One panel to rule them all

Easily control your database, pricing plan, and additional services
through the intuitive Hostman management console
Project management
Organize your multiple cloud servers and databases into a single, organized project, eliminating confusion and simplifying management
Software marketplace
24 ready-made assemblies for any tasks: frameworks, e-commerce, analytics tools
Mobile responsive
Get the optimal user experience across all devices with our mobile-responsive design

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
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...

More cloud services from Hostman

See all Products

Latest News

Python

Conditional Statements in Python

In this article, we will discuss perhaps the most essential part of any program, as conditional constructs shape its structure and determine which parts of the code are executed. These constructs are often referred to as the "heart" of a program in any programming language, and even artificial intelligence is largely built on conditional branching. Therefore, let's take a closer look at them in the following order: The if statement The if-else construct The if-elif-else construct Examples of programs What Does the Conditional Statement Do in Python? The simplest way to understand this is through an example. Enter the following in the Python interpreter and press Enter to see the output: >>> if 5 > 4:print('True, 5 is greater than 4.') Output: True, 5 is greater than 4. Here we have a basic example of how the program works with a condition.  Thus, if is used to execute a block of code based on a condition: if the condition is true, the block of code will be executed; if it is false, it will not. Let’s provide an example of False; enter and press Enter: if 5 < 4:print('True, 4 is greater than 5') The interpreter remains silent—which is correct because the condition is false, and thus the statement "True, 4 is greater than 5" (which is itself also incorrect) will never be output. However, in most cases, more than one condition will be required, and we will need to use more complex constructs: if-else and if-elif-else. The if-else Conditional Statement The if-else construct is used when you need to give the program a choice: in the first case, do one thing, and in the second case, do something else. Here’s an example: money = int(input('How much would you like to spend on shopping? Enter a number: ')) if money >= 10: print('Welcome! We have sent the catalog to your email.') else: print('Unfortunately, we do not have any products cheaper than 10 dollars. Please visit us again.') input('Press Enter to exit.') The first line is needed for input, handled by the input statement. In brief, the input function accepts user input and, if necessary, assigns the entered value to a variable (in this case, money). Next comes the condition: if the entered amount equals or exceeds $10, the program gives a positive response. If the entered amount is $9 or less, a different response is given. In the last line, we also added the input operator, which, in this case, does not pass any value to a variable but serves to move to the next line of code. Since we have no additional lines, pressing Enter will exit the program; this is another feature of input. The if-elif-else Conditional Statement Let’s complicate the previous example and make the program choose from three options. We can do this by adding an additional condition that will be set by the elif operator: money = int(input('How much would you like to spend on shopping? Enter a number: ')) if money >= 10000: print('Welcome, wholesale buyer! We have special discounts for you.') elif money >= 10: print('Welcome! We have sent the catalog to your email.') else: print('Unfortunately, we do not have any products cheaper than 10 dollars. Please visit us again.') input('Press Enter to exit.') Now, if the user enters an amount equal to or greater than the specified value (10000), the program will output the text from the first if block. If the amount is less than this value but equal to or greater than 10, the condition of the elif operator will be executed, and the user will see the second message. It’s worth noting that there can be as many elif statements as needed, but the main rule is that the first condition must always specify the if operator. Here’s an example of code with several elif statements. Let’s imagine we want to generate a starting star system for our civilization in a space strategy game: import random star = random.randint(1, 5) planets = random.randint(1, 10) if star == 1: print('Your civilization lives in a blue giant system with', planets, 'planets orbiting.') elif star == 2: print('Your civilization lives in a white dwarf system with', planets, 'planets orbiting.') elif star == 3: print('Your civilization lives in a sun-like yellow dwarf system with', planets, 'planets orbiting.') elif star == 4: print('Your civilization lives in an orange giant system with', planets, 'planets orbiting.') else: print('Your civilization lives in a red supergiant system with', planets, 'planets orbiting.') input('Press Enter to exit') Here’s the system that random has gifted us: Your civilization lives in a sun-like yellow dwarf system with 6 planets orbiting.Press Enter to exit. It’s almost solar, just with fewer planets. Note that we created two variables (star and planets), and we entrusted the generation of values to the random module, which needs to be called first: import random Next, using the random.randint instruction, we set the range of generated values, from which the random number generator (RNG) selects one: for stars from 5 and for planets from 10: star = random.randint(1, 5)planets = random.randint(1, 10) Since we have five types of stars, there should be just as many blocks of code with conditions, which is why we used several elif operators. The number of planets will be arbitrary for any piece of code because the planets variable is included in everything. One more thing: you may have already noticed that some operations in the code are indicated with a single = sign, while others use a double equality ==. In Python, a single equal sign = is used only for assigning values to variables, while double equality == is used for comparison. Therefore, in the example above, the code: star = random.randint(1, 5) means that the variable star takes on a random value generated by the random module, while the expression: if star == 1: means that the variable star, which has already been assigned a value, is being compared to the value 1 (and if this condition is true, the code in this block begins to execute). Game Examples The best way to learn is by playing, so let’s demonstrate how the if-else conditional operator works in Python through simple games while also getting acquainted with other useful functions. Coin Tossing Let’s write a program using the if-elif-else conditional statement and examine how this program is structured step by step. Type the following into your editor, making sure to maintain the indentation: import random coin = random.randint(1, 2) attempts = 0 heads = 0 tails = 0 while attempts < 100: if coin == 1: heads += 1 attempts += 1 coin = random.randint(1, 2) elif coin == 2: tails += 1 attempts += 1 coin = random.randint(1, 2) else: print('The coin landed on its edge. Does that ever happen? Alright, let’s toss it again.') attempts += 1 coin = random.randint(1, 2) print('Heads appeared', heads, 'time(s), and tails', tails, 'time(s).') input('Press Enter to exit') We will simulate the coin tosses using the RNG we are already familiar with, provided by the random module. This is called in the first line of the code: import random Next, we define several variables: coin — for the coin tosses, attempts — to count the number of tosses, heads — to tally the number of heads, tails — to tally the number of tails. When tossing the coin, we will use the RNG immediately, so we write: coin = random.randint(1, 2) This means that a value will be generated randomly in the range from 1 to 2, which means it can either be a 1 or a 2. Now we just need to assign these values to heads and tails accordingly, specify the maximum number of tosses, and ensure that the count of each increases by one with each toss. For this, we use the Python if-elif-else conditional construct inside a while loop: while attempts < 100: This part of the code means: as long as the number of tosses is less than 100: if coin == 1: heads += 1 attempts += 1 coin = random.randint(1, 2) If the RNG returns 1: increase the number of heads by one, increase the number of tosses by one, toss the coin again. elif coin == 2: tails += 1 attempts += 1 coin = random.randint(1, 2) The same applies for tails. else: print('The coin landed on its edge. Does that ever happen? Alright, let’s toss it again.') attempts += 1 coin = random.randint(1, 2) This code is added to handle the impossible case (a coin will never land on its edge since our RNG can only output 1 or 2). However, adding a final else block is a good habit — "impossible" conditions can sometimes still occur because programmers can’t always account for every scenario. Therefore, an else block can make the program more stable in cases of unanticipated conditions. As soon as the coin has been tossed for the hundredth time, the last block of code will execute: print('Heads appeared', heads, 'time(s), and tails', tails, 'time(s).')input('Press Enter to exit') The program will exit the while loop and display how many times heads and tails appeared; we analyze the statistics and exit. Essentially, the user will only see the result displayed like this: Heads appeared 53 time(s), and tails 47 time(s).Press Enter to exit. Of course, observing the RNG is interesting, but calling either the star and planet generator or the coin toss a game is a stretch, so let’s write a more interesting program. Playing Dice In this game, we will take turns rolling dice against the computer, and in the end, we will declare a winner. The following code accomplishes this: import random score1 = 0 score2 = 0 games = 0 die1 = 0 die2 = 0 total1 = 0 die3 = 0 die4 = 0 total2 = 0 input('Roll the dice, press Enter!\n') while score1 < 6 and score2 < 6 and games <= 11: die1 = random.randint(1, 6) die2 = random.randint(1, 6) total1 = die1 + die2 print(die1, die2) print(total1, '\n') input('Now it’s my turn, press Enter!\n') die3 = random.randint(1, 6) die4 = random.randint(1, 6) total2 = die3 + die4 print(die3, die4) print(total2, '\n') if total1 > total2: score1 += 1 games += 1 elif total1 < total2: score2 += 1 games += 1 else: games += 1 print('It’s a tie\n') print('Score', score1, ':', score2, '\n') input('Press Enter!\n') if score1 > score2: input('You won! Press Enter to exit.') elif score1 < score2: input('I won! Press Enter to exit.') else: input('Friendship wins! Press Enter to exit.') This code may seem a bit long and complicated at first glance, but, firstly, we've written a real game (even if it doesn’t have graphics yet), and secondly, there’s nothing particularly difficult here — let's explain everything now. First, we call the familiar random module, then we define the following variables, which will, of course, be initialized to 0 before the game starts: score1 and score2 for counting victories for the player and the computer, games for counting the number of rounds (which we will later limit to prevent a long game in case of frequent ties), die1, die2, die3, die4 for rolling the individual dice, total1 and total2 for calculating the total score in each roll for both players: for the human player, it will be the sum total1 of the dice die1 and die2, and for the computer, it will be total2 and die3, die4 respectively. Next, we prompt the start of the game (the player will see this first), and then the program enters a loop: while score1 < 6 and score2 < 6 and games < 11: As we can see, there are multiple conditions connected by and operators. This means the program will exit the loop if any one of them is no longer true (i.e., either score1 or score2 reaches 6, or games equals 11). We play almost like a tennis set: as soon as one of the players wins six rounds, the game ends in their victory. Meanwhile, the number of rounds cannot exceed 11. Thus, if no player achieves 6 wins due to a series of ties, the game will still end after the 11th round. Now the player rolls the dice, and the program calculates their total (total1 = die1 + die2) and prints the result. After pressing Enter, the computer does the same (its total will be total2 = die3 + die4). Of course, the entire game runs solely on the RNG, but that’s how most simple games are structured: even for the player, everything is determined by random chance. Next, we move to the most important part of the program: the two if-elif-else blocks. The first one is part of the while loop: if total1 > total2: score1 += 1 games += 1 elif total1 < total2: score2 += 1 games += 1 else: games += 1 print('It’s a tie\n') print('Score', score1, ':', score2, '\n') input('Press Enter!\n') This is straightforward: if our total is higher, we score a point; if the computer wins the round, it gets a point; and in the event of a tie, no one scores, but the round is counted as played in any case. The current score is then displayed, and the players are prompted to continue playing. As soon as the while loop condition is met, meaning one of the players has achieved 6 victories or the number of played rounds has reached 11, the program exits the loop and moves to the final block: if score1 > score2: input('You won! Press Enter to exit.') elif score1 < score2: input('I won! Press Enter to exit.') else: input('Friendship wins! Press Enter to exit.') The first if condition is satisfied when the player has won more rounds than the computer. The elif condition applies if the computer was more fortunate. But what if 11 rounds were played, and both players won an equal number? This is why we added the else block, which will display a conciliatory message. Lastly, it’s important to note that Python checks conditions sequentially and executes the first true one: it will first check the if condition, then the elif conditions (if there are multiple, they are checked from top to bottom), and finally the else. Thus, if several conditions happen to be true in a complex program, only the first block will execute: keep this in mind when writing code.
21 October 2024 · 12 min to read
Python

The filter() Function in Python

Python has consistently ranked among the most popular programming languages. According to the TIOBE Software Index, Python was the most popular language in 2021. In this article, we’ll explore the usage of the filter() function in Python, which is one of the most important functions in the language. What is filter()? filter() is a built-in Python function, meaning it does not require importing additional libraries. Syntax The function takes two arguments: a function and an iterable object. filter(function, iterable) function is a function with a single argument. This function is used to filter values. iterable is an object that can be iterated over, such as a list, tuple, dictionary, etc. It can also include generator or iterator objects. The filter() function accepts only one iterable object. The filter() function breaks down the provided iterable object into elements and passes each one to the given function, which returns a value (True, False, or something else like a number or string). The filter() function evaluates the returned value, and if it is "truthy" (not necessarily equal to True, but considered true), it adds the element to the iterator. If the value is not truthy, the element is excluded. The result is an iterator containing only the elements that returned True during filtering. To get elements evaluated as False, use the itertools.filterfalse() function. The filter() function is more efficient in terms of execution time than a for loop, which can also be used for filtering. Another advantage is that filter() returns an iterator, which is a more memory-efficient way of handling data. This was introduced for filter() in Python 3. In Python 2, the filter() function returns a list. Now that we’ve covered the basics, let's look at how filter() works through various examples. Using filter() With a Custom Function One of the simplest examples is filtering even numbers. numbers = [1, 2, 3, 4, 5, 7, 10, 11] def filter_num(num): if (num % 2) != 0: return True else: return False out_filter = filter(filter_num, numbers) print("Filtered list: ", list(out_filter)) In this case, we pass a custom function (filter_num) and a list of numbers (numbers) to filter(). The result will be: Filtered list: [1, 3, 5, 7, 11] Our custom function checks if each number is odd. If there is a non-zero remainder when dividing by 2, the function returns True, meaning the element is added to the resulting iterator. Since filter() returns an object of type <class 'filter'>, we need to convert the output to a list to see the result. This example can also be implemented using a lambda function: filter(lambda n: n % 2 != 0, numbers) Finding the Intersection of Two Arrays Input data: arr1 = ['1', '2', '3', '4', 5, 6, 7]arr2 = [1, '2', 3, '4', '5', '6', 7] We write a function to find the intersection: def intersection(arr1, arr2):    out = list(filter(lambda it: it in arr1, arr2))    return out The function takes two arrays as input and checks them. Using a lambda function, it identifies the common elements. Calling the function and displaying the result: out = intersection(arr1, arr2)print("Filtered list:", out) The result: Filtered list: ['2', '4', 7] Using filter() With a Lambda Function The Python filter() function can also accept lambda functions. For example, let’s create a palindrome detector: word = ["cat", "rewire", "level", "book", "stats", "list"]palindromes = list(filter(lambda word: word == word[::-1], word))print("Palindromes: ", list(palindromes)) The result: Palindromes: ['level', 'stats'] The lambda function checks if a word is the same when written in reverse. If it is, the function returns True. Using filter() to Filter Outliers in a Dataset We import a library for statistical computations and set up a normally distributed sample with a few outliers: import statistics as stsample = [10, 8, 10, 8, 2, 7, 9, 3, 34, 9, 5, 9, 25] We calculate the mean: mean = st.mean(sample) Mean: 10.69 In normally distributed samples, outliers are often defined as values that deviate from the mean by more than two standard deviations. stdev = st.stdev(sample)low = mean - 2*stdevhigh = mean + 2*stdev Next, we calculate the standard deviation and the upper and lower bounds, then filter the sample: clean_sample = list(filter(lambda x: low <= x <= high, sample)) Result: [10, 8, 10, 8, 2, 7, 9, 3, 9, 5, 9, 25] Clearly, the value 34 was an outlier. Now, the new mean is 8.75. If we perform another iteration of this method, the value 25 will also be filtered out, leaving us with: Sample without outliers: [10, 8, 10, 8, 2, 7, 9, 3, 9, 5, 9] The new mean is 7.273, which is significantly different from the original. Working With None To understand how filter() handles None, let’s look at the following example: list_ = [0, 1, 'Hello', '', None, [], [1,2,3], 0.1, 0.0, False]print(list(filter(None, list_))) If None is passed as the function in filter(), it filters out all logically False elements (i.e., elements that are false by themselves). In this case, the result will be: [1, 'Hello', [1, 2, 3], 0.1] Here, elements like 0, [], None, '', False are filtered out because they have a logical value of False. Using filter() With a List of Dictionaries The function can also work with more complex data structures. For example, if we have a list of dictionaries and want to iterate through each element in the list, including key-value pairs in those dictionaries. Let’s take a list of books in a bookstore: books = [ {"Title": "Angels and Demons", "Author": "Dan Brown", "Price": 9}, {"Title": "Harry Potter and the Philosopher's Stone", "Author": "J.K. Rowling", "Price": 7}, {"Title": "Anna Karenina", "Author": "Leo Tolstoy", "Price": 5}, {"Title": "Dead Souls", "Author": "Nikolai Gogol", "Price": 4} ] We will filter books by price. We’ll write a function that retrieves all books costing more than 5: def cost(book):    return book["Price"] > 5 Here, the function simply checks each book’s price and returns True if it meets the condition. To display the book titles, we iterate through the filtered object: filtered_object = filter(cost, books)for row in filtered_object:    print(dict(row)["Title"]) Result: Angels and DemonsHarry Potter and the Philosopher's Stone Filtering NaN Values Suppose we have the following sample: sample = [10.1, 8.3, 10.4, 8.8, float("nan"), 7.2, float("nan")] If we try to compute something like the mean or standard deviation on this sample, we will get nan (not a number). NaN values can appear for various reasons, so one option is to remove them from the data. We use the isnan() function from the math module, which checks if a value is NaN: import math import statistics as st sample = [10.1, 8.3, 10.4, 8.8, float("nan"), 7.2, float("nan")] def searcnan(x): return not math.isnan(x) Now, when we call: st.mean(filter(searcnan, sample)) We get a result of 8.96. Alternatively, we can simplify this by using the filterfalse() function, which retains elements where the condition is False: from itertools import filterfalsest.mean(filterfalse(math.isnan, sample)) The result is the same: 8.96. Conclusion As we’ve seen, Python’s filter() function can be used in various ways. We covered some of the main applications, but as you continue to work creatively, you’ll likely discover many other ways to use this powerful function.
21 October 2024 · 6 min to read
Python

Introduction to Requests Library in Python

Requests is a Python library that helps your local script interact with web resources and the global network. It provides developers with a wide range of functions for working with all types of HTTP requests. With this library, you can obtain weather forecasts, translate text, and download movies or images without a browser within your script. This guide provides introductory information about the Python Requests library, which will be sufficient for using it in your scripts. How to Install the requests Library in Python For the purpose of this guide, we will be working in the PyCharm IDE. requests is an external library in Python, so it needs to be installed before use. First, create a project and open the terminal. Run the following command: pip3 install requests If you are using a virtual environment like Pipenv, you can install the Requests library in Python 3 with the following command: pipenv install requests After running these commands, the module will begin downloading. You can use the pip freeze command to check which modules have been installed: pip3 freeze Example output: certifi==2022.9.24 charset-normalizer==2.1.1 idna==3.4 requests==2.28.1 urllib3==1.26.12 Here's a brief explanation of what these modules do: certifi: A package of certificates for ensuring secure connections. charset-normalizer: A library that automatically detects text encodings, useful since not all sites and services use UTF-8. idna: A library that supports internationalized domain names. requests: The actual Requests module. urllib3: A module that provides functions and classes for working with URLs. First Requests In this section, we will write code to retrieve information from web resources and learn the basics of the Requests library. We will explore all aspects in more detail later. To start working with the Requests library, we need to import it: import requests Let's request google.com: import requests as rq response = rq.get('https://google.com') print(response) Output: <Response [200]> Here, we use an HTTP GET request, which is similar to visiting a website via a URL in a browser. In return, we get a Response object with a status code 200, meaning the request was successful. If we try to access a non-existent section of the site, we will receive a different response: import requests as rq response = rq.get('https://google.com/hostman') print(response) Output: <Response [404]> Now, let's discuss the types of HTTP requests and how to work with them. HTTP Requests The primary HTTP request type is GET, which allows you to view the content of a resource without modifying it. However, other requests may be needed for full interaction with web resources. Not all servers support all requests. Here are the seven types of requests supported by the Requests library: GET POST OPTIONS HEAD PUT PATCH DELETE To test the Requests library, the creators have designed the site httpbin.org, which you can use to practice. GET A GET request sends information to the site via the URL. It is suitable for cases where the transmitted data is not sensitive, such as searching for a product online. You shouldn't use it to send passwords or other confidential information. Data is appended to the URL after a ? symbol, followed by key-value pairs, like so: https://serverurl.com/get?param1=value1&param2=value2 Where: https://serverurl.com/get is the URL. param1=value1&param2=value2 are the parameters, separated by &. In Requests, the GET method syntax is: requests.get('URL', {key: value}, additional_arguments) Where: URL: The URL of the resource. {key: value}: Optional parameters for the request. additional_arguments: Optional arguments like timeout. Example: import requests as rq GetParams = {'param1': 'value1', 'param2': 'value2'} response = rq.get('https://google.com', GetParams) print(response.url) Output: https://www.google.com/?param1=value1&param2=value2 POST The POST request is used to send data to a website in the request body. This data does not appear in the URL and is ideal for sending confidential information. In Requests, the POST method syntax is: requests.post('URL', {key: value}, additional_arguments) Where: URL: The URL of the resource. {key: value}: Optional parameters for the request body. Example: import requests as rq PostParams = {'param1': 'value1', 'param2': 'value2'} response = rq.post('https://httpbin.org/post', PostParams, timeout=2) print(response.json()['form']) Output: {'param1': 'value1', 'param2': 'value2'} Here, we used the json() method to retrieve the request body. If you make a similar request to google.com, you will get an error: import requests as rq PostParams = {'param1': 'value1', 'param2': 'value2'} response = rq.post('https://google.com', PostParams, timeout=2) print(response) Output: <Response [405]> Error 405 (Method Not Allowed) means that the resource does not support this type of request. To check which requests are supported by a resource, you can use the OPTIONS method. OPTIONS The OPTIONS method helps determine which requests the resource will not block. Syntax for OPTIONS: requests.options('URL', optional_arguments) Let's send an OPTIONS request to google.com to find out which methods it supports: import requests as rq response = rq.options('https://google.com', timeout=2) print(response.headers['Allow']) Output: GET, HEAD HEAD A HEAD request returns only the HTTP headers from the server. This is useful when you need metadata about a file or resource without downloading its content. It can also be used for testing purposes. Syntax for HEAD: requests.head('URL', optional_arguments) URL: The resource's address. optional_arguments: Additional arguments, such as a timeout. Example with google.com: import requests as rq response = rq.head('https://google.com', timeout=2) print(response.headers) This will return a list of headers from the server. PUT PUT is used to create a new object or replace an existing one. It is similar to POST but is idempotent, meaning repeated calls with the same data will not change the result. To clarify, imagine a database of usernames and passwords. If a user wants to change their password: POST might add a new record (if no validation occurs). PUT would update the existing record. Syntax for PUT: requests.put('URL', {key: value}, optional_arguments) URL: The resource's address. {key: value}: Parameters, which are automatically included in the request body. optional_arguments: Additional parameters like timeout. Example with httpbin.org: import requests as rq PutParams = {'param1': 'value2', 'param2': 'value2'} response = rq.put('https://httpbin.org/put', data=PutParams, timeout=2) print(response.status_code) Output: 200 PATCH PATCH is used for partial updates to a resource, such as changing a token or specific piece of data. Syntax for PATCH: requests.patch('URL', {key: value}, optional_arguments) Example with httpbin.org: import requests as rq PatchParams = {'param1': 'value2', 'param2': 'value2'} response = rq.patch('https://httpbin.org/patch', data=PatchParams, timeout=2) print(response.status_code) Output: 200 DELETE The DELETE method is used to remove an object from the resource. Syntax for DELETE: requests.delete('URL', {key: value}) URL: The resource's address. {key: value}: Parameters representing the data to be deleted. Example with httpbin.org: import requests as rq DelParams = {'param1': 'value2', 'param2': 'value2'} response = rq.delete('https://httpbin.org/delete', data=DelParams, timeout=2) print(response.status_code) Output: 200 Response Object As shown in the examples, the Response object in the Python Requests library has many methods and properties. Below is a list of them with brief descriptions: apparent_encoding — The encoding detected by charset-normalizer. close() — Closes the connection to the server. content — Returns the received data in bytes. cookies — Returns cookies. elapsed — Returns the elapsed time of the request. encoding — Specifies the encoding for decoding the response content. headers — Returns the headers of the resource. history — Returns the redirection history. is_permanent_redirect — Checks for permanent redirects. is_redirect — Checks if a redirect occurred. iter_content() — Returns the content in chunks. iter_lines() — Returns the content line by line. json() — Returns the response in JSON format. links — Returns the links in the response headers. next — Returns the next PreparedRequest. ok — Returns True if the request was successful, False if not. raise_for_status() — Raises an HTTPError exception if the request failed. reason — Returns a textual explanation of the response. request — Returns the PreparedRequest object. status_code — Returns the HTTP status code. text — Returns the response in Unicode. url — Returns the URL of the resource. Conclusion In this material, we explored the basic elements of the Requests library. If you want to learn more, the official documentation of the Python Requests library provides all the necessary details. And to test your scripts, you can use Hostman VPS.
18 October 2024 · 8 min to read
Python

How to Add Elements to a List in Python

In many programming languages, arrays are used as the primary structure for storing data. An array is an ordered set of elements of the same data type. However, not all programming languages have arrays. Specifically, in Python, lists are used instead of arrays. A list is a data structure for storing objects of various data types. In a sense, it can be considered a "dynamic" array: Python lists impose almost no limits on the number of items (the maximum size depends on the sys.maxsize parameter and the operating system's bitness) or the types of those items. In this article, we’ll explain how to add items to a Python list. Re-declaration The simplest and most "crude" way to add an element to a list in Python is to re-declare the object: example_list = [10, 11, 12] print(example_list) example_list = [10, 11, 12, 13] print(example_list) Output: [10, 11, 12] [10, 11, 12, 13] This method isn't really worth focusing on and is only useful if you’ve forgotten all other alternatives. The append() Method The append() method will help if you need to add a new element to a Python list. The new object is added at the end. Here is the syntax for this method: AppendList.append(object) Where: AppendList is the list to which the element is being added; object is the new object. Here's an example of adding an element to the end of a Python list using append(): AppendList = [11, 12, 13] print(AppendList) AppendList.append(14) print(AppendList) AppendList.append('another type') print(AppendList) Output: [11, 12, 13] [11, 12, 13, 14] [11, 12, 13, 14, 'another type'] In Python, you can also add an element to an empty list using append(): AppendList = [] AppendList.append('hostman') print(AppendList) Output: ['hostman'] The new object can even be another list: AppendList = [11, 12, 13] AddList = [14, 15] AppendList.append(AddList) print(AppendList) Output: [11, 12, 13, [14, 15]] Here, we added the list AddList as an object into the AppendList. If you need to add the individual elements of one list to another, you should use the extend() method instead. The extend() Method The extend() method allows you to merge two lists. Here is the syntax for the method: ExtendList.extend(iterable_object) Where: ExtendList is the list to which the elements will be added. iterable_object is the object whose elements will be added to ExtendList. Let's move to a practical example. Here's how to add multiple elements to a Python list using extend(): ExtendList = [11, 12, 13] AddList = [14, 15] ExtendList.extend(AddList) print(ExtendList) Output: [11, 12, 13, 14, 15] The extend() method also works with any iterable objects. What is an iterable object? An iterable object is an object that can return its elements one by one. Lists, tuples, dictionaries, and strings are all iterable objects. Let’s see how extend() works with these types of objects: ExtendList = [11, 12, 13] AddDictionary = {'first': 1, 'second': 2} AddString = 'host.man' AddTuple = (14, 15, 16, 17) ExtendList.extend(AddDictionary) print('Extend with dictionary:', ExtendList) ExtendList.extend(AddString) print('Extend with string:', ExtendList) ExtendList.extend(AddTuple) print('Extend with tuple:', ExtendList) Output: Extend with dictionary: [11, 12, 13, 'first', 'second'] Extend with string: [11, 12, 13, 'first', 'second', 'h', 'o', 's', 't', '.', 'm', 'a', 'n'] Extend with tuple: [11, 12, 13, 'first', 'second', 'h', 'o', 's', 't', '.', 'm', 'a', 'n', 14, 15, 16, 17] Instead of using extend(), you can also use the + operator to achieve the same result: ExtendList = [11, 12, 13] AddList = [14, 15, 16] ExtendList += AddList print(ExtendList) ExtendList = ExtendList + AddList print(ExtendList) Output: [11, 12, 13, 14, 15, 16] [11, 12, 13, 14, 15, 16, 14, 15, 16] The insert() Method To add an element to a Python list at a specific index, you can use the insert() method. This places the element in a user-specified position. Here's the syntax: InsertList.insert(pos, element) Where: InsertList is the list to which the element will be added. pos is the position of the new element. element is the object to be added. Here's how to add an element to the beginning of a list in Python: InsertList = [11, 12, 13] InsertList.insert(0, 10) print(InsertList) Output: [10, 11, 12, 13] Other examples: InsertList = [11, 12, 13] InsertList.insert(1, 'b') print(InsertList) InsertList.insert(4, 'c') print(InsertList) Output: [11, 'b', 12, 13] [11, 'b', 12, 13, 'c'] To add an element to the middle of a list: InsertList = [11, 12, 13] InsertList.insert(len(InsertList)//2, 'a') print(InsertList) InsertList.insert(len(InsertList)//2, 'middle') print(InsertList) Output: [11, 'a', 12, 13] [11, 'a', 'middle', 12, 13] If the index is out of bounds, no error will occur. Python will place the element at the far left or far right: InsertList = [11, 12, 13] InsertList.insert(-20, 'a') print(InsertList) InsertList.insert(20, 'b') print(InsertList) Output: ['a', 11, 12, 13] ['a', 11, 12, 13, 'b'] Concatenation Concatenation is the operation of joining several linear structures, like strings. For instance, concatenating the strings "host" and "man" results in "hostman." Concatenation Using the Asterisk *: ConcatenatedList = [11, 12, 13] new_list = [ConcatenatedList, 14] print(new_list) new_list = [*ConcatenatedList, 14] print(new_list) Output: [[11, 12, 13], 14] [11, 12, 13, 14] As you can see, in the first case, the object itself is added, while in the second case, its content is added. Concatenation Using a Nested Loop: FirstList = [11, 12, 13, 14, 15] SecondList = [16, 17, 18] result = [j for i in [FirstList, SecondList] for j in i] print(result) Output: [11, 12, 13, 14, 15, 16, 17, 18] Concatenation Using itertools.chain(): import itertools FirstList = [11, 12, 13, 14, 15] SecondList = [16, 17, 18] result = list(itertools.chain(FirstList, SecondList)) print(result) Output: [11, 12, 13, 14, 15, 16, 17, 18] Adding Elements Using Slices Slices are used to retrieve a subset of a list, but they can also be used to add or replace elements in a list. The syntax for slices is: SliceList[START_POS:STOP_POS:STEP] Where: SliceList is the list you're working with. START_POS is the index of the first element to include. STOP_POS is the index that marks the end of the slice (not included in the result). STEP is the interval between elements. Here's an example: SliceList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] new_list = SliceList[0:10:2] print(new_list) Output: [0, 2, 4, 6, 8] You can also use slices to add elements to a list by appending or replacing part of it. Here’s the syntax for adding: SliceList[START:] = iterable Where: SliceList is the list to modify. START is the position where new elements will be inserted. iterable is the iterable object whose elements will be added. Example with a String: slice_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] slice_string = 'hostman' slice_list[len(slice_list):] = slice_string print(slice_list) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'h', 'o', 's', 't', 'm', 'a', 'n'] Example with Another List: slice_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] slice_list2 = [10, 11, 12] slice_list[len(slice_list):] = slice_list2 print(slice_list) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Replacing Part of a List Using Slices: odd_list = [1, 1, 3, 3, 5, 5, 7, 7, 9, 9] even_list = [0, 2, 4, 6, 8] odd_list[0:10:2] = even_list print(odd_list) Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Conclusion This material covered various methods for adding elements to a Python list.  Most of the time, the functionality of common methods like extend(), insert(), and append() will be sufficient. However, knowing about other techniques such as concatenation and slices is also useful.
18 October 2024 · 6 min to read
Mail

How to Use Google SMTP Server

SMTP stands for "Simple Mail Transfer Protocol." As the name suggests, it is a protocol for sending and delivering emails to the recipient. What is an SMTP server? An SMTP server is a server responsible for ensuring the proper functioning of the SMTP protocol. Its main role is to act as a relay between the sender and the recipient. The SMTP server performs two essential tasks: Verifies the configuration of the device attempting to send a message and permits it to do so. Sends the message to the specified address and receives a response code. An SMTP server's responsibility ends here — it only handles sending emails. Receiving emails on the recipient's side is managed by other protocols, such as POP3 and IMAP. Basic steps of sending an email: The sender's server gathers the necessary information — such as the sender's and recipient's addresses, along with the message itself containing the required fields. The sender's server identifies the recipient's email provider by analyzing the recipient's email address and requests the IP address of the recipient's mail server. The sender's server receives a response from the recipient's server. If there is no response from the recipient's server, the sender's server will attempt to establish a connection multiple times. If there is still no response, an error code is returned. The standard port for SMTP is 25, but other ports like 465 and 587 are also used for secure SSL connections and mandatory authentication. It's worth noting that some providers block port 25 to prevent spam, so it's a good idea to check this with your provider. For SMTP, you can use cloud servers in almost any configuration. However, if you plan to send large volumes of emails or need to ensure that your emails are not marked as spam, using Google's SMTP server is recommended. Advantages of Using Google's SMTP Server Cost: One of the most obvious advantages is that Google SMTP is entirely free — you only need a Google account to use it. Pre-configured: Setting up and managing a mail server is quite complex and requires theoretical knowledge of network protocols and practical experience with server configuration. Using an external solution like Google's saves a lot of time configuring the server. Backup: You don't need to worry about the server's uptime — if something goes wrong in the middle of the night, Google's team will handle it. Google also takes care of backing up both sent and received emails, saving you the trouble of ensuring the security of valuable or confidential information. Indexing: Another advantage of storing emails on Google's servers is that indexing and searching through emails are powered by Google's computational resources. If you use the same SMTP for Gmail, emails will automatically appear in the "Sent" and "Inbox" folders, keeping everything organized in one place. Spam Protection: One of the biggest challenges with managing your own mail server is preventing emails from being marked as spam. When sending through Google's SMTP server, you can be confident that the email will arrive at the recipient's inbox just like any other Gmail message. Since Google doesn't use the standard port 25 for sending emails, the likelihood of the message being marked as spam or blocked by the recipient's provider is reduced. Disadvantages of Using a Third-Party SMTP Server Data storage on a remote server: One common concern with third-party SMTP servers is that all your communication is stored under Google's control. However, privacy concerns about keeping emails on your own servers are still valid, especially if you are communicating with average users who are unlikely to use their own SMTP servers. Email limits: Google limits the number of emails sent per day to 100. This limit is generally sufficient if you're testing the SMTP sending mechanism or your project doesn't require large volumes of outgoing emails. Setting Up Google SMTP You'll need access to a Google account to set up the Google SMTP service. In most cases, a simple login and password are sufficient. Still, if you have enabled two-factor authentication (which is highly recommended), you must generate an app-specific password. Here are the settings you'll need to configure Google's SMTP server: SMTP Server (Outgoing Mail Server): smtp.google.com SMTP Username: Your full email address SMTP Password: Your Google account password or the app password you generated SMTP Port: 465 Requires TLS/SSL?: Yes Note that Google will automatically overwrite the From header of any email you send via the SMTP server if it doesn't match your default email address. For instance, if you try to send an email from a non-existent address, Google will replace it with your real one. This is standard behavior, but you can adjust this in your email settings. Email Clients Besides sending automated emails using Google's SMTP server, you can also use these settings to connect with email clients like Thunderbird or Outlook. This way, you can send emails without using a browser or Google's standard client. However, to receive emails from your Google account in another client, you'll need to use POP3 or IMAP protocols. These settings are available in the same place as other Gmail mail settings, under the "Forwarding and POP/IMAP" section. Testing Email Sending We'll write a simple PHP script to test the configuration provided above. We'll send the email using the PHPMailer package, which we can install via the Composer dependency manager: composer require phpmailer/phpmailer Next, create a file index.php where we will specify the SMTP server settings and attempt to send a test email. <?php error_reporting(E_ALL); // Show all errors // Include PHPMailer require dirname(__FILE__) . '/vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); // Specify that we are using SMTP $mail->isSMTP(); // Enable debugging output for testing purposes $mail->SMTPDebug = 2; $mail->Debugoutput = 'html'; // Provide the SMTP credentials $mail->Host = 'smtp.gmail.com'; // SMTP host $mail->Port = 587; // SMTP port $mail->SMTPSecure = 'tls'; // Encryption $mail->SMTPAuth = true; // Enable authentication $mail->Username = "[email protected]"; // Your Google account email $mail->Password = "62584jattjjtmxnpwf124"; // App-specific password // Specify sender and recipient information $mail->setFrom('[email protected]', 'Test Sender Hostman); // Sender $mail->addReplyTo('[email protected]', 'First Last'); // Reply-To address $mail->addAddress('[email protected]', 'James Smith'); // Recipient // Subject and content $mail->Subject = 'Hostman: Google SMTP Test'; // Subject line $mail->msgHTML('<h1>Hello, Hostman</h1>'); // HTML content $mail->AltBody = 'This is a plain-text message body'; // Plain-text fallback // Output the result if (!$mail->send()) { echo "Mailer Error:". $mail->ErrorInfo; } else { echo "Message sent!"; } You can use the same script by replacing the credentials and recipients with your own information, including the Reply-To address. Now, execute the PHP script through the browser by loading the page. If everything is set up correctly, you'll see the output of the email being sent. If any credentials are incorrect, PHPMailer will display an error message. Next, open your email client and check if the email has arrived. Everything should work as expected, and you'll also see the email in the Sent folder in your Gmail account. Conclusion In this article, we explored the advantages of using Google's SMTP server, including the free setup and maintenance, reliable backup, and reduced likelihood of emails being marked as spam. Additionally, we wrote a simple PHP script to demonstrate how to send emails via Google SMTP. We also discussed some limitations and drawbacks of using third-party email services. If you decide to set up your own mail server, you can use Hostman's cloud servers. 
18 October 2024 · 7 min to read
Minecraft

How to Install Plugins on Your Minecraft Server

Plugins are essential for enhancing your Minecraft server by introducing new features, commands, and customization options. Bukkit and Spigot are popular platforms that support plugins, allowing server administrators to transform their vanilla Minecraft server into a feature-rich environment. This guide will walk you through the steps for installing and managing plugins, along with explaining how to set up custom server scripts for starting and restarting your server on Linux. Choosing the Right Plugins for Your Server Before installing plugins, it’s crucial to select the right ones that match your server's needs. Here are some steps to guide you: Define the focus of your server: Whether it's survival, creative, minigames, or roleplay, your plugins should match the gameplay style. Find reliable plugins: Visit well-known repositories like SpigotMC and Bukkit’s plugin directories to find safe and well-maintained plugins. Consider performance: Be cautious with performance-heavy plugins, especially if you have limited server resources. Prerequisites for Installing Plugins Before installing plugins on your Minecraft 1.21 server, make sure the following prerequisites are met: Bukkit or Spigot server: Ensure your server is running a compatible Bukkit or Spigot version for Minecraft 1.21, as plugins are not supported on a vanilla server. Server access: You will need SSH access to remotely connect to your Linux server, and SFTP for uploading plugin files. Java 21 installed: Minecraft 1.21 requires Java 21 to run. Ensure that your server has Java 21 installed and properly configured. You can check your Java version with: java -version If you need to install or update Java, use the following command on Ubuntu: sudo apt install openjdk-21-jre Installing Plugins on a Bukkit/Spigot Server After selecting the right plugins, follow these steps to install them on your server: Connect to your server using SSH: ssh username@your_server_ip Navigate to the plugins directory: Move to the plugins directory in your Minecraft server’s root folder. cd /path/to/your/minecraft/server/plugins Download or upload the plugin .jar: You can upload the plugin .jar file via SFTP or use wget to download it directly to the server. For example, to install EssentialsX: wget https://path-to-plugin/EssentialsX.jar Create a start.sh script (if you don't have one already): The start.sh script will handle starting your server. Here’s a basic version: #!/bin/bashcd /path/to/your/minecraft/serverjava -Xms2G -Xmx4G -jar spigot.jar nogui -Xms2G allocates 2 GB of minimum RAM. -Xmx4G allocates 4 GB of maximum RAM. nogui runs the server without the graphical interface. After saving the script, make it executable: chmod +x start.sh Start your server using the script: ./start.sh Restart нour Server with a restart.sh script. To make it easier to restart your server after plugin installation or updates, you can create a restart.sh script. Here’s a version that stops and restarts the server: #!/bin/bash cd /path/to/your/minecraft/server # Stop the server if it's running in a screen session screen -S minecraft -X stuff "stop$(echo -ne '\r')" # Wait a few seconds for the server to shut down sleep 10 # Start the server again java -Xms2G -Xmx4G -jar spigot.jar nogui This script sends the stop command to the server, waits for 10 seconds, and then starts the server again. Ensure the script has the necessary execute permissions: chmod +x restart.sh You can now restart your server with: ./restart.sh Verifying Plugin Compatibility and Version Before installing any plugin, always verify that it is compatible with your version of Bukkit or Spigot: Check plugin version: Ensure the plugin supports your Minecraft version. Verify the plugin’s .jar or plugin.yml file for supported versions. Unzip the plugin and inspect: unzip plugin.jarcat plugin.yml Review the plugin's documentation: Some plugins may have dependencies or specific configurations needed to function correctly. You can check your server version with the following command: /version Managing and Configuring Installed Plugins Once your plugins are installed, many will require configuration to suit your server's needs: Edit configuration files: Most plugins create a folder in the plugins directory with a config.yml or plugin.yml file. You can modify this file using a text editor like nano: nano /path/to/your/minecraft/server/plugins/pluginname/plugin.yml Reload the server or the plugin: After editing the configuration, restart your server using restart.sh or reload the plugin in-game using: /reload Check plugin status: To see which plugins are installed and running, use: /plugins This will display a list of active plugins in-game or via the server console. Common Plugin-Related Issues and Solutions Here are a few common problems and solutions related to plugins: Plugin not loading: Ensure the plugin is placed in the correct plugins folder and is compatible with your Minecraft version. Server crashes: Review the server.log for errors, as a plugin mismatch or missing dependency could be the cause. Incompatible plugins: Some plugins may conflict with others, especially those with overlapping functionalities (e.g., multiple permissions managers). Best Practices for Managing Plugins To keep your server running smoothly, follow these best practices: Limit the number of plugins: Only install plugins that are necessary. Too many plugins can slow down your server and cause lag. Regular backups: Always back up your server before adding or updating plugins to prevent data loss. cp -r /path/to/your/minecraft/server /path/to/backup/location Update plugins regularly: Keep your plugins up to date to maintain compatibility with newer Minecraft versions. Test new plugins locally: Before adding a plugin to your live server, test it on a local server to avoid disruptions. Popular Plugins to Enhance Your Server Here are some highly recommended plugins that can enhance your server: EssentialsX: A comprehensive plugin providing essential server commands. LuckPerms: A flexible and powerful permissions management plugin. WorldEdit: A tool for quickly building and editing large areas of blocks. Vault: A permissions and economy manager, often required by other plugins. Dynmap: Generates a live web map of your Minecraft world. Conclusion With this guide, you now have all the knowledge needed to install, manage, and configure plugins for your Minecraft server. By choosing the right plugins, verifying compatibility, and using custom scripts like start.sh and restart.sh, you can efficiently manage your server and provide an engaging experience for your players.
18 October 2024 · 6 min to read
Go

How to Install and Configure Go on Ubuntu: A Step-by-step Guide

Go, also known as Golang, is a programming language created by Google. It simplifies coding and provides great performance, which makes it popular among developers. Its user-friendly syntax and built-in concurrency support allow developers to efficiently create scalable applications. Moreover, Go is a cross-platform programming language and is available for all major operating systems, including Linux, Windows, etc. In this article, we’ll discuss what Golang is and how to install and use it on Ubuntu. What is Golang? Golang is a simple yet powerful programming language that enables developers to build basic to advanced applications. Go was developed to manage large-scale projects, with a focus on concurrency and clean code. Its scalability and cross-platform compatibility have made it a popular choice among developers. Go is widely used in systems programming, networking, and microservices. Key benefits of Golang include fast compilation, simple syntax, automatic memory management, and tools like go fmt and go test. Prerequisites for Installing Go on Ubuntu To install the Go language on Ubuntu, the below-listed requirements must be fulfilled: Ubuntu must be pre-installed. A user with root or sudo privileges. If a user fulfills the prerequisites, he can proceed with the installation of Go on Ubuntu. Method 1: Installing Golang on Ubuntu via the Default Package Manager Apt is the default package manager of Ubuntu. Installing Golang through the default package is the most convenient way. However, it’s important to note that the version installed via Ubuntu's default package manager may not always be the latest. Let’s go through the below-listed steps to install Go on Ubuntu through apt: Updating and Upgrading System Repositories Before installing Golang on Ubuntu, it is recommended to update and upgrade the system repositories to ensure we have the latest package information: sudo apt update && sudo apt upgrade -y Installing Go Using apt Now run the command below to install Go on Ubuntu using the default package manager: sudo apt install golang-go -y The installation process for Golang on Ubuntu may take a while to complete.  Verify Go Language Installation Finally, confirm the Golang installation on Ubuntu by checking its version: go version The output indicates that the go version go1.22.2 has been installed successfully: Uninstall Go from Ubuntu If Golang is no longer needed, uninstall it from Ubuntu by executing the following command: sudo apt remove golang-go -y It's recommended to remove unnecessary dependent packages, as they can take up extra space. To do this, simply execute the below-given command: sudo apt autoremove Method 2: Installing Golang Using wget To install the Go programming language on Ubuntu from the official source, users can use the wget command. This command downloads the latest Golang binary package from the official website.  Let’s go through the step-by-step process below to download and install Golang on Ubuntu using the wget command. Download and Install Go Language First, open a browser and navigate to the Go language’s official All Releases page. Scroll down to select an appropriate binary package under the stable version. Copy the link address of the selected binary package: Now specify the copied link address with the wget command, as shown below: wget https://go.dev/dl/go1.23.2.linux-amd64.tar.gz -O golang.tar.gz Here, the -O option is used to specify an output file name. For instance, the above command downloads the Golang binary package and saves it as golang.tar.gz: After this, use the tar command to extract the downloaded package: sudo tar -xzvf golang.tar.gz -C /usr/local Set Up the Go Environment Configuring the PATH variable for Golang allows access to Go commands and tools from any directory on the system. For this purpose, the Go binary paths need to be added to the PATH environment variable: echo export PATH=$HOME/golang/bin:/usr/local/go/bin:$PATH >> ~/.profile Next, execute the following command to apply the changes made to the profile file: source ~/.profile Verify Go Installation Once the Go environment is configured, execute the command below to check if Go has been successfully installed: go version Configure the $GOPATH and $GOROOT (Optional) In Golang, the default workspace directory is ~/go, and the environment variable $GOPATH refers to this location. However, users can customize this workspace by setting the $GOPATH environment variable in their ~/.profile, ~/.bashrc, or ~/.zshrc files: export GOPATH=$HOME/golangExamples This command will set the workspace directory to ~/golangExamples. Moreover, users can also set $GOROOT to override the default Go installation path. However, this is usually not necessary: export GOROOT=/usr/local/go Finally, execute the command below to apply the changes: source ~/.profile Users can customize the $GOPATH and $GOROOT environment variables, however, it is not recommended to change them unless you have a specific reason. Remove Go From Ubuntu If Golang is downloaded using the wget command and now needs to be removed, simply run the command below: sudo rm -rf /usr/local/go This command will permanently remove the Go language from Ubuntu.  How to Use Go Programming Language on Ubuntu? Once the Go programming language is installed on Ubuntu, we can use it to fulfill our programming needs, such as creating applications, and web services, handling concurrent tasks, etc.  You can use any text editor, like nano, to create a new file and save it with a .go extension: nano exampleCode.go After creating a go file, paste the following code into it to print a "Welcome to hostman.com" message on the terminal: package main import "fmt" func main() { fmt.Println("Welcome to hostman.com") } Save the code, close the nano editor, and then run the command below in the terminal to execute the Go program: go run exampleCode.go The output shows that the "Welcome to hostman.com" message is successfully displayed in the Ubuntu terminal, which confirms that the Golang program has been executed correctly: That’s all about installing, configuring, and using the Go programming language on Ubuntu. Conclusion Golang is a cross-platform programming language best known for its easy-to-use syntax, concurrency support, and scalability. Key benefits of Golang include fast compilation, simple syntax, and built-in tools like go fmt and go test, etc. These features make Golang a perfect choice for building efficient applications. In this article, we explored two methods to install Golang on Ubuntu. The first method uses the default package manager (apt). The second method involves downloading via wget. Choose any of the discussed methods to install the Go language and start using it to develop scalable applications on Ubuntu.
18 October 2024 · 6 min to read
Network

A Complete Guide to the nslookup Command in Linux and Windows

The nslookup command is a widely used tool for querying Domain Name System (DNS) records. It helps network administrators troubleshoot DNS-related issues by allowing them to perform a range of lookups, from finding IP addresses associated with domain names to querying specific DNS servers. This tutorial will guide you through the basics of using nslookup on both Linux and Windows platforms. In this tutorial, you will learn: Basic syntax and options of nslookup How to perform simple DNS queries Retrieving mail exchange (MX) records Performing reverse DNS lookups Querying specific DNS servers Using non-interactive mode By the end of this tutorial, you will be familiar with the most common and useful nslookup commands for effective DNS troubleshooting. Basic Syntax and Options for nslookup The basic syntax for the nslookup command is straightforward: nslookup [options] [domain] Here is a breakdown of the commonly used options: No parameters: Opens an interactive mode where you can enter multiple queries [domain]: Performs a DNS lookup for the specified domain name -type=[record_type]: Specify the type of DNS record to query (e.g., A, MX, AAAA, etc.) [server]: Specify a DNS server for querying instead of using the default system server For example: nslookup example.com This command performs a DNS lookup for "example.com" using your default DNS server. Common Options for nslookup -query=A: Query the IP address (default record type) -query=MX: Retrieve mail exchange records -query=AAAA: Query for IPv6 addresses -timeout=[seconds]: Set a timeout for the response -debug: Show detailed information about the query process How to Perform a Simple DNS Query One of the most common uses of nslookup is to resolve domain names to IP addresses. Step-by-Step Guide to Performing a Simple DNS Query Open the terminal or command prompt. Type the nslookup command followed by the domain name: nslookup google.com Output: In this example, the DNS server at 8.8.8.8 (Google's public DNS server) returned the IP address 142.250.65.238 for google.com. Using nslookup to Retrieve MX Records The mail exchange (MX) records for a domain indicate which mail servers are responsible for receiving emails on behalf of that domain. To retrieve the MX records using nslookup: Use the -type=MX option to specify that you want to retrieve MX records.     nslookup -query=MX gmail.com The output will list the MX records, including the mail servers and their priority: Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: gmail.com mail exchanger = 20 alt2.gmail-smtp-in.l.google.com.. gmail.com mail exchanger = 10 alt1.gmail-smtp-in.l.google.com. In this case, the mail servers for gmail.com are listed along with their priorities. The lower the number, the higher the priority. Performing Reverse DNS Lookups A reverse DNS lookup translates an IP address back to its associated domain name. This is useful for identifying the domain that corresponds to a given IP address. To perform a reverse DNS lookup, input the IP address into the nslookup command: nslookup 142.250.65.238 The output should display the domain name associated with the IP: Non-authoritative answer: 238.65.250.142.in-addr.arpa name = lga25s73-in-f14.1e100.net. In this example, the IP 142.250.65.238 resolves back to lga25s73-in-f14.1e100.net, which is part of Google's infrastructure. Querying Specific DNS Servers By default, `nslookup` uses the system's configured DNS server to perform queries. However, you can specify a different DNS server if needed. To query a specific DNS server, append the server's IP address to the command: nslookup example.com 1.1.1.1 The command will query the 1.1.1.1 DNS server (Cloudflare's DNS) for the domain example.com: Server: 1.1.1.1 Address: 1.1.1.1#53 Non-authoritative answer: Name: example.com Address: 93.184.215.14 This allows you to test DNS resolution from different servers. Using Non-Interactive Mode in nslookup In non-interactive mode, you can issue multiple queries without entering nslookup's interactive shell. This is useful when scripting or automating tasks. To use nslookup non-interactively, simply pass the domain name and the server (optional) in one command: nslookup example.com 8.8.8.8 The response will be printed directly, without entering the interactive shell: Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: Name: example.com Address: 93.184.215.14 This method is efficient when you need to quickly query DNS records without additional input. Conclusion The nslookup command is a powerful and flexible tool for performing DNS queries. Whether you're troubleshooting domain resolution, retrieving MX records, or performing reverse lookups, nslookup is an essential command for network administrators. By mastering the options and syntax, you can use nslookup effectively on both Linux and Windows systems. To recap, here’s what we covered in this tutorial: Performing simple DNS queries Retrieving MX records Conducting reverse DNS lookups Querying specific DNS servers Using non-interactive mode
18 October 2024 · 4 min to read
Python

How to Install Python on Windows 10

Python is a high-level programming language used by millions of programmers and developers. It is intuitive, offers many useful tools and libraries, and is essential for working with and analyzing large datasets. However, Python is not pre-installed on Windows operating systems. This guide will walk you through installing Python on Windows 10. Which Version to Choose There are two main versions of Python: Python 2 and Python 3, and they are patible. Python 3 was released in 2008 to address issues found in Python 2. It offers more straightforward, intuitive syntax, a wide range of useful libraries (especially for data analysis), and a large community supports it. Python 2 is no longer supported, unlike Python 3. Therefore, for new projects, you only need Python 3. However, if you need to work on projects written in Python 2, you might still need this version, so we will also explain how to install it. How to Install Python 2 To install Python 2 on Windows 10: Open your browser and go to the official website python.org. Go to the Downloads section. In the Downloads section, find the section for specific releases and locate the version you need. The last Python 2 release is 2.7.18. Click on Download and check the related files. For your operating system, download the 64-bit installer (it is the last file in the list). Once the file is downloaded, open it. Before starting the installation, the installer will allow you to choose the installation path and additional tools. Select the necessary options and start the installation. How to Install Python 3 on Windows There are several ways to install Python, each with its own features, advantages, and disadvantages: Full Installation: Installs all components of Python, which is ideal for most projects. Microsoft Store Installation: Suitable for development environments and running scripts. NuGet Package Installation: Python comes as a ZIP file with the .nupkg extension, designed for continuous integration systems. It does not include the user interface. Ideal for building packages and running scripts. Embeddable Package: Installs a minimal version of Python, often used as part of a larger application or project. Full Installation Using the Official Installer The steps for installing Python 3 from the official website are similar to those for Python 2. Here’s how to install Python 3 on Windows 10: Open your browser and go to python.org. Go to the Downloads section. Click on Download Python x.x.x (the latest version). Once you click it, the installer will start downloading. After downloading, open the installer. If Python 3 is already installed, the installer will offer to update it to the version you just downloaded. If Python is not installed, it will offer a fresh installation. Make sure to check the following options: Installing for all users. Add Python to PATH (this allows you to use Python from the command line). There are two installation options: Install now: Administrator rights are not required. Python will be installed in your user directory. Standard libraries, test suites, a launcher, and pip will be installed. Customize Installation: May require administrator rights. Python will be installed in the Program Files directory. Additional features can be installed. The Python standard library can be precompiled into bytecode. Choose the option that suits you and start the installation. After it finishes, disable the MAX_PATH length limitation to avoid errors related to file path length. To check if the installation was successful, run the command python --version in the command line. If everything went well, you should see an output like this: Python 3.10.8 Python is now installed and ready to use. Installing Python via Microsoft Store To install Python from the Microsoft Store: Open the Microsoft Store application. In the search bar, type Python 3.x, specifying the version you want (e.g., "Python 3.10"). Click Get. The download and installation will begin automatically. Installing Python Using NuGet To install Python on Windows via NuGet: Go to the official website and navigate to the Downloads section. Select the recommended version and download it. After opening the downloaded file, installation will take just a few seconds. To install Python, open Windows PowerShell and run the following commands: For the 64-bit version: nuget.exe install python -ExcludeVersion -OutputDirectory For the 32-bit version: nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory Embeddable Package The embeddable package provides a minimal Python environment. It is distributed as a ZIP file and is intended to integrate Python into larger applications. The embeddable package is not designed for direct user access. You will have a fully isolated Python environment when extracted from the archive. It will be isolated from the user’s operating system, including environment variables (like PATH), the system registry, and any installed packages. The standard Python library is included in the embeddable package as compiled and optimized files. However, this version does not include a package manager (pip) or documentation. You can download the embeddable package from the python.org website: Go to the Downloads section. Clicking on Download will download the regular version, so click the hyperlink for Python for Windows instead. Click Latest Python 3 Release - Python x.x.x. Scroll down to the Files section and choose one of the embeddable versions (for 64-bit or 32-bit systems). Conclusion This guide has covered various methods for installing Python on Windows 10. For more useful Python resources, you can explore our tutorials. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
18 October 2024 · 5 min to read
Linux

How to Use DNF to Manage Packages on CentOS

DNF (Dandified Yum) is the next-generation version of Yum, the default package manager for CentOS and Fedora distributions. It is designed to resolve dependencies more efficiently, handle larger package sets, and improve performance over its predecessor. DNF simplifies the management of software packages by allowing users to install, update, and remove packages from the command line with a user-friendly interface. Installing and Removing Packages with DNF One of the primary functions of DNF is installing and removing software packages. To install a package using DNF, you need root or sudo privileges. The syntax is straightforward: sudo dnf install package_name For example, to install the Apache HTTP server: sudo dnf install httpd To remove a package, the command is similar: sudo dnf remove package_name For example, to remove Apache HTTP server: sudo dnf remove httpd Updating and Upgrading Packages Keeping your system up to date is essential for security and performance. DNF makes this process simple. To update all the packages on your system, use: sudo dnf update This command will update installed packages to the latest versions available in the configured repositories. If you want to upgrade your entire system to the latest release (such as when moving between CentOS versions), you can use: sudo dnf upgrade The difference between update and upgrade is that the latter will also remove obsolete packages, whereas update does not. Searching for Packages in DNF DNF allows users to search for packages before installing them. This is helpful if you're unsure of the exact package name or want to explore available options. To search for a package: sudo dnf search <keyword> For example, to search for packages related to Apache: sudo dnf search apache DNF will list all packages that match the search term, along with a brief description. Managing Repositories with DNF Repositories are essential for managing where DNF pulls its packages from. DNF automatically handles repository configuration files, usually located in /etc/yum.repos.d/. You can add, enable, or disable repositories with DNF. To add a new repository, you need to create a .repo file in /etc/yum.repos.d/. For example, let's say you want to add the EPEL (Extra Packages for Enterprise Linux) repository, which provides additional packages not available in the default CentOS repositories. Install the EPEL repository using DNF EPEL is available as a package that can be installed directly: sudo dnf install epel-release This command automatically creates the necessary .repo file and enables the EPEL repository. Manually adding a repository If you want to manually add a repository, you would create a .repo file, for instance, myrepo.repo, in /etc/yum.repos.d/, and add the following content: [myrepo]name=My Custom Repobaseurl=http://example.com/repo/centos/$releasever/$basearch/enabled=1gpgcheck=1gpgkey=http://example.com/repo/RPM-GPG-KEY-myrepo Here: name specifies the name of the repository. baseurl defines the URL from where the packages will be downloaded. enabled=1 ensures the repository is active. gpgcheck=1 enables GPG key checking for security. gpgkey provides the URL to the GPG key used to verify the packages. To disable the epel repository: sudo dnf config-manager --set-enabled epel To enable it again: sudo dnf config-manager --set-enabled epel Cleaning Up Unused Packages Over time, your system may accumulate unnecessary packages and cache files, which take up valuable space. DNF includes a built-in command to clean up unused packages and free up disk space: sudo dnf autoremove This will remove any orphaned packages that are no longer required by the system. Additionally, you can clean up cached data using: sudo dnf clean all This command clears all cached package files stored in /var/cache/dnf/. Troubleshooting DNF Issues Occasionally, you may encounter issues when managing packages with DNF. Common problems include broken dependencies or repository errors. Here are some troubleshooting tips: Broken dependencies: If you're facing dependency issues, try running: sudo dnf install --best --allowerasing This command attempts to resolve conflicts by allowing DNF to erase conflicting packages. Corrupted cache: If the cache becomes corrupted, clean it up using: sudo dnf clean metadata Failed transactions: If a DNF transaction fails, try rebuilding the database: sudo rpm --rebuilddb By using these tips, you can quickly resolve most issues you might face with DNF. Conclusion DNF is a powerful and efficient package manager that makes software management on CentOS easy. From installing and updating packages to managing repositories and cleaning up unused files, DNF provides a wide range of features to ensure your system runs smoothly. With this guide, you should be well-equipped to handle package management tasks on your CentOS system.
18 October 2024 · 4 min to read

Answers to Your Questions

Which operating systems are supported on your cloud servers?

Choose popular server operating systems and deploy them in one click: from Ubuntu to CentOS. Licensed operating systems are available directly in the control panel.

How can I get started with a cloud server? Is there a straightforward registration process?

Register with Hostman and choose the tariff that suits your needs and requirements. You can always add processing power and purchase additional services if needed.

You don't need a development team to start shared hosting - you'll do everything yourself in a convenient control panel. Even a person with no technical background can easily work with it.

What is the minimum and maximum resource allocation (CPU, RAM, storage) available for cloud servers?

The starter package includes a 1×1.28 GHz 1-core CPU, 1 GB RAM, 15 GB fast MVNe SSD, dedicated IP address and 200 Mbps. For demanding users, go for a powerful 8×3.3 GHz server, 16 GB RAM, 160 GB fast MVNe SSD, dedicated IP address and 200 Mbps. Alternatively, you can always get an incredibly powerful server by configuring it yourself.

What scaling options are available for cloud servers?

You can easily add power, bandwidth, and channel width with just a few clicks directly in the control panel. With Hostman, you can enhance all the important characteristics of your server with hourly billing.

How much does a cloud server cost, and what is the pricing structure like?

Add capacity, bandwidth and channel width with a few clicks right in the control panel. With Hostman, you can improve all important features of your server - with hourly billing.

Is there a trial or testing period available for cloud servers before purchasing?

Contact the friendly Hostman support team, and they will offer you comfortable conditions for test-driving our cloud server — and will transfer your current projects to the cloud for free.

What security measures and data protection are in place for cloud servers?

Cloud servers are hosted in a Tier III data center with a high level of reliability. Hostman guarantees 99.99% availability according to the SLA, with downtime not exceeding 52 minutes per year. Additionally, data is backed up for extra security, and the communication channel is protected against DDoS attacks.

What level of support is provided for cloud servers?

Hostman support is always available, 7 days a week, around the clock. We respond to phone calls within a minute and chat inquiries within 15 minutes. Your questions will always be handled by knowledgeable staff with sufficient authority and technical background.

Can I install my own software on a cloud server?

Yes, absolutely! You can deploy any software, operating systems, and images you desire on your server. Everything is ready for self-configuration.

What backup and data recovery methods are available for cloud servers?

Hostman takes care of the security of your data and backs up important information. Additionally, you can utilize the automatic backup service for extra safety and reliability.

Is there a guaranteed Service Level Agreement (SLA) for cloud server availability?

Hostman guarantees a 99.99% level of virtual server availability according to the SLA (Service Level Agreement).

Which data center locations are available for hosting cloud servers?

Our servers are located in a modern Tier III data center in the European Union and the United States.

Can I create and manage multiple cloud servers under a single account?

Certainly, you can launch multiple cloud servers and other services (such as databases) within a single account.

What is the deployment time for cloud servers after ordering?

With Hostman, you'll get a service that is easy and quick to manage on your own. New cloud servers can be launched almost instantly from the control panel, and the necessary software can be installed within minutes.

What monitoring and notification capabilities are offered for cloud servers?

Hostman specialists monitor the technical condition of servers and software around the clock. You won't have to worry about server availability — it will simply work, always.

Can I modify the specifications of my cloud server (e.g., increase RAM) after creation?

You can easily configure your server by adding resources directly in the control panel. And if you need to switch to lower-tier plans, you can rely on Hostman support — our specialists will handle everything for you.

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