Author name: cndro

Blogs

13 Selenium Commands Every Developer Must Know

                                                                  Photo by Fotis Fotopoulos on Unsplash In our last tutorial, we discussed why Selenium is the best automation tool and demonstrated how we could run a simple test case in Python. As we said, Selenium is compatible with leading programming languages like Python, Java, Ruby, and others. We can use it with any of our popular browsers like Chrome, Firefox, Edge, and lots more. Today, we’ll discuss the top commands we need to know when working with Selenium in Python. Commands for Searching Specific Web Elements The list of commands we will first discuss is the commands used for automating and searching web pages. They are also called Locators in Selenium. Now, to identify these specific elements on a web page, we will use the findElement() command. Here is the list of the commands; find_element_by_xpath: This can be used to locate and return the first element with the XPath syntax. Xpath can also be implemented when working with an XML document, and mainly XPath is used when the code isn’t working successfully with ID, class, or name. We can implement XPath in our script as shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window 7 driver.maximize_window() 8 9 #We will use the driver.get to open the wiki main page 10 driver.get(“https://en.wikipedia.org/wiki/Main_Page”) 11 12 #we copy our xpath of the elements we are interested in from the Inspect element in browser 13 elements = driver.find_element_by_xpath(‘//*[@id=”n-contents”]/a/span’) 14 15 16 print(elements) 17 18 #we then close the browser 19 driver.close() 20 21   2. find_element_by_id: We use the find_element_by_id to return first element with id attribute value matching the location of our item. If no element was found, the NoSuchElementException would be raised. An example is shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window 7 driver.maximize_window() 8 #We will use the driver.get to open the wiki main page 9 driver.get(“https://en.wikipedia.org/wiki/Main_Page”) 10 #we specify the id of the element we want to search for here 11 elements = driver.find_element_by_id(‘mw-navigation’) 12 13 print(elements) 14 15 #we then close the browser 16 driver.close() 17   3. find_element_by_name: We can also find our element by name. To do that, we use the find_element_by name locator and pass the name attribute. This will return the first element found during the search. An example is shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window 7 driver.maximize_window() 8 #We will use the driver.get to open the wiki main page 9 driver.get(“https://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Wikipedia%3AAbout”) 10 #we specify the name of the element we want to search for here 11 elements = driver.find_element_by_name(‘wploginattempt’) 12 13 print(elements) 14 15 #we then close the browser 16 driver.close()   4. find_element_by_class_name: To use the find_element by class name locator, we use it along by specifying the element’s class name. This will give us the first element found in our search. An example is shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window 7 driver.maximize_window() 8 #We will use the driver.get to open the wiki main page 9 driver.get(“https://en.wikipedia.org/wiki/Main_Page”) 10 #we specify the class name of the element we want to search for here 11 elements = driver.find_element_by_class_name(‘mw-parser-output’) 12 13 print(elements) 14 15 #we then close the browser 16 driver.close() 17   5. find_element_by_link_text: We use this find_element_by_link_text to find a particular hyperlinked text in a page. To use this locator, we specify the name of the hyperlinked text inside our locator. This will return the first element found in our search. An example is shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window 7 driver.maximize_window() 8 #We will use the driver.get to open the wiki main page 9 driver.get(“https://en.wikipedia.org/wiki/Main_Page”) 10 #we specify the name of the element we want to search for here 11 elements = driver.find_element_by_link_text(‘Contents’) 12 13 print(elements) 14 15 #we then close the browser 16 driver.close()   6. find_element_by_css_selector: It is possible to find an element using the CSS selector. We specify the CSS selector we want to use inside the locator during the search. The first element with the matching selector will be returned, and if no element was returned, the NoSuchElementException would be raised. An example is shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window 7 driver.maximize_window() 8 #We will use the driver.get to open the wiki main page 9 driver.get(“https://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Wikipedia%3AAbout”) 10 #we specify the css selector of the element we want to search for here 11 elements = driver.find_element_by_css_selector(‘input.wploginattempt’) 12 print(elements) 13 14 #we then close the browser 15 driver.close()   7. find_element_by_tag_name: Just as we mentioned the CSS selector earlier, we can also find our element using the Html Tag name. This tag name will be used inside the find_element_by_tag_name locator. This will return the first element that matches the tag name; if no element, a NoSuchElementException will be raised. An example is shown below; 1 #we import our library 2 from selenium import webdriver 3 4 #here we paste link to our exe file in the webdriver.chrome method 5 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 6 #we maximize our window

Blogs

Why You Need a Layout Container in Tableau Dashboard

This tutorial will discuss why you need to use a layout container in your dashboard. Layout Containers are perfect for neatly arranging objects when creating your dashboard. Arranging objects in a dashboard has always been a struggle for some Developers, who find this confusing. We must be intentional about arranging our worksheets in an orderly manner on our dashboard. Setting them well gives the dashboard a cleaner look for the audience or users. This is why containers are the solution to standardize the size and layout of the dashboard when viewed via different device lenses(Desktop, Tablet, Phone). Before we move into using Layout Containers in Tableau, let’s discuss critical things to consider while planning our dashboard. Define your Audience — You need to define your audience and what they want to see on their dashboard. Also, ask if your dashboard is user-friendly, whereby the audience can quickly grasp what you did and, what are the metrics important to your audiences’ businesses. Layout — The layout, which is the subject of our discussion today, is also vital when planning a dashboard. You should always separate your dashboards into sections, making navigating easier for your users. Design Purposeful Dashboard — When designing your dashboard, it has to be purposeful, whereby you consider the impact it has on the users or audience. It would help if you also consider how your audience would understand the dashboard. How to Get Started with Layout Containers Containers, like we said, allow us to group our objects, i.e., worksheets, images, filters, and lots more, together. We can move the container anywhere we want, and our dashboard objects will maintain the size we allocate. We have two types of Layout containers; Horizontal and Vertical. Horizontal Containers — The horizontal containers help group worksheets and dashboard components from left to right across our page. There is no limit to the number of containers we can place within other containers. Vertical Containers — Vertical containers help users group worksheets from top to bottom down along a page. So we may have a horizontal container on the left-hand side and a vertical container to our right where the sheet has a drop-down filter. From the image below, you can find the Horizontal and Vertical containers under the Objects sections. You drag it inside your Dashboard working area to use either of it. Steps to follow while Inserting Containers Always have an outer Container: Whenever you’re designing your dashboard, it’s always good to have an outer container that contains both the dashboard title and its content. Insert Dashboard Title and more Containers: Now that you’ve inserted an outer container, you can bring in more containers per your desired choice of placing content. Then you go further by typing in your dashboard title, which should be at the top of the view. Also, Inside our containers, we can put temporary blank contents in to help us arrange our contents well while placing the worksheets in them. Populate Containers with Worksheets: So now we can remove those blanks and populate them with our worksheets accordingly, and we put in mind to arrange them for easy navigation for our users or according to our audience priority. We have a simple representation in the image below. Also, you must always check your items’ hierarchy when working on your layout. This is very important as it lets you quickly change how objects are layered and grouped on your dashboard. The view tells you that Items at the top of the list appear in the front, while items at the bottom appear at the back. A simple representation of the items hierarchy is shown below; Hope you found this post helpful. Let’s know your thoughts in the comments section below. Thanks for reading.

Blogs

Why Selenium is the Best Automation Tool

                                                         Photo by Joshua Sortino on Unsplash This article will discuss why Selenium is the best automation tool. Selenium is an open-source automation testing tool used for automating tests to validate web applications on different web browsers. It supports different programming languages to create test scripts, such as Python, Java, C#, e.t.c. It also supports various browsers like Chrome, Mozilla, Firefox, Safari, e.t.c. We can easily automate browser testing across these browsers using Selenium WebDriver. Selenium is well used by Developers because of the result derived from it. Now we will move further to discuss key reasons Developers use Selenium tool. After that, we’ll implement how we can use the tool. Key Reasons to use Selenium Tool Open Source Availability: One of the most exceptional reasons many Developers use this tool daily is that it’s publicly accessible and free. To use this tool, you don’t have to make any payment. The community keeps helping developers improve the web browser features and functionalities. Language and Framework Support: We also have the aspect of language and framework support. For a Developer to utilize this tool, he can use any of his desired programming languages: Python, Java, C# e.t.c. As a Developer, you don’t have to worry about language support. You can use any major languages to carry out your test automation. Also, for every supported language in Selenium , there is an allocated framework designed to assist in writing test scripts. This was put in place to make the tool easier to use. Ease of Implementation: Selenium has a friendly user interface making it very easy to implement test scripts effectively. With Selenium we can add different configurations on how we want our test to run. We can also reduce code duplication and improve code readability. In addition, new users who just started learning the tool find it easier to use and it doesn’t take much time to learn. Certainly, Developers who use Selenium sure do excellent feedbacks to give on this tool. Support Across Various Operating Systems: It supports various Operating systems; it isn’t OS-dependent. This tool can work across this different OS; Windows, Linux, Mac OS, UNIX, etc. With Selenium WebDriver, we can create a test case on Windows and execute it on Mac and other OS. Constant Update: Just like we mentioned earlier that a community supports Selenium. The selenium community releases regular updates and upgrades to make this tool more effective for Developers. Constant improvement on this tool drives more users daily. Now that we’ve seen the different reasons this tool is very effective and why it’s one of the best automation tools. We’ll discuss how we can use this tool in Python. Selenium With Python Let’s implement how we to run a Selenium test script with Python programming language. Follow the installation steps carefully. Install Python on Windows To demonstrate this, we will use a windows machine. If you don’t have Python on your machine, please visit this link to download, preferably Python 3. After installing python, go to your command prompt to confirm by typing python, just as seen below. You will have your python version, just as ours shows python 3.10.5. Install Selenium We can install Selenium using the command below. This will install the latest package of Selenium. Python -m pip install -U Selenium You can also confirm your installation using the same command we used below. Download Selenium Web Driver The next step is to download the Selenium Web driver for the browser we’ll be using. We’re using Google Chrome Browser, so we will download the chrome driver based on our chrome’s version. We can download the driver here. If you’re using other browsers, you can get Firefox, Safari, and Edge via each link. Here, we download the chrome driver for Windows as shown below. Our Code After downloading the zip file, we will extract the .exe file inside our working environment folder. To make things look cleaner, we can create a folder named Browser and put the .exe file inside. Like what we have below, our code will reside in the code.py file. This is what we have in our code as shown below. In this code, we demonstrated a simple test case of how Selenium get driver was used to open Google and then we searched for our Name “Cndro”. Selenium performs the action of searching and clicking on search button automatically, after then, close the browser. 1 #we import our library 2 from selenium import webdriver 3 import time 4 from selenium.webdriver.common.keys import Keys 5 6 #here we paste link to our exe file in the webdriver.chrome method 7 driver = webdriver.Chrome(r’C:\Users\CNDRO\Documents\Selenium_project\Browser\chromedriver.exe’) 8 9 #we maximize our window 10 driver.maximize_window() 11 12 #We will use the driver.get to open google 13 driver.get(“https://www.google.com/”) 14 15 #we use the driver to find name of the search bar name, so we can paste in our search item name 16 driver.find_element_by_name(“q”).send_keys(“cndro”) 17 18 #we use time.sleep to make selenium work at a balance by not being too fast 19 time.sleep(3) 20 21 #Now, we also get the name of the button where selenium will click automatically 22 #and then use send keys.enter to automatically click it 23 driver.find_element_by_name(“btnK”).send_keys(Keys.ENTER) 24 25 #we put it on sleep again 26 time.sleep(3) 27 28 #we then close the brower 29 driver.close()   So we run our code with the command python code.py as seen below; Then it opens a new browser, just as seen below, to carry out our designated action. Which automation tool do you consider the best? Drop your thoughts in the comments section below. Thanks for reading.

Blogs

Why You Need the Pandas Library

Photo by Shunya Koide on Unsplash Pandas is a software library written for the Python programming language for data manipulation and analysis. Wes McKinney first started this library in 2008 out of the demand for a high performance and flexible tools to perform quantitative analysis on financial data. Pandas is built on top of two core python libraries. We have the Matplotlib, used for data visualization, and Numpy, used for mathematical operations. With Pandas, Developers can easily work with tabular data (like spreadsheets) within a Python script. Now, let’s discuss why Pandas library is a useful tool for data exploration and manipulation. Data cleansing: It isn’t new that Data Scientist/ Analyst spends a huge amount of time on cleaning datasets and preprocessing to the actual form they want. Pandas provides an easy pathway to be able to handle this messy data, deal with missing values and remove irrelevant data. With pandas we can read, process and write to (CSV, TSV, Excel, HDF, JSON, THML , database data files) and any other formats. Pandas gives us two different forms of representing our data. We have the Series, a list-like structure, and DataFrames, which has a tabular structure. Data Exploration: Data exploration refers to the initial step in data analysis in which Data Analysts use data visualization and statistical techniques to describe dataset characterizations. In this phase, a data analyst can explore and identify relationships between different data variables, the presence of outliers and what the structure looks like. Data Exploration is usually carried out to get insight and recognize patterns from the data. With that being said, Pandas is an excellent tool when it comes to Data Exploration in a dataset. All Data Scientists/ Analysts should have this in their skill set. Here are different functions we can use in pandas for exploring data; .info(): The info function is used to return information about our DataFrame. The information contains the number of columns, column labels, column data types, memory usage, range index, and the number of cells in each column. .head(): With this function, we can print the first 6 rows of our data and change it to print other values . i.e df.head(10); this will print the first 10 rows of data in our DataFrame. .tail(): We can use .tail() in the reverse order of .head(). Here we’ll print the last 6 rows of our data, or the tail end of our data. .describe(): We can use the .describe() method to calculate statistical data such as the Percentile, Mean & Standard Deviation of numerical values in our DataFrame or series. .sort_values(): When working with our data, a need might arise for us to want to sort our DataFrame in a particular order. We can sort by column, ascending order and descending order. .groupby(): the .groupby() function is usually used to split data into separate groups, so as to perform computations such as; .mean(), .sum() e.t.c for better analysis Data visualization: Pandas is one of the efficient ways to visualize data. It provides several different functions to use with the help of the .plot() function. With this .plot() function we can plot all kinds of graphs such as Bar graph, Histogram, Box Plot, Area Plot, Scatter Plot e.t.c. when working with series or DataFrame. Bar graph — df.plot(kind=”bar”) Histogram — df.plot.hist() Box Plot — df.plot.box() Area Plot — df.plot.area() Scatter Plot — df.plot.scatter(); Merges and Joins: Another way Pandas is helpful is the ability to merge and join datasets. Pandas provides us an effective method for easily combining DataFrame or Series based on different forms of logic. With pandas, we can merge, join, and concatenate in our datasets, thereby providing a meaningful structure for our dataset. .merge() — Pandas use the .merge() method to combine two different datasets. We can also merge with any join types(inner, left, right, and outer). .join() — Here also, pandas uses .join() method to combine differently-indexed DataFrames into a new DataFrame. We can join using the argument ‘on’ , or join on two differently indexed DataFrames. .concatenate() — The .concat() method is a very efficient way of handling large datasets. We can concatenate DataFrames both vertically(axis=0) and horizontally(axis=1). Data Normalization: Another area where we use Pandas is the aspect of Data Normalization. Data analysts or scientists usually carry out normalization to adjust values existing on different scales to a common scale. The Pandas library provides multiple built-in methods through maximum absolute scaling which makes data normalization techniques very easy to implement. Some of these methods includes; .max() method .abs() method Statistical Analysis: Pandas has also proven many times as the best tool for carrying out statistical analysis of data. In Pandas, different built-in statistics are made available, which we can apply to our numerical data. Some of these methods we can use are listed below; .value_counts() — This function returns object containing counts of unique values .count() — The count() method is used for counting the number of not empty values for each row, or column. .mean() — The mean() method is used to calculate the mean of the values for the requested axis. .median() — The median() method is used to calculate the median values for the requested axis. .argmax() — This can be used to calculate the maximum value present in the input Index. If we have more than one maximum value (i.e., the maximum value is present more than once), then it returns the index of the first occurrence of the maximum value. .max() — This is used to calculate the maximum value of the requested axis. Hope you enjoyed this article. Thanks for reading.

Blogs

Class or Static Variables in Python

Class or Static Variables in Python                                                            Photo by Shahadat Rahman on Unsplash In this tutorial, we’ll discuss class or static variables in Python. Class or Static variables are the variables that belong to a class and not objects. We can also say they are shared amongst objects of the class. Therefore, all variables assigned a value in the class declaration are called class variables, and variables given inside the class methods are referred to as instance variables. Whenever we have a class, all class objects will share the static variable. This static variables can be accessed either by class name or through object reference such as ClassName.static_variable_name. Let’s check the examples below to understand how this is done; Example1 There is an Employee class with a class variable known as role in this example. We assigned a variable to our class variable called “Software Engineer”. Next, we defined a class constructor which accepts two new arguments. We then created our instance variable(_id and name). After this, we created 2 different objects for the Employee class. Through this object, we could access our static/class variable “role”. We were also able to call each of the instance variables using each of the individual objects created. 1 class Employee: 2 # Here is a Class Variable 3 role = ‘Software Engineer’ 4 def __init__(self,_id,name): 5 #this is an Instance Variable 6 self._id= _id 7 #this is an Instance Variable 8 self.name = name 9 10 11 # our objects of the Employee class 12 a = Employee(1, ‘Adams’) 13 b = Employee(2, ‘Janes’) 14 15 print(a.role) 16 print(b.role) 17 print(a._id) 18 print(b._id) 19 print(a.name) 20 print(b.name) 21 print(Employee.role)   Output 1 Software Engineer 2 Software Engineer 3 1 4 2 5 Adams 6 Janes 7 Software Engineer We can change the value in a class variable by using class object but mind you; this doesn’t affect another object of the class that might just be created. Let’s see the demonstration below; 1 a.role = ‘Data Engineer’ 2 print(a.role) 3 print(b.role) 4 print(Employee.role) Here, we use the  a object to change the value in the role(our class variable). We observe that this code won’t affect the second object and the main class variable whenever we run this code. The reason is that this occurs at the level of that particular object. We generated the output below; Output 1 Data Engineer 2 Software Engineer 3 Software Engineer Note: You can access the class variable by using either the class name or the object reference, just as seen below; 1 print(a.role) 2 print(Employee.role) Output 1 Software Engineer 2 Software Engineer Let’s check another example below on class or static variable; Example 2 Here is another example on how to use the class or static variable. In this example, we demonstrated using a particular animals class called carnivorous. We defined our static variable in our class and also created our constructor which has an argument called name. We defined another new method used for printing all the objects of the animal class we created just as seen below; 1 class Animals: 2 # class or static variable 3 category = ‘carnivorous’ 4 5 def __init__(self, name): 6 # instance variable 7 self.name = name 8 9 10 # method to show data 11 def show(self): 12 # accessing class variable 13 print(self.name) 14 15 a = Animals(‘Lion.’) 16 b = Animals(‘Wolf.’) 17 c = Animals(‘Leopard.’) 18 d = Animals(‘Hyena.’) 19 e = Animals(‘Polar Bear.’) 20 21 print(‘These animals belong to the class: ‘, Animals.category) 22 print(‘These animals are:’) 23 a.show() 24 b.show() 25 c.show() 26 d.show() 27 e.show() Output We generated the output below; 1 These animals belong to the class: carnivorous 2 These animals are: 3 Lion. 4 Wolf. 5 Leopard. 6 Hyena. 7 Polar Bear. Hope you enjoyed this post. Thanks for reading.

Blogs

Getting Started with Docker in Python

.                                                                  Photo by Rubaitul Azad on Unsplash This articles explains how you can get started with Docker in Python. Docker is a free software developed by Docker Inc. This containerization platform helps us package our application and its dependencies in the form of containers. This application can work effortlessly in any environment, either development, test, or production. Docker was developed to tackle many problems developers face, including the issue of an application working on a computer but not starting on a staging server or development. Let’s discuss some of the different terminologies in docker before moving to the installation aspect. Docker Container — The containers are created from images. We can also refer to them as the runtime instances of Docker Images. The Containers also have the equipment required for an application to be run in an isolated way. Docker Image — Docker images refer to the template for creating our Docker containers. The starting point of every Docker image is a base image such as ubuntu14.04 LTS. Docker File: Docker file is usually a text file that has series of instructions on how Docker Image should be created. Volume — This can be defined as a shared folder. They are usually initialized when a container is created. Registry — The registry can be referred to as the server which stores the Docker Images. It provides us the ability to pull up any docker image. Installation Now, we need to install Docker Engine on our machine. To install Docker Engine on your machine either Linux, Windows, or Mac, you can visit this link . After you’ve done your installation, you verify with the command docker –version on your terminal. I will be using a windows machine to demonstrate in this tutorial. Create your Project Open your VS Code or any other IDE to create a new project, let’s create a folder call docker_demo. In this folder we have our two files, main.py and requirements.txt just as seen below: Main.py file Inside this main.py file, we use the Numpy library. We want to create NumPy ndarray object by using the array() function as seen below: 1 import numpy as np 2 3 arr = np.array([1, 2, 3, 4, 5]) 4 5 print(arr) Requirements.txt file 1 -i https://pypi.org/simple 2 numpy>=1.18.1 3 pandas>=1.0.1 4 python-dateutil>=2.8.1 5 pytz>=2019.3 6 six>=1.14.0 Our requirements.txt also contains all the necessary libraries we need. Let’s create our Docker File now. Create Docker File Here, we’ll create a new file that has no extension and name it Docker File inside our current working directory, just as seen below: We then write the following command inside our Docker file: 1 #all docker file starts with a “FROM” instruction for setting parent image, here we are pulling latest python to run our application 2 FROM python:latest 3 4 #we copy the requirements file into the app folder we are just creating now 5 COPY requirements.txt /app/ 6 7 #here we set this app folder as our working directory 8 WORKDIR /app 9 10 #Now we use the RUN command to pip install –upgrade pip and install the requirements.txt in our parent image here 11 RUN pip install –upgrade pip \ 12 && pip install –requirement requirements.txt 13 14 #After installation, we copy our python file(main.py) inside our working directory in the parent image 15 COPY main.py . 16 17 #here, we defined the command to be executed to run our python file 18 #just like we do “python main.py” to run our python file in our VS Code terminal. 19CMD [“python”, “main.py”] Build Docker Image To build our Docker image, we will write this command below in our terminal docker build -t image_name . The image-name stands for the name you want to assign to your image . The command I used is shown below: docker build -t my_docker . A local image with my_docker will be automatically created for us, just as shown below. Run local Docker image What we need to do now is to run our local docker image. We can run with the command below by using the docker image name; Therefore our code is ready to be launched. 1 $ docker run my_docker After running the docker image, we generated our result as shown in the image below; Docker Commands Check All Containers You can also view all running containers you have by using the command below: 1 docker ps -a   Show Running Containers To show only running containers, you use this command: 1 docker ps Show Latest Created Container To show the latest created container, you use the command below. 1 docker ps -l Hope you found this post helpful. Thanks for reading.

Blogs

Python Constructors: All You Need to Know

                                                                  Photo by Clément Hélardot on Unsplash Constructors in Python are methods used for initializing an object. We can say they are methods called whenever an object is created. A constructor also has one simple task, which is to assign values to data members of a class whenever an object has been created. In explaining constructor better, a constructor is called by the __init__() method, and it is invoked whenever an object is created. For instance, if we create three objects, our class constructor will be called by that same three times. Now, let’s discuss the different types of constructors we have in Python; Types Of Constructors We have two types of Constructors and they are: Default constructor Parameterized constructor Default Constructor The default constructor is the type of constructor that takes no arguments. This constructor holds only one argument “self”, which is a reference to the instance that is being established. Example 1 In the example below, we created a class named Fruits and defined a constructor that takes no arguments. Inside the constructor, we initialized two variables known as “first_fruit” and “second_fruit”. Then we created a method for printing our data members and also created an objects of the class named “our_object”. Using these objects, we were able to call our instance method. 1 class Fruits: 2 3 # our default constructor 4 def __init__(self): 5 self.first_fruit = “Pineapple” 6 self.second_fruit =”Apple” 7 8 # we define a method for printing our data members 9 def print_fruit(self): 10 print(self.first_fruit) 11 print(self.second_fruit) 12 13 14 # created object of the class here 15 our_object = Fruits() 16 17 # let’s call the instance method using our object of the class 18 our_object.print_fruit()   Output We generated the output below; 1 Pineapple 2 Apple Let’s look at this other example below on Default Constructor. In our example below, we can observe that it has no argument as well. Example 2 1 class Customer: 2 3 #our default constructor 4 def __init__(self): 5 self.name = “Scott” 6 self.age = 40 7 self.address = “Elizabeth strt” 8 9 # we define a method for printing our data members 10 def details(self): 11 print(‘Name:’, self.name, ‘Age:’, self.age,’Address:’, self.address) 12 13 # created object of the class here 14 the_cust= Customer() 15 16 # let’s call the instance method using our object of the class 17the_cust.details()   Output We generated this output. 1 Name: Scott Age: 40 Address: Elizabeth strt 2​ Parameterized constructor This constructor contains parameters just as the name depicted. It has a reference to the instance being created called self just like that of the default constructor but here, it can allow more arguments and the self serves as the first argument. Let’s dive in different examples on Parameterized constructors to understand it better. Example 1 In this example, we created a Customer class with constructor that has one more argument apart from the self, which acts as the first argument. Here, we can see how we used the “name” arguments after we created the object of our class. We can observe that the name (Mr Scott) was passed in as an argument when we created the object. 1 class Customer: 2 # Our parameterized Constructor with more argument 3 def __init__(self, name): 4 self.name = name 5 self.age = 40 6 7 # we define a method for printing our data members 8 def details(self): 9 print(“Hi “,self.name) 10 11 # created object of the class here 12 the_cust = Customer(“Mr Scott”) 13 14 # let’s call the instance method using our object of the class 15the_cust.details()   Output We should have this output after running our code 1 Hi Mr Scott Let’s check one more example on the Parameterized Constructor Example2 Here is also another way of defining more than one arguments in a constructor just as seen below 1 class Customer: 2 # parameterized constructor 3 def __init__(self, name, age, address): 4 self.name = name 5 self.age = age 6 self.address = address 7 8 # display object 9 def details(self): 10 print(self.name, self.age, self.address) 11 12 # creating object of the Employee class 13 Mike = Customer(‘Mike Howard’, 40, ‘520 N MADISON LOS ANGELES’) 14 Rose = Customer(‘Rose Cooper’, 32, ‘521 N MADISON LOS ANGELES’) 15 Benjamin = Customer(‘Benjamin Smith’,35,’522 N MADISON LOS ANGELES’) 16 Mike.details() 17 Rose.details() 18 Benjamin.details()   Output 1 Mike Howard 40 520 N MADISON LOS ANGELES 2 Rose Cooper 32 521 N MADISON LOS ANGELES 3 Benjamin Smith 35 522 N MADISON LOS ANGELES Hope you enjoyed this post. If you do, Comment, share, and follow for more informative posts. Thanks for reading.

Blogs

How to Create Power BI Calendar Table Using DAX Functions

This tutorial will demonstrate how we can create a calendar table in Power BI Report using the DAX(Data Analysis Expressions) function. Power BI is a Business Intelligence tool used for sharing insights in different companies. It is very efficient for creating reports and dashboards. Dates are crucial in data; it helps us gain information about events, sales reports, and so many other useful references in our data. There are two different functions that can be used for creating a Power BI calendar. These are; the CALENDAR DAX function and CALENDARAUTO function. CALENDAR Function We can use the Calendar function to put a date range in data. Writing this function gives us a range of dates: the start date and finish date of what we set. The Syntax 1 CALENDAR(<start_date>, <end_date>) 2 The start_date specifies the start date, while the end_date specifies the end of our date.   Let’s see an example below; The date range we specified here should give us the date from May 1st, 2014 till January 1st, 2021. CALENDAR (DATE (2014, 5, 1), DATE (2021, 1, 10))   CALENDARAUTO Function CALENDARAUTO function generates the list of dates containing all the data model dates. The argument needed here is the fiscal year-end month. The Syntax looks like this; CALENDARAUTO([fiscal_year_end_month])   [fiscal_year_end_month]: This is a DAX expression that returns an integer from 1 to 12. When omitted, it defaults to the value specified in the calendar table template for the current user, if present; otherwise, it defaults to 12. Let’s see the example below; In this example, we click on New table and write the CALENDARAUTO function in the empty box. On writing that, Power BI will then create a start and end date calendar by looking at the date range of your table dates. Now that we’ve examined the two different functions we can use, we can discuss how to add columns to the date table with DAX. The ADDCOLUMNS Function With the ADDCOLUMNS function, we can create new columns in our table. The syntax looks like this; ADDCOLUMNS ( <Table>, <Name>, <Expression> [, <Name>, <Expression> [, … ] ] )   Let’s look at this example below. This example shows us how we can create many columns. We created the Year column, the month_number, days of the week, Quarter, YearQuarter, and others. We use the Format function to specify how we want our date to be. 1 Calendar = 2 3 ADDCOLUMNS ( 4 5 CALENDAR (DATE(2014,5,1), DATE(2021,1,10)), 6 7 “DateAsInteger”, FORMAT ( [Date], “YYYYMMDD” ), 8 9 “Year”, YEAR ( [Date] ), 10 11 “Monthnumber”, FORMAT ( [Date], “MM” ), 12 13 “YearMonthnumber”, FORMAT ( [Date], “YYYY/MM” ), 14 15 “YearMonthShort”, FORMAT ( [Date], “YYYY/mmm” ), 16 17 “MonthNameShort”, FORMAT ( [Date], “mmm” ), 18 19 “MonthNameLong”, FORMAT ( [Date], “mmmm” ), 20 21 “DayOfWeekNumber”, WEEKDAY ( [Date] ), 22 23 “DayOfWeek”, FORMAT ( [Date], “dddd” ), 24 25 “DayOfWeekShort”, FORMAT ( [Date], “ddd” ), 26 27 “Quarter”, “Q” & FORMAT ( [Date], “Q” ), 28 29 “YearQuarter”, FORMAT ( [Date], “YYYY” ) & “/Q” & FORMAT ( [Date], “Q” ) 30 31) Our table should resemble what we have below; And that’s a wrap. See you in our next post.

Blogs

Introduction to Docker Compose

In this tutorial, we will discuss what Docker Compose is all about. In one of our previous posts, we mentioned that Docker is a containerization platform developed to help package applications and their dependencies in the form of containers. This allows these applications to work effortlessly in any environment, either development, test, or Production. We also stated that Docker was introduced to tackle many problems developers face on staging servers and development. Here now, we will discuss how Docker Compose is majorly used. Docker compose helps to facilitate multiple services running simultaneously. We run multiple containers as a single service here, and each of these containers runs in isolation but communicate with each other when required. Installation Firstly, we need to install Docker Compose on our machine. To install Docker Compose on Linux, Windows, or Mac, you can visit this link. After installing it, verify with the command docker-compose –version on your terminal. How to Create a Compose File Hello World Docker Compose Let’s look at this basic example of  creating Hello World with Docker Compose. In the code below, we created a container from the ubuntu image, whereby the “Hello World” service is initialized from the ubuntu image, which will print “Hello World” when run. 1 version: ‘2’ 2 services: 3 hello_world: 4 image: ubuntu 5 command: [/bin/echo, ‘Hello world’] We use docker-compose up to run the code; Let’s try out another example of how much further we can use the Docker Compose for our application. Using Redis in Flask App We use Redis to handle our requests in this application, whereby we pass our data via Redis. What we have below is our requirements.txt file which is flask and Redis. Requirements.txt Our Flask App Here is the code to our flask app ,we’re using the POST and GET method. The POST method was used to send data which is in form of {‘name’: your_input} via the Redis as a collection of string keys and values. Whenever the GET method endpoint is called, we can get our items, which will be returned via the redis.lrange(). from flask import Flask, request, jsonify from redis import Redis app = Flask(__name__) redis = Redis(host=”redis”, db=0, socket_timeout=5, charset=”utf-8″, decode_responses=True) @app.route(‘/’, methods=[‘POST’, ‘GET’]) def index(): if request.method == ‘POST’: name = request.json[‘name’] redis.rpush(‘customers’, {‘name’: name}) return jsonify({‘name’: name}) if request.method == ‘GET’: return jsonify(redis.lrange(‘customers’, 0, -1)) The DockerFile This is our DockerFile which contains series of instructions on how we want our image to be created. FROM python:3.7.0-alpine3.8 COPY requirements.txt /app/ WORKDIR /app RUN pip install –no-cache-dir -r requirements.txt COPY . . ENV FLASK_APP=app.py CMD flask run –host=0.0.0.0 Docker Compose File Under our docker compose file, we tell docker how to build our image and we specify Flask development environment. So whenever we run the docker-compose up, our flask app will run based on the port we specified there as well. version: “3” services: app: build: . image: flask-redis:1.0 environment: – FLASK_ENV=development ports: – 5000:5000 redis: image: redis:4.0.11-alpine Running Docker Compose File We use the docker-compose up in our terminal to run our compose file, then we have our application running as seen below. We can move further to test with Postman. Project structure Your project structure should look like this

Blogs

How to Get Started with Regular Expressions in Tableau

                                                                    Photo by Myriam Jessier on Unsplash In this tutorial, we’ll look at how we can use Regular Expressions in Tableau. In our last tutorial, we discussed how we can use Regular Expressions in Python. Just like we learnt earlier, Regular Expression is used for extracting data element from a string of data. The common application of Regular Expression is website and mobile apps. The use of Regex here is basically for input validation. Many applications can validate if what a user enters matches the back end’s required structure. An example is our email address, which the system checks to see if we typed it correctly. Now, let’s look at the Metacharacters classes which build up our knowledge foundation in Regex. Regular Expression Metacharacters Classes The Metacharacters are classes useful in defining rules to find a specific pattern in a string. These classes do have a special meaning in the REGEX Engine. Few examples of the Metacharacters classes are listed below. Now that we’ve discussed the Metacharacters classes, this gives us an overview of how to interpret or define our Regex expressions. In Tableau, we have four different REGEXP functions, and they are; REGEXP_EXTRACT (string, pattern) REGEXP_EXTRACT_NTH (string, pattern, index) REGEXP_MATCH (string, pattern) REGEXP_REPLACE (string, pattern, replacement) Let’s discuss how each can be used and their various examples. REGEXP_EXTRACT (string, pattern): The REGEXP_EXTRACT is used for searching a particular pattern within a string or substring, and then extract the data element which is our output. Example: We have students’ descriptions with their names, subjects, and ages in the table below. We’ll demonstrate how we can use REGEXP_EXTRACT to extract each student’s first and last name. Extract Last Name To extract their last name, we will use the code below. In this code, we observed that the pattern (\w+) is a rule from the metacharacters we explained earlier. This is why understanding the metacharacters helps a lot in writing our regex. 1 REGEXP_EXTRACT([Text], ‘(\w+)’) The function of the pattern (\w+) here tells us the parenthesis acts as our capture group, and the backslash describes the starting point to start with. Now the “w” is matching on a word character and alphanumeric values. The function of the “+ “ symbol means to extract all characters once and stop when it finds a next character which isn’t a word. This is similar to what we have after each last name is a comma. As seen below, we should have our desired text extracted with this code. Extract First Name Let’s extract our first name . We’ll also define the right pattern we need to extract our data correctly. We have the code we’ll use for this below. 1 REGEXP_EXTRACT([Text], ‘,\s+(\w+)’) In this code, we observed it’s quite different from what we used to extract the last name. The reason is where the first name is located. Look at this first string, “Cooper, Elizabeth is a student of Account, Age: 15”. Elizabeth, the first name is located after a comma and a space. This constraint has to be dealt with to extract our data correctly. So with our pattern (R EGEXP_EXTRACT([Text], ‘,\s+(\w+)’), we first have the “,” whereby it is to search for the comma. Also, the “\s+” is for searching for space, and the plus symbol is used for any double space. Then we use the (\w+) to extract our word. REGEXP_EXTRACT_NTH (string, pattern, index) This is used to search for a particular pattern within a string or substring, starting at the nth position in the string, and extracting the data element. Example: String= ‘abc 123’   To extract 123 out, we use the pattern ‘([a-z]+)\s+(\d+)’ and also specify the item index position REGEXP_EXTRACT_NTH(‘abc 123’, ‘([a-z]+)\s+(\d+)’, 2) = ‘123’ REGEXP_MATCH (string, pattern): The REGEXP_MATCH is used to look for a particular pattern within a string or substring and returns TRUE if we have an exact match. Example: In the table below, we want to search if the Student’s Details contains an Email Address. We will specify our pattern as seen below to check for all email address in the data. 1 REGEXP_MATCH 2 ( 3 [Student Details], 4 ‘([A-Za-Z0-9 ._% + -] + @ [A-Za-Z0-9 .-] + \. [Az] {2,4})’ 5) We should have this result table; REGEXP_REPLACE (string, pattern, replacement) This function is used for searching for a particular pattern within a string or substring and replacing that data element with a different data element. Example: In this table below we want to replace all this email address with a space. To handle this, we’ll use the code below, which has same pattern we used earlier to search for email addresses. Whenever it finds the email address in the text, it replaces it with a space. 1 ( 2 [Messy Data], 3 ‘([A-Za-Z0-9 ._% + -] + @ [A-Za-Z0-9 .-] + \. [Az] {2,4})’, 4 ” 5 )   We should have our output as seen below; Hope you enjoyed this post. Thanks for reading.

Scroll to Top