Search

Python's Articles

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability with its notable use of significant whitespace.

Best Practices for Node.js Development: Tips and Tricks
Many developers nowadays prefer the Node.js framework to build websites and applications. Node.js is an advanced PHP framework that many big tech giants are using. Therefore, due to this change in the software landscape, there is a huge demand for Node.js framework to build web projects. The development of applications has been simplified by Node.js and its modules. Since Node.js allows developers to create applications both on the client and server simultaneously, it is highly versatile. However, creating and hosting applications are both different, as online scalability is totally dependent on what kind of infrastructure you use. MilesWeb is the leading Nodejs hosting provider offering compelling features and IT resources.  There are over a quarter of a million modules available in this framework. A Node.js application can be developed quickly and easily scaled thanks to its simplicity. Apart from Node JS one more popular web framework is Python. Several expert Python developers use the Python framework and their advanced version. We know that many of you will have the concern about which is suitable between Node js vs Python. For that, we recommend you to refer to online guides. Understanding the Mighty Event Loop  Node.js is so fast and brilliant because of the event loop. Because of this, it helps in utilizing the time efficiently or else it would have been wasted while waiting for input and output tasks to complete. If your Node.js application needs to do a CPU-intensive activity, such as computing, hashing passwords, or compressing, you'll also need to investigate possibilities for postponing the operation with setImmediate() or setTimeout in addition to the standard chore of spawning new processes for CPU-tasks. (). On the subsequent event loop cycle, the code in their callbacks will run again. Unfortunately, despite its name, nextTick() operates on the same cycle. Use Built-In Debugger  Debugging Node.js applications with the help of IDE integration in languages like Java or C# is a challenging task. Many Node.js developers are using the debugging pattern by making most of the console.log.  Apart from this, there are alternative methods also to debug Node.js applications. The essential one is Node.js is comprised of with own built-in debugger that runs by calling node to debug. Another interesting tool to debug Node.js apps is Node Inspector. Many branded tools are also available, but Built-In Debugger and Node-inspector have some interesting features, like live code changing, step debugging, and scope injection. Use npm Scripts To build, test, and even start the app, developers need to create npm scripts. Nowadays, it has become a standard option for testing Node.js applications. In fact, many developers look for this element while taking on new Node.js projects.  While developing front-end applications, there might be a scenario you have come across that is to run two or more processes to rebuild the code. For instance, you want to code for Webpack and nodemon. It is easy to achieve with the help of && (in the npm script) because the first command will not release the prompt. A module called Concurrently can handle this situation by spawning multiple processes at the same time. To avoid conflicts, you can also install development command-line tools locally, such as Webpack, nodemon, gulp, and Mocha.  Nodefly to Gauge the Performance Once the development process is completed, it the time to check its efficiency. Developers need to ensure all of their performance measures to check whether apps are running at an optimum speed or not. It is a logical step for any developer to monitor the node.js app's performance and profile. Nodefly is a service that allows developers to monitor the performance and profile of apps.  Nodefly will start to monitor the application for issues like memory leaks and measure how long it takes for Redis, mongo queries, and other essential stuff.  Lowercase is a king File names should match class names, of course. Files must, however, be lowercase. Some operating systems support both myclass.js and myclass.js, but Linux, for example, cannot. If you use lowercase in your Node.js code, you can reduce the time it takes to develop. Cluster your app It is important to be aware of the Node execution time limits, which lead to a huge waste of resources. Cluster support gives flexibility to developers to run the process on very little hardware.  Look deeper Node.js coding should be speed up by addressing the root cause, not just the surface level. The machine may be weak, the code may be flawed, or automatic scaling is not implemented. Identify the problem first and then determine how to proceed. You should also register the application's behavior, which will aid you in understanding the problem.
How to Create Python Virtual Environments on Ubuntu
Sometimes we have more than one project running in one machine and sometimes they require same package with different version. In that case, installing package with one version will crash other project that require different version of the package. And that is why we need Virtual Environment. Virtual environment is tool that creates separate environment for separate project. virtualenv is Python module that allows to create Virtual Environment for Python projects which could break system tools or other projects. All Python packages are called as Python module. This article will share you details how to create virtual environment for python. Requirement You need to have non-root user account logged in with sudo privileges to set up on your server. Pip installed which will install Python modules. We will install Python3 modules in this article. Step 1. Install virtualenv Open the terminal by using the CTRL+ALT+T keyboard shortcut or by running a search in Ubuntu Dash. Now run any of the following command to install virtual environment. sudo apt-get install python3-virtualenv or python3 -m pip install virtualenv or pip3 install virtualenv You can check environment version by running following command: virtualenv --version Step 2. Create Virtual Environment Run any of the following command to create virtual environment: python3 -m venv newenv or virtualenv -m newenv This will create Virtual Environment folder named newenv. This folder is the Virtual Environment and all Python modules for this environment will install in this folder. Step 3. Activate Virtual Environment Use this command to activate virtual environment source newenv/bin/activate This will prefix environment name in Terminal window when you activate Virtual Environment like this: (newenv) root@root-host:~#  Step 4. Install Python modules for specific Virtual Environment. When you have Virtual Environment activated and you install new Python modules, it will be installed for that specific environment only. It will not affect Python modules installed Globally. Install Python modules with Pip with running command: pip3 install <package_name> Step 4. Deactivate virtual Environment If you need to deactivate environment, run bellow command: deactivate Conclusion So now you have created virtual environment named newenv. You can create as many Virtual Environment as you want with any name.
How to Install Python Pip on Ubuntu
Pip is Python package manager command line tools that makes python packages easy to download from Python Package Index (PyPI). In the sense Pip is like package manager as Ubuntu has apt and programming languages like PHP has composer, node.js has npm. This article is intended to guide you installing Pip on Ubuntu system. If you want to download pip for Python3, then you have to be installed Python3 and in the way, also Pip for Python2. To check which version of Python you have installed, use following command. python --version python2 --version python3 --version Note: You need to be logged in as root user with sudo privileges. 1. Open your terminal, by pressing shortcut key CTRL + ALT + T or go to menu and click Terminal. 2. Update your package list by following command: sudo apt-get update 3. If you want to install pip for Python3 run following command, sudo apt-get install python3-pip For Python2, run command sudo apt-get install python-pip 4. Check Pip for Python3 version pip3 --version pip3 -V or Pip for Python2 version pip --version pip -V Some important Pip commands. Note: for Pip for Python2 use pip word instead of pip3 1. To get all your installed packages, run command pip3 list 2. Search for packages pip3 <package-keyword> 3. Installing packages from Pip. pip3 install <package-name> 4. Uninstalling package commmand. pip3 uninstall <package-name> 5. To get more option, run command pip3 --help Conclusion So this way, you can manage your python packages. You can visit pip documentation site to get more information.
Python Numpy Array Tutorial Part 2
In the first part, we have discussed what is Numpy package, how to install and how to use it. In this part we will discuss about basic Numpy array functions of Numpy. If you have not read first part, I will recommend to check it. First of all, we will import numpy package in the file and then create a Numpy array, on which, we will perform basic array function. import numpy as np # create numpy array x = np.array([[1, 2, 3],               [4, 5, 6],               [7, 8, 9]]) # print array print(x) And then from the Terminal go to file location and execute the file with bellow command. python index.py It will run the script and print the array. Basic functions Let's first work with array functions ndarray.shape Returns the shape of the array print(x.shape) >>> (3, 3) ndarray.ndim returns number of dimentions of the array print(x.ndim) >>> 2 ndarray.itemsize returns byte size of each elements of the array print(x.itemsize) >>> 8 ndarray.dtype returns type of array elements print(x.dtype) >>> int64 ndarray.size returns total number of elements of the array print(x.size) >>> 9 We can access the array by its indexes. Numpy index starts from the 0. Get first indexed element print(x[0]) >>> [1 2 3] Get between two indexed elements including first index print(x[0:2]) >>> [[1 2 3]      [4 5 6]] Get elements from the first indexed print(x[1:]) >>> [[4 5 6]      [7 8 9]] Get elements from the reverse print(x[-1:]) >>> [[7 8 9]] Adding or deleting elements from the array. Add the elements to your array and create new array x = np.append(x, [1, 2]) print(x) >>> [1 2 3 4 5 6 7 8 9 1 2] Remove the elements of the position and create new array x = np.delete(x, 1) print(x) >>> [1 3 4 5 6 7 8 9] Sort the elements in the array x = np.sort(x) print(x) [[1 3 9]  [1 4 6]  [7 8 9]] Reshape the array columns and rows x = x.reshape(1, 9) print(x) >>> [[1 9 3 4 5 6 7 8 9]] Now let's see how to create numpy array with other methods Create array with arrange() and reshape() method x = np.arange(15).reshape(3, 5) >>> print(x) >>> [[ 0  1  2  3  4]      [ 5  6  7  8  9]      [10 11 12 13 14]] Create array with all zero elements x = np.zeros((2, 2)) >>> print(x) >>> [[0. 0.]      [0. 0.]] Create array with all elements with 1 value x = np.ones((2,3)) >>> [[1. 1. 1.]      [1. 1. 1.]] Create array with constant value x = np.full((2, 3), 3) >>> print(x) >>> [[3 3 3]      [3 3 3]] Create sequance array with 4 up to 20 x = np.arange(0, 20, 4) >>> print(x) >>> [ 0  4  8 12 16] create an array with values that are spaced linearly in a specified interval: x = np.linspace(0, 8, 5) >>> print(x) >>> [0. 2. 4. 6. 8.] In the next part, we will discuss more about basic operations on Numpy array.
Python Numpy Array Tutorial
Python is the most popular general purpose programming language used in machine learning, data science, web application etc. Python has so many packages for machine learning, data-science and data analysis like, Matplotlib, Pandas, SciPy, Tensor-Flow, Keras etc. One of the basic package is Numpy. Numpy is the basic package to manipulate data in Python. Numpy provides support for large, multi-dimensional arrays,  various derived objects(such as masked arrays and matrices), for scientific calculation in linear algebra and matrices.Numpy is largely used in all machine-learning packages like Matplotlib, Pandas, SciPy, Tensor-Flow, Keras etc. Numpy is not preinstalled with Python. You have to install Numpy addtionally. In this article, we will discuss about installation and how to use Numpy. Installation Linux and Mac users can directly install Numpy with pip command. pip install numpy To Install Numpy in Windows system, download Anaconda which is open-source distribution of the Python and R programming languages including Numpy and many popular packages. You can check if Numpy is installed correctly by running bellow command. It will display all your pip installed packages. pip list How to Use? Whenever you want to use Numpy in your script, first import Numpy module in above the script. import numpy as np Now you can use all Numpy functions. Lets first create simple Numpy array. For that first create file index.py file and put bellow code which will print array variable. import numpy as np # create numpy array x = np.array([[1, 2, 3],               [4, 5, 6],               [7, 8, 9]]) # print array print(x) Now go to Terminal in the file location and run script with bellow command. python index.py Conclusion This way, you can run Python script from your Terminal. In the next part, we will discuss on Basic functions to create and manipulate Numpy array.
Python String Splitlines Method
Python splitlines() is an inbuilt method that returns a list when there is a line break in the string. It breaks the string at line boundaries and returns the split strings in the form of a list. There are different types of line breaks. For example \n(newline), \r(carriage return), \r\n(carriage return+new line) and many more. Python String splitlines() Python splitlines() function is used to split the lines at line boundaries. The splitlines() returns a list of lines in the string, including the line break(optional). Syntax string.splitlines([keepends]) Here the string is the primary string variable, which will be split using the splitlines() method. keepends (optional): It is an optional parameter. When set to True, the line breaks are included in the resulting list. This can be a number, specifying a position of a line break or, can be any Unicode characters, like “\n”, “\r”, “\r\n”, etc. as boundaries for strings. The splitlines() method takes an optional parameter keepends, which take values as True and False. If the value is True, then the line break statements are also included in the returning list otherwise not. Return value It returns a list consisting of the elements of the main string with different elements breaking at line boundaries in the main string. See the following code. # app.py h1 = 'Hello boy\n' h1.splitlines(True) print(h1) Output ➜ pyt python3 app.py Hello boy ➜ pyt Example programs on splitlines() method in python # app.py h1 = "Hello I am\n a\n geek!" h2 = "Python\nC++\nC\nJava\nKotlin" h3 = "Virat Kohli \nis \nthe best" h4 = "India is the best" h5 = "I love chinese\r food!!" print("Splitted list: ", h1.splitlines(), "\n") print("Splitted list: ", h2.splitlines(), "\n") print("Splitted list: ", h3.splitlines(), "\n") print("Splitted list: ", h4.splitlines(), "\n") print("Splitted list: ", h5.splitlines(), "\n") Output ➜ pyt python3 app.py Splitted list: ['Hello I am', ' a', ' geek!'] Splitted list: ['Python', 'C++', 'C', 'Java', 'Kotlin'] Splitted list: ['Virat Kohli ', 'is ', 'the best'] Splitted list: ['India is the best'] Splitted list: ['I love chinese', ' food!!'] ➜ pyt Example 2: Write a program by passing parameters in the splitlines() method in python and show the output. # app.py h1 = "Hello I am\n a\n geek!" h2 = "Python\nC++\nC\nJava\nKotlin" h3 = "Virat Kohli \nis \nthe best" h4 = "India is the best" h5 = "I love chinese\r food!!" print("Splitted list: ", h1.splitlines(True), "\n") print("Splitted list: ", h2.splitlines(False), "\n") print("Splitted list: ", h3.splitlines(True), "\n") print("Splitted list: ", h4.splitlines(True), "\n") print("Splitted list: ", h5.splitlines(True), "\n") Output ➜ pyt python3 app.py Splitted list: ['Hello I am\n', ' a\n', ' geek!'] Splitted list: ['Python', 'C++', 'C', 'Java', 'Kotlin'] Splitted list: ['Virat Kohli \n', 'is \n', 'the best'] Splitted list: ['India is the best'] Splitted list: ['I love chinese\r', ' food!!'] ➜ pyt Example 3 # app.py def str_len(string): li = string.splitlines() print(li) l = [len(element) for element in li] return l string = "Hello\rthere\rHackTheStuff" print(str_len(string)) Output ➜ pyt python3 app.py ['Hello', 'there', 'HackTheStuff'] [5, 5, 11] ➜ pyt In the above code, we are learning how to use the concept of splitlines() to calculate the length of each word in a string. Finally, Python String splitlines() Method Example is over.
Python String Title method
Python String title() is an inbuilt string handling function that returns a string in which the first letter of the words present in the string is uppercase, and all the other letters of the word are lowercase. If the string contains symbols and numbers, then the 1st number after it is converted to uppercase. We also call the words that have the first letter as uppercase and all other letters as lowercase title cased. Python String title() The title() function in python is used to convert the first character in each word to an uppercase and remaining characters to Lowercase in the string and returns a new string. Syntax string.title() Here, the string is variable that is converted to be title cased. Parameters The title() method doesn’t take any parameter and throws an error if any parameter is passed. It is used with a string using a dot operator, and the output string is shown. Return Value The method returns a string in which the characters of the words are title cased. Example programs on the title() method Write a program to show the working of the title() method. // app.py h1 = "Hello" h2 = "How are you" h3 = "I am HackTheStuff" h4 = "I love Python" print("Original string: ", h1) print("title(): ", h1.title(), "\n") print("Original string: ", h2) print("title(): ", h2.title(), "\n") print("Original string: ", h3) print("title(): ", h3.title(), "\n") print("Original string: ", h4) print("title(): ", h4.title(), "\n") Output ➜ pyt python3 app.py Original string: Hello title(): Hello Original string: How are you title(): How are you Original string: I am HackTheStuff title(): I am HackTheStuff Original string: I love Python title(): I love Python ➜ pyt You can check I hope you will like this article.
Python String Zfill Method Example
Python zfill() is an inbuilt python string method that is used to append zero to the left side of the given string. It is a padding mechanism. The number of 0’s to be appended decided by the argument, which is a number passed in the zfill() method. The argument is the total length of the list.  Suppose the current length of the string is 20, and the argument is 30, then the zfill() method will attach 10 zeroes to the leftmost side of the string to make that string of length 30. The zfill() function returns a string. Python String zfill() Python zfill() method fills the string at left with 0 digits to make a string of length width. It returns a string contains a sign prefix + or – before the 0 digits. It returns original length string if the width is less than string length. Syntax str.zfill(length) Here str is the string variable that holds the main string, which is to be filled. Length is the length of the string that we want to make. Parameters: It takes a single parameter, which is the length. It specifies the length of the string we want. It must be greater than the current length of the string. Return Value It returns a string with the required number of zeroes padded in the main string. Example program on zfill() in python Write a program to show the working of the zfill() method in python. # app.py h1= "MilEy CirUS" h2= "Hello Boy" h3= "Qwerty" h4= "HELLO girl" h5="lionel messi IS THE BEST" print(h1.zfill(20)) print(h2.zfill(15)) print(h3.zfill(25)) print(h4.zfill(24)) print(h5.zfill(30)) Output ➜ pyt python3 app.py 000000000MilEy CirUS 000000Hello Boy 0000000000000000000Qwerty 00000000000000HELLO girl 000000lionel messi IS THE BEST ➜ pyt Hope you like this small article.