title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C Program for Tower of Hanoi
The tower of Hanoi is a mathematical puzzle. It consists of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same stack on the third rod. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules− Only one disk can be moved at a time. Only one disk can be moved at a time. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. No disk may be placed on top of a smaller disk. No disk may be placed on top of a smaller disk. Input − 3 Output − A to B A to C B to C A to B C to A C to B A to B Explanation − uses recursive function & solves the tower of Hanoi. #include<stdio.h> void TOH(int n,char x,char y,char z) { if(n>0) { TOH(n-1,x,z,y); printf("\n%c to %c",x,y); TOH(n-1,z,y,x); } } int main() { int n=3; TOH(n,'A','B','C'); } A to B A to C B to C A to B C to A C to B A to B
[ { "code": null, "e": 1368, "s": 1062, "text": "The tower of Hanoi is a mathematical puzzle. It consists of three rods and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same stack on the third rod." }, { "code": null, "e": 1476, "s": 1368, "text": "The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules−" }, { "code": null, "e": 1514, "s": 1476, "text": "Only one disk can be moved at a time." }, { "code": null, "e": 1552, "s": 1514, "text": "Only one disk can be moved at a time." }, { "code": null, "e": 1728, "s": 1552, "text": "Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack." }, { "code": null, "e": 1904, "s": 1728, "text": "Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack." }, { "code": null, "e": 1952, "s": 1904, "text": "No disk may be placed on top of a smaller disk." }, { "code": null, "e": 2000, "s": 1952, "text": "No disk may be placed on top of a smaller disk." }, { "code": null, "e": 2011, "s": 2000, "text": "Input − 3" }, { "code": null, "e": 2030, "s": 2011, "text": "Output − A to B " }, { "code": null, "e": 2052, "s": 2030, "text": " A to C " }, { "code": null, "e": 2073, "s": 2052, "text": " B to C " }, { "code": null, "e": 2093, "s": 2073, "text": " A to B " }, { "code": null, "e": 2113, "s": 2093, "text": " C to A " }, { "code": null, "e": 2133, "s": 2113, "text": " C to B " }, { "code": null, "e": 2208, "s": 2133, "text": "A to B Explanation − uses recursive function & solves the tower of Hanoi." }, { "code": null, "e": 2411, "s": 2208, "text": "#include<stdio.h>\nvoid TOH(int n,char x,char y,char z) {\n if(n>0) {\n TOH(n-1,x,z,y);\n printf(\"\\n%c to %c\",x,y);\n TOH(n-1,z,y,x);\n }\n}\nint main() {\n int n=3;\n TOH(n,'A','B','C');\n}" }, { "code": null, "e": 2460, "s": 2411, "text": "A to B\nA to C\nB to C\nA to B\nC to A\nC to B\nA to B" } ]
Pandas - Plotting
Pandas uses the plot() method to create diagrams. We can use Pyplot, a submodule of the Matplotlib library to visualize the diagram on the screen. Read more about Matplotlib in our Matplotlib Tutorial. Import pyplot from Matplotlib and visualize our DataFrame: The examples in this page uses a CSV file called: 'data.csv'. Download data.csv or Open data.csv Specify that you want a scatter plot with the kind argument: kind = 'scatter' A scatter plot needs an x- and a y-axis. In the example below we will use "Duration" for the x-axis and "Calories" for the y-axis. Include the x and y arguments like this: x = 'Duration', y = 'Calories' Remember: In the previous example, we learned that the correlation between "Duration" and "Calories" was 0.922721, and we conluded with the fact that higher duration means more calories burned. By looking at the scatterplot, I will agree. Let's create another scatterplot, where there is a bad relationship between the columns, like "Duration" and "Maxpulse", with the correlation 0.009403: A scatterplot where there are no relationship between the columns: Use the kind argument to specify that you want a histogram: kind = 'hist' A histogram needs only one column. A histogram shows us the frequency of each interval, e.g. how many workouts lasted between 50 and 60 minutes? In the example below we will use the "Duration" column to create the histogram: Note: The histogram tells us that there were over 100 workouts that lasted between 50 and 60 minutes. Insert a correct syntax for visualize the data in DataFrame as a diagram (plotting). df.() Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 51, "s": 0, "text": "Pandas uses the plot() method to create \ndiagrams." }, { "code": null, "e": 149, "s": 51, "text": "We can use Pyplot, a submodule of the Matplotlib library to visualize the \ndiagram on the screen." }, { "code": null, "e": 204, "s": 149, "text": "Read more about Matplotlib in our Matplotlib Tutorial." }, { "code": null, "e": 263, "s": 204, "text": "Import pyplot from Matplotlib and visualize our DataFrame:" }, { "code": null, "e": 325, "s": 263, "text": "The examples in this page uses a CSV file called: 'data.csv'." }, { "code": null, "e": 361, "s": 325, "text": "Download data.csv or Open \ndata.csv" }, { "code": null, "e": 423, "s": 361, "text": "Specify that you want a scatter plot with the \nkind argument:" }, { "code": null, "e": 440, "s": 423, "text": "kind = 'scatter'" }, { "code": null, "e": 481, "s": 440, "text": "A scatter plot needs an x- and a y-axis." }, { "code": null, "e": 571, "s": 481, "text": "In the example below we will use \"Duration\" for the x-axis\nand \"Calories\" for the y-axis." }, { "code": null, "e": 612, "s": 571, "text": "Include the x and y arguments like this:" }, { "code": null, "e": 643, "s": 612, "text": "x = 'Duration', y = 'Calories'" }, { "code": null, "e": 850, "s": 643, "text": "\nRemember:\n In the previous example, we learned that the correlation between \"Duration\" and \"Calories\"\n was 0.922721, and we conluded with the fact that\n higher duration means more calories burned." }, { "code": null, "e": 897, "s": 850, "text": "By looking at the scatterplot, I will agree. " }, { "code": null, "e": 1049, "s": 897, "text": "Let's create another scatterplot, where there is a bad relationship between the columns, like \"Duration\" and \"Maxpulse\", with the correlation 0.009403:" }, { "code": null, "e": 1116, "s": 1049, "text": "A scatterplot where there are no relationship between the columns:" }, { "code": null, "e": 1178, "s": 1116, "text": "Use the \nkind argument \nto specify that you want a histogram:" }, { "code": null, "e": 1192, "s": 1178, "text": "kind = 'hist'" }, { "code": null, "e": 1227, "s": 1192, "text": "A histogram needs only one column." }, { "code": null, "e": 1337, "s": 1227, "text": "A histogram shows us the frequency of each interval, e.g. how many workouts lasted between 50 and 60 minutes?" }, { "code": null, "e": 1417, "s": 1337, "text": "In the example below we will use the \"Duration\" column to create the histogram:" }, { "code": null, "e": 1524, "s": 1417, "text": "\nNote:\n The histogram tells us that there were over 100 workouts that lasted between 50 and 60 minutes." }, { "code": null, "e": 1609, "s": 1524, "text": "Insert a correct syntax for visualize the data in DataFrame as a diagram (plotting)." }, { "code": null, "e": 1616, "s": 1609, "text": "df.()\n" }, { "code": null, "e": 1635, "s": 1616, "text": "Start the Exercise" }, { "code": null, "e": 1668, "s": 1635, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1710, "s": 1668, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1817, "s": 1710, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1836, "s": 1817, "text": "[email protected]" } ]
How to Install Apache Kafka Using Docker — The Easy Way | by Dario Radečić | Towards Data Science
In a world of big data, a reliable streaming platform is a must. That’s where Kafka comes in. And today, you’ll learn how to install it on your machine and create your first Kafka topic. Want to sit back and watch? I’ve got you covered: Today’s article covers the following topics: Approaches to installing Kafka Terminology rundown — Everything you need to know Install Kafka using Docker Connect to Kafka shell Create your first Kafka topic Connect Visual Studio Code to Kafka container Summary & Next steps You can install Kafka on any OS, like Windows, Mac, or Linux, but the installation process is somewhat different for every OS. So, instead of covering all of them, my goal was to install Kafka in a virtual machine and use Linux Ubuntu as a distribution of choice. But, since I’m using a MacBook with the M1 chip, managing virtual machines isn’t all that easy. Attaching ISO images to VirtualBox just fails. If anyone knows the solution, please let me know in the comment section below. So instead, you’ll use Docker. I think it’s an even better option, since you don’t have to install the tools manually. Instead, you’ll write one simple Docker compose file, which will take care of everything. And the best part is — it will work on any OS. So, if you are following this article on Windows or Linux, everything will still work. You only need to have Docker and Docker compose installed. Refer to the video if you need instructions on installing Docker. This article is by no means an extensive guide to Docker or Kafka. Heck, it shouldn’t even be your first article on these topics. The rest of the section will give only high-level definitions and overviews. There’s a lot more going in to these concepts that are way beyond the scope of this article. Kafka — Basically an event streaming platform. It enables users to collect, store, and process data to build real-time event-driven applications. It’s written in Java and Scala, but you don’t have to know these to work with Kafka. There’s also a Python API. Kafka broker — A single Kafka Cluster is made of Brokers. They handle producers and consumers and keeps data replicated in the cluster. Kafka topic — A category to which records are published. Imagine you had a large news site — each news category could be a single Kafka topic. Kafka producer — An application (a piece of code) you write to get data to Kafka. Kafka consumer — A program you write to get data out of Kafka. Sometimes a consumer is also a producer, as it puts data elsewhere in Kafka. Zookeeper — Used to manage a Kafka cluster, track node status, and maintain a list of topics and messages. Kafka version 2.8.0 introduced early access to a Kafka version without Zookeeper, but it’s not ready yet for production environments. Docker — An open-source platform for building, deploying, and managing containers. It allows you to package your applications into containers, which simplifies application distribution. That way, you know if the application works on your machine, it will work on any machine you deploy it to. You now have some basic high-level understanding of the concepts in Kafka, Zookeeper, and Docker. The next step is to install Zookeeper and Kafka using Docker. You will need two Docker images to get Kafka running: wurstmeister/zookeeper wurstmeister/kafka You don’t have to download them manually, as a docker-compose.yml will do that for you. Here’s the code, so you can copy it to your machine: version: '3'services: zookeeper: image: wurstmeister/zookeeper container_name: zookeeper ports: - "2181:2181" kafka: image: wurstmeister/kafka container_name: kafka ports: - "9092:9092" environment: KAFKA_ADVERTISED_HOST_NAME: localhost KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 Make sure to edit the ports if either 2181 or 9092 aren’t available on your machine. You can now open up a Terminal and navigate to a folder where you saved docker-compose.yml file. Execute the following command to pull the images and create containers: docker-compose -f docker-compose.yml up -d The -d means both Zookeeper and Kafka will run in the background, so you’ll have access to the Terminal after they start. You should now see the download and configuration process printed to the Terminal. Here’s how mine looks like, but keep in mind — I already have these two configured: And that’s it! You can use the docker ps command to verify both are running: But what can you now do with these two containers? Let’s cover that next, by opening up a Kafka terminal and creating your first Kafka topic. Once Zookeeper and Kafka containers are running, you can execute the following Terminal command to start a Kafka shell: docker exec -it kafka /bin/sh Just replace kafka with the value of container_name, if you’ve decided to name it differently in the docker-compose.yml file. Here’s what you should see: Now you have everything needed to create your first Kafka topic! All Kafka shell scripts are located in /opt/kafka_<version>/bin: Here’s the command you’ll have to issue to create a Kafka topic: kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic first_kafka_topic Where first_kafka_topic is the name of your topic. Since this is a dummy environment, you can keep replication-factor and partitions at 1. Here’s the output you should see: And that’s it! The topic will be created after a second or so. You can list all Kafka topics with the following command: kafka-topics.sh --list --zookeeper zookeeper:2181 Here’s what it prints on my machine: And that’s how you create a Kafka topic. You won’t do anything with it today. The following article will cover how to write Producers and Consumers in Python, but there’s still something else to cover today. No, you won’t write producers and consumers today, but you will in the following article. Manually transferring Python files from your machine to a Docker container is tedious. You can write code directly on the Kafka container with Visual Studio Code. You will need an official Docker extension by Microsoft, so install it if you don’t have it already: Once it installs, click on the Docker icon in the left sidebar. You’ll see all running containers listed on the top: You can attach Visual Studio Code to this container by right-clicking on it and choosing the Attach Visual Studio Code option. It will open a new window and ask you which folder to open. Go to root (/), and you should see all the folders you saw minutes ago when you were in the shell: Easy, right? Well, it is, and it’ll save you much time when writing consumers and producer code. And that does it for today. You went from installing Docker, Kafka, and Zookeeper to creating your first Kafka topic and connecting to Docker containers through Shell and Visual Studio Code. Refer to the video if you need detailed instructions on installing Docker and attaching Kafka shell through Visual Studio Code. The following article will cover consumers and producers in Python, so stay tuned if you want to learn more about Kafka. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Follow me on Medium for more stories like this Sign up for my newsletter Connect on LinkedIn Originally published at https://betterdatascience.com on September 23, 2021.
[ { "code": null, "e": 359, "s": 172, "text": "In a world of big data, a reliable streaming platform is a must. That’s where Kafka comes in. And today, you’ll learn how to install it on your machine and create your first Kafka topic." }, { "code": null, "e": 409, "s": 359, "text": "Want to sit back and watch? I’ve got you covered:" }, { "code": null, "e": 454, "s": 409, "text": "Today’s article covers the following topics:" }, { "code": null, "e": 485, "s": 454, "text": "Approaches to installing Kafka" }, { "code": null, "e": 535, "s": 485, "text": "Terminology rundown — Everything you need to know" }, { "code": null, "e": 562, "s": 535, "text": "Install Kafka using Docker" }, { "code": null, "e": 585, "s": 562, "text": "Connect to Kafka shell" }, { "code": null, "e": 615, "s": 585, "text": "Create your first Kafka topic" }, { "code": null, "e": 661, "s": 615, "text": "Connect Visual Studio Code to Kafka container" }, { "code": null, "e": 682, "s": 661, "text": "Summary & Next steps" }, { "code": null, "e": 946, "s": 682, "text": "You can install Kafka on any OS, like Windows, Mac, or Linux, but the installation process is somewhat different for every OS. So, instead of covering all of them, my goal was to install Kafka in a virtual machine and use Linux Ubuntu as a distribution of choice." }, { "code": null, "e": 1168, "s": 946, "text": "But, since I’m using a MacBook with the M1 chip, managing virtual machines isn’t all that easy. Attaching ISO images to VirtualBox just fails. If anyone knows the solution, please let me know in the comment section below." }, { "code": null, "e": 1570, "s": 1168, "text": "So instead, you’ll use Docker. I think it’s an even better option, since you don’t have to install the tools manually. Instead, you’ll write one simple Docker compose file, which will take care of everything. And the best part is — it will work on any OS. So, if you are following this article on Windows or Linux, everything will still work. You only need to have Docker and Docker compose installed." }, { "code": null, "e": 1636, "s": 1570, "text": "Refer to the video if you need instructions on installing Docker." }, { "code": null, "e": 1936, "s": 1636, "text": "This article is by no means an extensive guide to Docker or Kafka. Heck, it shouldn’t even be your first article on these topics. The rest of the section will give only high-level definitions and overviews. There’s a lot more going in to these concepts that are way beyond the scope of this article." }, { "code": null, "e": 2194, "s": 1936, "text": "Kafka — Basically an event streaming platform. It enables users to collect, store, and process data to build real-time event-driven applications. It’s written in Java and Scala, but you don’t have to know these to work with Kafka. There’s also a Python API." }, { "code": null, "e": 2330, "s": 2194, "text": "Kafka broker — A single Kafka Cluster is made of Brokers. They handle producers and consumers and keeps data replicated in the cluster." }, { "code": null, "e": 2473, "s": 2330, "text": "Kafka topic — A category to which records are published. Imagine you had a large news site — each news category could be a single Kafka topic." }, { "code": null, "e": 2555, "s": 2473, "text": "Kafka producer — An application (a piece of code) you write to get data to Kafka." }, { "code": null, "e": 2695, "s": 2555, "text": "Kafka consumer — A program you write to get data out of Kafka. Sometimes a consumer is also a producer, as it puts data elsewhere in Kafka." }, { "code": null, "e": 2936, "s": 2695, "text": "Zookeeper — Used to manage a Kafka cluster, track node status, and maintain a list of topics and messages. Kafka version 2.8.0 introduced early access to a Kafka version without Zookeeper, but it’s not ready yet for production environments." }, { "code": null, "e": 3229, "s": 2936, "text": "Docker — An open-source platform for building, deploying, and managing containers. It allows you to package your applications into containers, which simplifies application distribution. That way, you know if the application works on your machine, it will work on any machine you deploy it to." }, { "code": null, "e": 3389, "s": 3229, "text": "You now have some basic high-level understanding of the concepts in Kafka, Zookeeper, and Docker. The next step is to install Zookeeper and Kafka using Docker." }, { "code": null, "e": 3443, "s": 3389, "text": "You will need two Docker images to get Kafka running:" }, { "code": null, "e": 3466, "s": 3443, "text": "wurstmeister/zookeeper" }, { "code": null, "e": 3485, "s": 3466, "text": "wurstmeister/kafka" }, { "code": null, "e": 3626, "s": 3485, "text": "You don’t have to download them manually, as a docker-compose.yml will do that for you. Here’s the code, so you can copy it to your machine:" }, { "code": null, "e": 3946, "s": 3626, "text": "version: '3'services: zookeeper: image: wurstmeister/zookeeper container_name: zookeeper ports: - \"2181:2181\" kafka: image: wurstmeister/kafka container_name: kafka ports: - \"9092:9092\" environment: KAFKA_ADVERTISED_HOST_NAME: localhost KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181" }, { "code": null, "e": 4200, "s": 3946, "text": "Make sure to edit the ports if either 2181 or 9092 aren’t available on your machine. You can now open up a Terminal and navigate to a folder where you saved docker-compose.yml file. Execute the following command to pull the images and create containers:" }, { "code": null, "e": 4243, "s": 4200, "text": "docker-compose -f docker-compose.yml up -d" }, { "code": null, "e": 4365, "s": 4243, "text": "The -d means both Zookeeper and Kafka will run in the background, so you’ll have access to the Terminal after they start." }, { "code": null, "e": 4532, "s": 4365, "text": "You should now see the download and configuration process printed to the Terminal. Here’s how mine looks like, but keep in mind — I already have these two configured:" }, { "code": null, "e": 4609, "s": 4532, "text": "And that’s it! You can use the docker ps command to verify both are running:" }, { "code": null, "e": 4751, "s": 4609, "text": "But what can you now do with these two containers? Let’s cover that next, by opening up a Kafka terminal and creating your first Kafka topic." }, { "code": null, "e": 4871, "s": 4751, "text": "Once Zookeeper and Kafka containers are running, you can execute the following Terminal command to start a Kafka shell:" }, { "code": null, "e": 4901, "s": 4871, "text": "docker exec -it kafka /bin/sh" }, { "code": null, "e": 5027, "s": 4901, "text": "Just replace kafka with the value of container_name, if you’ve decided to name it differently in the docker-compose.yml file." }, { "code": null, "e": 5055, "s": 5027, "text": "Here’s what you should see:" }, { "code": null, "e": 5120, "s": 5055, "text": "Now you have everything needed to create your first Kafka topic!" }, { "code": null, "e": 5185, "s": 5120, "text": "All Kafka shell scripts are located in /opt/kafka_<version>/bin:" }, { "code": null, "e": 5250, "s": 5185, "text": "Here’s the command you’ll have to issue to create a Kafka topic:" }, { "code": null, "e": 5366, "s": 5250, "text": "kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic first_kafka_topic" }, { "code": null, "e": 5505, "s": 5366, "text": "Where first_kafka_topic is the name of your topic. Since this is a dummy environment, you can keep replication-factor and partitions at 1." }, { "code": null, "e": 5539, "s": 5505, "text": "Here’s the output you should see:" }, { "code": null, "e": 5660, "s": 5539, "text": "And that’s it! The topic will be created after a second or so. You can list all Kafka topics with the following command:" }, { "code": null, "e": 5710, "s": 5660, "text": "kafka-topics.sh --list --zookeeper zookeeper:2181" }, { "code": null, "e": 5747, "s": 5710, "text": "Here’s what it prints on my machine:" }, { "code": null, "e": 5955, "s": 5747, "text": "And that’s how you create a Kafka topic. You won’t do anything with it today. The following article will cover how to write Producers and Consumers in Python, but there’s still something else to cover today." }, { "code": null, "e": 6208, "s": 5955, "text": "No, you won’t write producers and consumers today, but you will in the following article. Manually transferring Python files from your machine to a Docker container is tedious. You can write code directly on the Kafka container with Visual Studio Code." }, { "code": null, "e": 6309, "s": 6208, "text": "You will need an official Docker extension by Microsoft, so install it if you don’t have it already:" }, { "code": null, "e": 6426, "s": 6309, "text": "Once it installs, click on the Docker icon in the left sidebar. You’ll see all running containers listed on the top:" }, { "code": null, "e": 6613, "s": 6426, "text": "You can attach Visual Studio Code to this container by right-clicking on it and choosing the Attach Visual Studio Code option. It will open a new window and ask you which folder to open." }, { "code": null, "e": 6712, "s": 6613, "text": "Go to root (/), and you should see all the folders you saw minutes ago when you were in the shell:" }, { "code": null, "e": 6809, "s": 6712, "text": "Easy, right? Well, it is, and it’ll save you much time when writing consumers and producer code." }, { "code": null, "e": 7000, "s": 6809, "text": "And that does it for today. You went from installing Docker, Kafka, and Zookeeper to creating your first Kafka topic and connecting to Docker containers through Shell and Visual Studio Code." }, { "code": null, "e": 7128, "s": 7000, "text": "Refer to the video if you need detailed instructions on installing Docker and attaching Kafka shell through Visual Studio Code." }, { "code": null, "e": 7249, "s": 7128, "text": "The following article will cover consumers and producers in Python, so stay tuned if you want to learn more about Kafka." }, { "code": null, "e": 7432, "s": 7249, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 7443, "s": 7432, "text": "medium.com" }, { "code": null, "e": 7490, "s": 7443, "text": "Follow me on Medium for more stories like this" }, { "code": null, "e": 7516, "s": 7490, "text": "Sign up for my newsletter" }, { "code": null, "e": 7536, "s": 7516, "text": "Connect on LinkedIn" } ]
Program to print its script name as output in Python
In this tutorial, we are going to write a program that prints the name of the Python script file. We can find the script name using the sys module. The sys module will store all the command line arguments of python command in the sys.argv list. The first element in the list is the script name. We can extract it from that list. Python makes it easy. Let's see the steps involved in the program. Import the sys module. Import the sys module. Now, print the first element of the sys.argv list. Now, print the first element of the sys.argv list. That's it. You got the script name. That's it. You got the script name. Let's see it practically. Live Demo # importing the sys module import sys # importing os module for absolute path import os # printing the script name # first element of sys.argv list print(os.path.abspath(sys.argv[0])) If you run the above code, you will get the absolute path of your Python script. C:\Users\hafeezulkareem\Desktop\sample\tutorialspoint.py If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1210, "s": 1062, "text": "In this tutorial, we are going to write a program that prints the name of the Python script file. We can find the script name using the sys module." }, { "code": null, "e": 1413, "s": 1210, "text": "The sys module will store all the command line arguments of python command in the sys.argv list. The first element in the list is the script name. We can extract it from that list. Python makes it easy." }, { "code": null, "e": 1458, "s": 1413, "text": "Let's see the steps involved in the program." }, { "code": null, "e": 1481, "s": 1458, "text": "Import the sys module." }, { "code": null, "e": 1504, "s": 1481, "text": "Import the sys module." }, { "code": null, "e": 1555, "s": 1504, "text": "Now, print the first element of the sys.argv list." }, { "code": null, "e": 1606, "s": 1555, "text": "Now, print the first element of the sys.argv list." }, { "code": null, "e": 1642, "s": 1606, "text": "That's it. You got the script name." }, { "code": null, "e": 1678, "s": 1642, "text": "That's it. You got the script name." }, { "code": null, "e": 1704, "s": 1678, "text": "Let's see it practically." }, { "code": null, "e": 1715, "s": 1704, "text": " Live Demo" }, { "code": null, "e": 1899, "s": 1715, "text": "# importing the sys module\nimport sys\n# importing os module for absolute path\nimport os\n# printing the script name\n# first element of sys.argv list\nprint(os.path.abspath(sys.argv[0]))" }, { "code": null, "e": 1980, "s": 1899, "text": "If you run the above code, you will get the absolute path of your Python script." }, { "code": null, "e": 2037, "s": 1980, "text": "C:\\Users\\hafeezulkareem\\Desktop\\sample\\tutorialspoint.py" }, { "code": null, "e": 2114, "s": 2037, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
Cassandra - Drop Index
You can drop an index using the command DROP INDEX. Its syntax is as follows − DROP INDEX <identifier> Given below is an example to drop an index of a column in a table. Here we are dropping the index of the column name in the table emp. cqlsh:tp> drop index name; You can drop an index of a table using the execute() method of Session class. Follow the steps given below to drop an index from a table. Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below. //Creating Cluster.Builder object Cluster.Builder builder1 = Cluster.builder(); Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder. //Adding contact point to the Cluster.Builder object Cluster.Builder builder2 = build.addContactPoint( "127.0.0.1" ); Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object. //Building a cluster Cluster cluster = builder.build(); You can build a cluster object using a single line of code as shown below. Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Create an instance of Session object using the connect() method of Cluster class as shown below. Session session = cluster.connect( ); This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below. Session session = cluster.connect(“ Your keyspace name ” ); Here we are using the KeySpace named tp. Therefore, create the session object as shown below. Session session = cluster.connect(“ tp” ); You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh. In the following example, we are dropping an index “name” of emp table. You have to store the query in a string variable and pass it to the execute() method as shown below. //Query String query = "DROP INDEX user_name;"; session.execute(query); Given below is the complete program to drop an index in Cassandra using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Drop_Index { public static void main(String args[]){ //Query String query = "DROP INDEX user_name;"; //Creating cluster object Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();. //Creating Session object Session session = cluster.connect("tp"); //Executing the query session.execute(query); System.out.println("Index dropped"); } } Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below. $javac Drop_index.java $java Drop_index Under normal conditions, it should produce the following output − Index dropped 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2366, "s": 2287, "text": "You can drop an index using the command DROP INDEX. Its syntax is as follows −" }, { "code": null, "e": 2391, "s": 2366, "text": "DROP INDEX <identifier>\n" }, { "code": null, "e": 2526, "s": 2391, "text": "Given below is an example to drop an index of a column in a table. Here we are dropping the index of the column name in the table emp." }, { "code": null, "e": 2554, "s": 2526, "text": "cqlsh:tp> drop index name;\n" }, { "code": null, "e": 2692, "s": 2554, "text": "You can drop an index of a table using the execute() method of Session class. Follow the steps given below to drop an index from a table." }, { "code": null, "e": 2788, "s": 2692, "text": "Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below." }, { "code": null, "e": 2869, "s": 2788, "text": "//Creating Cluster.Builder object\nCluster.Builder builder1 = Cluster.builder();\n" }, { "code": null, "e": 3013, "s": 2869, "text": "Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder." }, { "code": null, "e": 3132, "s": 3013, "text": "//Adding contact point to the Cluster.Builder object\nCluster.Builder builder2 = build.addContactPoint( \"127.0.0.1\" );\n" }, { "code": null, "e": 3317, "s": 3132, "text": "Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object." }, { "code": null, "e": 3374, "s": 3317, "text": "//Building a cluster\nCluster cluster = builder.build();\n" }, { "code": null, "e": 3449, "s": 3374, "text": "You can build a cluster object using a single line of code as shown below." }, { "code": null, "e": 3524, "s": 3449, "text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n" }, { "code": null, "e": 3621, "s": 3524, "text": "Create an instance of Session object using the connect() method of Cluster class\nas shown below." }, { "code": null, "e": 3660, "s": 3621, "text": "Session session = cluster.connect( );\n" }, { "code": null, "e": 3863, "s": 3660, "text": "This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below." }, { "code": null, "e": 3924, "s": 3863, "text": "Session session = cluster.connect(“ Your keyspace name ” );\n" }, { "code": null, "e": 4018, "s": 3924, "text": "Here we are using the KeySpace named tp. Therefore, create the session object as shown below." }, { "code": null, "e": 4062, "s": 4018, "text": "Session session = cluster.connect(“ tp” );\n" }, { "code": null, "e": 4311, "s": 4062, "text": "You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh." }, { "code": null, "e": 4484, "s": 4311, "text": "In the following example, we are dropping an index “name” of emp table. You have to store the query in a string variable and pass it to the execute() method as shown below." }, { "code": null, "e": 4557, "s": 4484, "text": "//Query\nString query = \"DROP INDEX user_name;\";\nsession.execute(query);\n" }, { "code": null, "e": 4639, "s": 4557, "text": "Given below is the complete program to drop an index in Cassandra using Java API." }, { "code": null, "e": 5172, "s": 4639, "text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Drop_Index {\n\n public static void main(String args[]){\n \n //Query\n String query = \"DROP INDEX user_name;\";\n \n //Creating cluster object\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();.\n \n //Creating Session object\n Session session = cluster.connect(\"tp\"); \n \n //Executing the query\n session.execute(query);\n \n System.out.println(\"Index dropped\");\n }\n}" }, { "code": null, "e": 5324, "s": 5172, "text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below." }, { "code": null, "e": 5365, "s": 5324, "text": "$javac Drop_index.java\n$java Drop_index\n" }, { "code": null, "e": 5431, "s": 5365, "text": "Under normal conditions, it should produce the following output −" }, { "code": null, "e": 5446, "s": 5431, "text": "Index dropped\n" }, { "code": null, "e": 5479, "s": 5446, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 5493, "s": 5479, "text": " Navdeep Kaur" }, { "code": null, "e": 5528, "s": 5493, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5546, "s": 5528, "text": " Bigdata Engineer" }, { "code": null, "e": 5553, "s": 5546, "text": " Print" }, { "code": null, "e": 5564, "s": 5553, "text": " Add Notes" } ]
Google Guice - Optional Injection
Injection is a process of injecting dependeny into an object. Optional injection means injecting the dependency if exists. Method and Field injections may be optionally dependent and should have some default value if dependency is not present. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() {} } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { private String dbUrl = "jdbc:mysql://localhost:5326/emp"; public SpellCheckerImpl(){} @Inject(optional=true) public void setDbUrl(@Named("JDBC") String dbUrl){ this.dbUrl = dbUrl; } @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp 27 Lectures 1.5 hours Lemuel Ogbunude Print Add Notes Bookmark this page
[ { "code": null, "e": 2369, "s": 2102, "text": "Injection is a process of injecting dependeny into an object. Optional injection means injecting the dependency if exists. Method and Field injections may be optionally dependent and should have some default value if dependency is not present. See the example below." }, { "code": null, "e": 2408, "s": 2369, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 2425, "s": 2408, "text": "GuiceTester.java" }, { "code": null, "e": 3782, "s": 2425, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() {} \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n private String dbUrl = \"jdbc:mysql://localhost:5326/emp\";\n\n public SpellCheckerImpl(){}\n \n @Inject(optional=true)\n public void setDbUrl(@Named(\"JDBC\") String dbUrl){\n this.dbUrl = dbUrl;\n }\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 3843, "s": 3782, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 3898, "s": 3843, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 3933, "s": 3898, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3950, "s": 3933, "text": " Lemuel Ogbunude" }, { "code": null, "e": 3957, "s": 3950, "text": " Print" }, { "code": null, "e": 3968, "s": 3957, "text": " Add Notes" } ]
Bounded Types with Generics in Java - GeeksforGeeks
15 Mar, 2022 There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Numbers or their subclasses. This is what bounded type parameters are for. Sometimes we don’t want the whole class to be parameterized. In that case, we can create a Java generics method. Since the constructor is a special kind of method, we can use generics type in constructors too. Suppose we want to restrict the type of objects that can be used in the parameterized type. For example, in a method that compares two objects and we want to make sure that the accepted objects are Comparables. The invocation of these methods is similar to the unbounded method except that if we will try to use any class that is not Comparable, it will throw compile time error. How to Declare a Bounded Type Parameter in Java? List the type parameter’s name,Along with the extends keywordAnd by its upper bound. (which in the below example c is A.) List the type parameter’s name, Along with the extends keyword And by its upper bound. (which in the below example c is A.) Syntax <T extends superClassName> Note that, in this context, extends is used in a general sense to mean either “extends” (as in classes). Also, This specifies that T can only be replaced by superClassName or subclasses of superClassName. Thus, a superclass defines an inclusive, upper limit. Let’s take an example of how to implement bounded types (extend superclass) with generics. Java // This class only accepts type parameters as any class// which extends class A or class A itself.// Passing any other type will cause compiler time error class Bound<T extends A>{ private T objRef; public Bound(T obj){ this.objRef = obj; } public void doRunTest(){ this.objRef.displayClass(); }} class A{ public void displayClass() { System.out.println("Inside super class A"); }} class B extends A{ public void displayClass() { System.out.println("Inside sub class B"); }} class C extends A{ public void displayClass() { System.out.println("Inside sub class C"); }} public class BoundedClass{ public static void main(String a[]) { // Creating object of sub class C and // passing it to Bound as a type parameter. Bound<C> bec = new Bound<C>(new C()); bec.doRunTest(); // Creating object of sub class B and // passing it to Bound as a type parameter. Bound<B> beb = new Bound<B>(new B()); beb.doRunTest(); // similarly passing super class A Bound<A> bea = new Bound<A>(new A()); bea.doRunTest(); }} Inside sub class C Inside sub class B Inside super class A Now, we are restricted to only type A and its subclasses, So it will throw an error for any other type of subclasses. Java // This class only accepts type parameters as any class// which extends class A or class A itself.// Passing any other type will cause compiler time error class Bound<T extends A>{ private T objRef; public Bound(T obj){ this.objRef = obj; } public void doRunTest(){ this.objRef.displayClass(); }} class A{ public void displayClass() { System.out.println("Inside super class A"); }} class B extends A{ public void displayClass() { System.out.println("Inside sub class B"); }} class C extends A{ public void displayClass() { System.out.println("Inside sub class C"); }} public class BoundedClass{ public static void main(String a[]) { // Creating object of sub class C and // passing it to Bound as a type parameter. Bound<C> bec = new Bound<C>(new C()); bec.doRunTest(); // Creating object of sub class B and // passing it to Bound as a type parameter. Bound<B> beb = new Bound<B>(new B()); beb.doRunTest(); // similarly passing super class A Bound<A> bea = new Bound<A>(new A()); bea.doRunTest(); Bound<String> bes = new Bound<String>(new String()); bea.doRunTest(); }} Output : error: type argument String is not within bounds of type-variable T Bounded type parameters can be used with methods as well as classes and interfaces. Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can’t have more than one class in multiple bounds. Syntax: <T extends superClassName & Interface> Java class Bound<T extends A & B>{ private T objRef; public Bound(T obj){ this.objRef = obj; } public void doRunTest(){ this.objRef.displayClass(); }} interface B{ public void displayClass();} class A implements B{ public void displayClass() { System.out.println("Inside super class A"); }} public class BoundedClass{ public static void main(String a[]) { //Creating object of sub class A and //passing it to Bound as a type parameter. Bound<A> bea = new Bound<A>(new A()); bea.doRunTest(); }} Inside super class A This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nishkarshgandhi simmytarika5 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Set in Java Singleton Class in Java LinkedList in Java Overriding in Java Multithreading in Java Collections in Java Queue Interface In Java Different ways of Reading a text file in Java Initializing a List in Java
[ { "code": null, "e": 24064, "s": 24036, "text": "\n15 Mar, 2022" }, { "code": null, "e": 24341, "s": 24064, "text": "There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Numbers or their subclasses. This is what bounded type parameters are for. " }, { "code": null, "e": 24551, "s": 24341, "text": "Sometimes we don’t want the whole class to be parameterized. In that case, we can create a Java generics method. Since the constructor is a special kind of method, we can use generics type in constructors too." }, { "code": null, "e": 24762, "s": 24551, "text": "Suppose we want to restrict the type of objects that can be used in the parameterized type. For example, in a method that compares two objects and we want to make sure that the accepted objects are Comparables." }, { "code": null, "e": 24931, "s": 24762, "text": "The invocation of these methods is similar to the unbounded method except that if we will try to use any class that is not Comparable, it will throw compile time error." }, { "code": null, "e": 24981, "s": 24931, "text": "How to Declare a Bounded Type Parameter in Java? " }, { "code": null, "e": 25103, "s": 24981, "text": "List the type parameter’s name,Along with the extends keywordAnd by its upper bound. (which in the below example c is A.)" }, { "code": null, "e": 25135, "s": 25103, "text": "List the type parameter’s name," }, { "code": null, "e": 25166, "s": 25135, "text": "Along with the extends keyword" }, { "code": null, "e": 25227, "s": 25166, "text": "And by its upper bound. (which in the below example c is A.)" }, { "code": null, "e": 25234, "s": 25227, "text": "Syntax" }, { "code": null, "e": 25261, "s": 25234, "text": "<T extends superClassName>" }, { "code": null, "e": 25520, "s": 25261, "text": "Note that, in this context, extends is used in a general sense to mean either “extends” (as in classes). Also, This specifies that T can only be replaced by superClassName or subclasses of superClassName. Thus, a superclass defines an inclusive, upper limit." }, { "code": null, "e": 25611, "s": 25520, "text": "Let’s take an example of how to implement bounded types (extend superclass) with generics." }, { "code": null, "e": 25616, "s": 25611, "text": "Java" }, { "code": "// This class only accepts type parameters as any class// which extends class A or class A itself.// Passing any other type will cause compiler time error class Bound<T extends A>{ private T objRef; public Bound(T obj){ this.objRef = obj; } public void doRunTest(){ this.objRef.displayClass(); }} class A{ public void displayClass() { System.out.println(\"Inside super class A\"); }} class B extends A{ public void displayClass() { System.out.println(\"Inside sub class B\"); }} class C extends A{ public void displayClass() { System.out.println(\"Inside sub class C\"); }} public class BoundedClass{ public static void main(String a[]) { // Creating object of sub class C and // passing it to Bound as a type parameter. Bound<C> bec = new Bound<C>(new C()); bec.doRunTest(); // Creating object of sub class B and // passing it to Bound as a type parameter. Bound<B> beb = new Bound<B>(new B()); beb.doRunTest(); // similarly passing super class A Bound<A> bea = new Bound<A>(new A()); bea.doRunTest(); }}", "e": 26830, "s": 25616, "text": null }, { "code": null, "e": 26889, "s": 26830, "text": "Inside sub class C\nInside sub class B\nInside super class A" }, { "code": null, "e": 27007, "s": 26889, "text": "Now, we are restricted to only type A and its subclasses, So it will throw an error for any other type of subclasses." }, { "code": null, "e": 27012, "s": 27007, "text": "Java" }, { "code": "// This class only accepts type parameters as any class// which extends class A or class A itself.// Passing any other type will cause compiler time error class Bound<T extends A>{ private T objRef; public Bound(T obj){ this.objRef = obj; } public void doRunTest(){ this.objRef.displayClass(); }} class A{ public void displayClass() { System.out.println(\"Inside super class A\"); }} class B extends A{ public void displayClass() { System.out.println(\"Inside sub class B\"); }} class C extends A{ public void displayClass() { System.out.println(\"Inside sub class C\"); }} public class BoundedClass{ public static void main(String a[]) { // Creating object of sub class C and // passing it to Bound as a type parameter. Bound<C> bec = new Bound<C>(new C()); bec.doRunTest(); // Creating object of sub class B and // passing it to Bound as a type parameter. Bound<B> beb = new Bound<B>(new B()); beb.doRunTest(); // similarly passing super class A Bound<A> bea = new Bound<A>(new A()); bea.doRunTest(); Bound<String> bes = new Bound<String>(new String()); bea.doRunTest(); }}", "e": 28285, "s": 27012, "text": null }, { "code": null, "e": 28294, "s": 28285, "text": "Output :" }, { "code": null, "e": 28362, "s": 28294, "text": "error: type argument String is not within bounds of type-variable T" }, { "code": null, "e": 28446, "s": 28362, "text": "Bounded type parameters can be used with methods as well as classes and interfaces." }, { "code": null, "e": 28647, "s": 28446, "text": "Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can’t have more than one class in multiple bounds." }, { "code": null, "e": 28655, "s": 28647, "text": "Syntax:" }, { "code": null, "e": 28694, "s": 28655, "text": "<T extends superClassName & Interface>" }, { "code": null, "e": 28699, "s": 28694, "text": "Java" }, { "code": "class Bound<T extends A & B>{ private T objRef; public Bound(T obj){ this.objRef = obj; } public void doRunTest(){ this.objRef.displayClass(); }} interface B{ public void displayClass();} class A implements B{ public void displayClass() { System.out.println(\"Inside super class A\"); }} public class BoundedClass{ public static void main(String a[]) { //Creating object of sub class A and //passing it to Bound as a type parameter. Bound<A> bea = new Bound<A>(new A()); bea.doRunTest(); }}", "e": 29297, "s": 28699, "text": null }, { "code": null, "e": 29318, "s": 29297, "text": "Inside super class A" }, { "code": null, "e": 29742, "s": 29318, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29758, "s": 29742, "text": "nishkarshgandhi" }, { "code": null, "e": 29771, "s": 29758, "text": "simmytarika5" }, { "code": null, "e": 29776, "s": 29771, "text": "Java" }, { "code": null, "e": 29781, "s": 29776, "text": "Java" }, { "code": null, "e": 29879, "s": 29781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29888, "s": 29879, "text": "Comments" }, { "code": null, "e": 29901, "s": 29888, "text": "Old Comments" }, { "code": null, "e": 29920, "s": 29901, "text": "Interfaces in Java" }, { "code": null, "e": 29932, "s": 29920, "text": "Set in Java" }, { "code": null, "e": 29956, "s": 29932, "text": "Singleton Class in Java" }, { "code": null, "e": 29975, "s": 29956, "text": "LinkedList in Java" }, { "code": null, "e": 29994, "s": 29975, "text": "Overriding in Java" }, { "code": null, "e": 30017, "s": 29994, "text": "Multithreading in Java" }, { "code": null, "e": 30037, "s": 30017, "text": "Collections in Java" }, { "code": null, "e": 30061, "s": 30037, "text": "Queue Interface In Java" }, { "code": null, "e": 30107, "s": 30061, "text": "Different ways of Reading a text file in Java" } ]
Type of 'this' Pointer in C++ - GeeksforGeeks
06 Jan, 2022 this pointer refers to the current object of the class and passes it as a parameter to another method. In C++, this pointer is passed as a hidden argument to all non-static member function calls. Type of ‘this’ pointer: The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It depends on whether it lies inside a const or a non-const method of the class ExampleClass. 1) If the member function of class X is declared const, the type of this is const X* as shown below, CPP // CPP Program to demonstrate// if the member function of a// class X is declared const#include <iostream>using namespace std; class X { void fun() const { // this is passed as hidden argument to fun(). // Type of this is const X* const }}; 2) If the member function is declared volatile, the type of this is volatile X* as shown below, CPP // CPP Program to demonstrate// if the member function is// declared volatile#include <iostream>using namespace std; class X { void fun() volatile { // this is passed as hidden argument to fun(). // Type of this is volatile X* const }}; 3) If the member function is declared const volatile, the type of this is const volatile X* as shown below, CPP // CPP program to demonstrate// if the member function is// declared const volatile#include <iostream>using namespace std; class X { void fun() const volatile { // this is passed as hidden argument to fun(). // Type of this is const volatile X* const }}; Please note that const, volatile, and const volatile are type qualifiers. Note: ‘this’ pointer is not an lvalue. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 C++-this pointer cpp-pointer pointer C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ C++ Classes and Objects Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Virtual Function in C++ Constructors in C++ Object Oriented Programming in C++ Copy Constructor in C++ Templates in C++ with Examples
[ { "code": null, "e": 24424, "s": 24396, "text": "\n06 Jan, 2022" }, { "code": null, "e": 24621, "s": 24424, "text": "this pointer refers to the current object of the class and passes it as a parameter to another method. In C++, this pointer is passed as a hidden argument to all non-static member function calls. " }, { "code": null, "e": 24866, "s": 24621, "text": "Type of ‘this’ pointer: The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It depends on whether it lies inside a const or a non-const method of the class ExampleClass." }, { "code": null, "e": 24967, "s": 24866, "text": "1) If the member function of class X is declared const, the type of this is const X* as shown below," }, { "code": null, "e": 24971, "s": 24967, "text": "CPP" }, { "code": "// CPP Program to demonstrate// if the member function of a// class X is declared const#include <iostream>using namespace std; class X { void fun() const { // this is passed as hidden argument to fun(). // Type of this is const X* const }};", "e": 25236, "s": 24971, "text": null }, { "code": null, "e": 25332, "s": 25236, "text": "2) If the member function is declared volatile, the type of this is volatile X* as shown below," }, { "code": null, "e": 25336, "s": 25332, "text": "CPP" }, { "code": "// CPP Program to demonstrate// if the member function is// declared volatile#include <iostream>using namespace std; class X { void fun() volatile { // this is passed as hidden argument to fun(). // Type of this is volatile X* const }};", "e": 25597, "s": 25336, "text": null }, { "code": null, "e": 25705, "s": 25597, "text": "3) If the member function is declared const volatile, the type of this is const volatile X* as shown below," }, { "code": null, "e": 25709, "s": 25705, "text": "CPP" }, { "code": "// CPP program to demonstrate// if the member function is// declared const volatile#include <iostream>using namespace std; class X { void fun() const volatile { // this is passed as hidden argument to fun(). // Type of this is const volatile X* const }};", "e": 25988, "s": 25709, "text": null }, { "code": null, "e": 26062, "s": 25988, "text": "Please note that const, volatile, and const volatile are type qualifiers." }, { "code": null, "e": 26101, "s": 26062, "text": "Note: ‘this’ pointer is not an lvalue." }, { "code": null, "e": 26226, "s": 26101, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26240, "s": 26226, "text": "anshikajain26" }, { "code": null, "e": 26257, "s": 26240, "text": "C++-this pointer" }, { "code": null, "e": 26269, "s": 26257, "text": "cpp-pointer" }, { "code": null, "e": 26277, "s": 26269, "text": "pointer" }, { "code": null, "e": 26281, "s": 26277, "text": "C++" }, { "code": null, "e": 26285, "s": 26281, "text": "CPP" }, { "code": null, "e": 26383, "s": 26285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26392, "s": 26383, "text": "Comments" }, { "code": null, "e": 26405, "s": 26392, "text": "Old Comments" }, { "code": null, "e": 26424, "s": 26405, "text": "Inheritance in C++" }, { "code": null, "e": 26448, "s": 26424, "text": "C++ Classes and Objects" }, { "code": null, "e": 26476, "s": 26448, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26504, "s": 26476, "text": "Operator Overloading in C++" }, { "code": null, "e": 26539, "s": 26504, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26563, "s": 26539, "text": "Virtual Function in C++" }, { "code": null, "e": 26583, "s": 26563, "text": "Constructors in C++" }, { "code": null, "e": 26618, "s": 26583, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 26642, "s": 26618, "text": "Copy Constructor in C++" } ]
Equals(String, String) Method in C#
The Equals() method in C# is used to check whether two String objects have the same value or not. bool string.Equals(string s1, string s2) Above, s1 and s2 are the strings to be compared. Live Demo using System; public class Demo { public static void Main(string[] args) { string s1 = "Kevin"; string s2 = "Tom"; string s3 = s2; Console.WriteLine("String1 = "+s1); Console.WriteLine("String2 = "+s2); Console.WriteLine("Are both the strings equal? = "+s1.Equals(s2)); Console.WriteLine("Are both the strings equal? = "+s2.Equals(s3)); } } String1 = Kevin String2 = Tom Are both the strings equal? = False Are both the strings equal? = True Live Demo using System; public class Demo { public static void Main(string[] args) { string s1 = "David"; string s2 = "David"; string s3 = s2; string s4 = "Tom"; string s5 = s4; Console.WriteLine("String1 = "+s1); Console.WriteLine("String2 = "+s2); Console.WriteLine("String3 = "+s3); Console.WriteLine("String4 = "+s4); Console.WriteLine("String5 = "+s5); Console.WriteLine("Is s1 and s2 equal? = "+s1.Equals(s2)); Console.WriteLine("Is s2 and s3 equal? = "+s2.Equals(s3)); Console.WriteLine("Is s3 and s4 equal? = "+s3.Equals(s4)); Console.WriteLine("Is s4 and s5 equal? = "+s4.Equals(s5)); } } String1 = David String2 = David String3 = David String4 = Tom String5 = Tom Is s1 and s2 equal? = True Is s2 and s3 equal? = True Is s3 and s4 equal? = False Is s4 and s5 equal? = True
[ { "code": null, "e": 1160, "s": 1062, "text": "The Equals() method in C# is used to check whether two String objects have the same value or not." }, { "code": null, "e": 1201, "s": 1160, "text": "bool string.Equals(string s1, string s2)" }, { "code": null, "e": 1250, "s": 1201, "text": "Above, s1 and s2 are the strings to be compared." }, { "code": null, "e": 1261, "s": 1250, "text": " Live Demo" }, { "code": null, "e": 1650, "s": 1261, "text": "using System;\npublic class Demo {\n public static void Main(string[] args) {\n string s1 = \"Kevin\";\n string s2 = \"Tom\";\n string s3 = s2;\n Console.WriteLine(\"String1 = \"+s1);\n Console.WriteLine(\"String2 = \"+s2);\n Console.WriteLine(\"Are both the strings equal? = \"+s1.Equals(s2));\n Console.WriteLine(\"Are both the strings equal? = \"+s2.Equals(s3));\n }\n}" }, { "code": null, "e": 1751, "s": 1650, "text": "String1 = Kevin\nString2 = Tom\nAre both the strings equal? = False\nAre both the strings equal? = True" }, { "code": null, "e": 1762, "s": 1751, "text": " Live Demo" }, { "code": null, "e": 2440, "s": 1762, "text": "using System;\npublic class Demo {\n public static void Main(string[] args) {\n string s1 = \"David\";\n string s2 = \"David\";\n string s3 = s2;\n string s4 = \"Tom\";\n string s5 = s4;\n Console.WriteLine(\"String1 = \"+s1);\n Console.WriteLine(\"String2 = \"+s2);\n Console.WriteLine(\"String3 = \"+s3);\n Console.WriteLine(\"String4 = \"+s4);\n Console.WriteLine(\"String5 = \"+s5);\n Console.WriteLine(\"Is s1 and s2 equal? = \"+s1.Equals(s2));\n Console.WriteLine(\"Is s2 and s3 equal? = \"+s2.Equals(s3));\n Console.WriteLine(\"Is s3 and s4 equal? = \"+s3.Equals(s4));\n Console.WriteLine(\"Is s4 and s5 equal? = \"+s4.Equals(s5));\n }\n}" }, { "code": null, "e": 2625, "s": 2440, "text": "String1 = David\nString2 = David\nString3 = David\nString4 = Tom\nString5 = Tom\nIs s1 and s2 equal? = True\nIs s2 and s3 equal? = True\nIs s3 and s4 equal? = False\nIs s4 and s5 equal? = True" } ]
UML - Overview
UML is a standard language for specifying, visualizing, constructing, and documenting the artifacts of software systems. UML was created by the Object Management Group (OMG) and UML 1.0 specification draft was proposed to the OMG in January 1997. OMG is continuously making efforts to create a truly industry standard. UML stands for Unified Modeling Language. UML stands for Unified Modeling Language. UML is different from the other common programming languages such as C++, Java, COBOL, etc. UML is different from the other common programming languages such as C++, Java, COBOL, etc. UML is a pictorial language used to make software blueprints. UML is a pictorial language used to make software blueprints. UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system. UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system. Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc. Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc. UML is not a programming language but tools can be used to generate code in various languages using UML diagrams. UML has a direct relation with object oriented analysis and design. After some standardization, UML has become an OMG standard. A picture is worth a thousand words, this idiom absolutely fits describing UML. Object-oriented concepts were introduced much earlier than UML. At that point of time, there were no standard methodologies to organize and consolidate the object-oriented development. It was then that UML came into picture. There are a number of goals for developing UML but the most important is to define some general purpose modeling language, which all modelers can use and it also needs to be made simple to understand and use. UML diagrams are not only made for developers but also for business users, common people, and anybody interested to understand the system. The system can be a software or non-software system. Thus it must be clear that UML is not a development method rather it accompanies with processes to make it a successful system. In conclusion, the goal of UML can be defined as a simple modeling mechanism to model all possible practical systems in today’s complex environment. To understand the conceptual model of UML, first we need to clarify what is a conceptual model? and why a conceptual model is required? A conceptual model can be defined as a model which is made of concepts and their relationships. A conceptual model can be defined as a model which is made of concepts and their relationships. A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other. A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other. As UML describes the real-time systems, it is very important to make a conceptual model and then proceed gradually. The conceptual model of UML can be mastered by learning the following three major elements − UML building blocks Rules to connect the building blocks Common mechanisms of UML UML can be described as the successor of object-oriented (OO) analysis and design. An object contains both data and methods that control the data. The data represents the state of the object. A class describes an object and they also form a hierarchy to model the real-world system. The hierarchy is represented as inheritance and the classes can also be associated in different ways as per the requirement. Objects are the real-world entities that exist around us and the basic concepts such as abstraction, encapsulation, inheritance, and polymorphism all can be represented using UML. UML is powerful enough to represent all the concepts that exist in object-oriented analysis and design. UML diagrams are representation of object-oriented concepts only. Thus, before learning UML, it becomes important to understand OO concept in detail. Following are some fundamental concepts of the object-oriented world − Objects − Objects represent an entity and the basic building block. Objects − Objects represent an entity and the basic building block. Class − Class is the blue print of an object. Class − Class is the blue print of an object. Abstraction − Abstraction represents the behavior of an real world entity. Abstraction − Abstraction represents the behavior of an real world entity. Encapsulation − Encapsulation is the mechanism of binding the data together and hiding them from the outside world. Encapsulation − Encapsulation is the mechanism of binding the data together and hiding them from the outside world. Inheritance − Inheritance is the mechanism of making new classes from existing ones. Inheritance − Inheritance is the mechanism of making new classes from existing ones. Polymorphism − It defines the mechanism to exists in different forms. Polymorphism − It defines the mechanism to exists in different forms. OO can be defined as an investigation and to be more specific, it is the investigation of objects. Design means collaboration of identified objects. Thus, it is important to understand the OO analysis and design concepts. The most important purpose of OO analysis is to identify objects of a system to be designed. This analysis is also done for an existing system. Now an efficient analysis is only possible when we are able to start thinking in a way where objects can be identified. After identifying the objects, their relationships are identified and finally the design is produced. The purpose of OO analysis and design can described as − Identifying the objects of a system. Identifying the objects of a system. Identifying their relationships. Identifying their relationships. Making a design, which can be converted to executables using OO languages. Making a design, which can be converted to executables using OO languages. There are three basic steps where the OO concepts are applied and implemented. The steps can be defined as OO Analysis → OO Design → OO implementation using OO languages The above three points can be described in detail as − During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are collaborated, the purpose of the system is fulfilled. During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are collaborated, the purpose of the system is fulfilled. The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the design is also complete. The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the design is also complete. The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc. The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc. UML is a modeling language used to model software and non-software systems. Although UML is used for non-software systems, the emphasis is on modeling OO software applications. Most of the UML diagrams discussed so far are used to model different aspects such as static, dynamic, etc. Now whatever be the aspect, the artifacts are nothing but objects. If we look into class diagram, object diagram, collaboration diagram, interaction diagrams all would basically be designed based on the objects. Hence, the relation between OO design and UML is very important to understand. The OO design is transformed into UML diagrams according to the requirement. Before understanding the UML in detail, the OO concept should be learned properly. Once the OO analysis and design is done, the next step is very easy. The input from OO analysis and design is the input to UML diagrams. 77 Lectures 6.5 hours Arnab Chakraborty 18 Lectures 1.5 hours Axel Mammitzsch 7 Lectures 59 mins Axel Mammitzsch 37 Lectures 2 hours Felix Tuna Print Add Notes Bookmark this page
[ { "code": null, "e": 2075, "s": 1954, "text": "UML is a standard language for specifying, visualizing, constructing, and documenting the\nartifacts of software systems." }, { "code": null, "e": 2201, "s": 2075, "text": "UML was created by the Object Management Group (OMG) and UML 1.0 specification draft was proposed to the OMG in January 1997." }, { "code": null, "e": 2273, "s": 2201, "text": "OMG is continuously making efforts to create a truly industry standard." }, { "code": null, "e": 2315, "s": 2273, "text": "UML stands for Unified Modeling Language." }, { "code": null, "e": 2357, "s": 2315, "text": "UML stands for Unified Modeling Language." }, { "code": null, "e": 2449, "s": 2357, "text": "UML is different from the other common programming languages such as C++, Java, COBOL, etc." }, { "code": null, "e": 2541, "s": 2449, "text": "UML is different from the other common programming languages such as C++, Java, COBOL, etc." }, { "code": null, "e": 2603, "s": 2541, "text": "UML is a pictorial language used to make software blueprints." }, { "code": null, "e": 2665, "s": 2603, "text": "UML is a pictorial language used to make software blueprints." }, { "code": null, "e": 2796, "s": 2665, "text": "UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system." }, { "code": null, "e": 2927, "s": 2796, "text": "UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system." }, { "code": null, "e": 3140, "s": 2927, "text": "Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc." }, { "code": null, "e": 3353, "s": 3140, "text": "Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc." }, { "code": null, "e": 3595, "s": 3353, "text": "UML is not a programming language but tools can be used to generate code in various languages using UML diagrams. UML has a direct relation with object oriented analysis and design. After some standardization, UML has become an OMG standard." }, { "code": null, "e": 3900, "s": 3595, "text": "A picture is worth a thousand words, this idiom absolutely fits describing UML. Object-oriented\nconcepts were introduced much earlier than UML. At that point of time, there were no standard methodologies to organize and consolidate the object-oriented development. It was then that UML came into picture." }, { "code": null, "e": 4109, "s": 3900, "text": "There are a number of goals for developing UML but the most important is to define some general purpose modeling language, which all modelers can use and it also needs to be made simple to understand and use." }, { "code": null, "e": 4429, "s": 4109, "text": "UML diagrams are not only made for developers but also for business users, common people, and anybody interested to understand the system. The system can be a software or non-software system. Thus it must be clear that UML is not a development method rather it accompanies with processes to make it a successful system." }, { "code": null, "e": 4578, "s": 4429, "text": "In conclusion, the goal of UML can be defined as a simple modeling mechanism to model all possible practical systems in today’s complex environment." }, { "code": null, "e": 4714, "s": 4578, "text": "To understand the conceptual model of UML, first we need to clarify what is a conceptual model? and why a conceptual model is required?" }, { "code": null, "e": 4810, "s": 4714, "text": "A conceptual model can be defined as a model which is made of concepts and their relationships." }, { "code": null, "e": 4906, "s": 4810, "text": "A conceptual model can be defined as a model which is made of concepts and their relationships." }, { "code": null, "e": 5066, "s": 4906, "text": "A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other." }, { "code": null, "e": 5226, "s": 5066, "text": "A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other." }, { "code": null, "e": 5435, "s": 5226, "text": "As UML describes the real-time systems, it is very important to make a conceptual model and then proceed gradually. The conceptual model of UML can be mastered by learning the following three major elements −" }, { "code": null, "e": 5455, "s": 5435, "text": "UML building blocks" }, { "code": null, "e": 5492, "s": 5455, "text": "Rules to connect the building blocks" }, { "code": null, "e": 5517, "s": 5492, "text": "Common mechanisms of UML" }, { "code": null, "e": 5600, "s": 5517, "text": "UML can be described as the successor of object-oriented (OO) analysis and design." }, { "code": null, "e": 5925, "s": 5600, "text": "An object contains both data and methods that control the data. The data represents the state of the object. A class describes an object and they also form a hierarchy to model the real-world system. The hierarchy is represented as inheritance and the classes can also be associated in different ways as per the requirement." }, { "code": null, "e": 6105, "s": 5925, "text": "Objects are the real-world entities that exist around us and the basic concepts such as abstraction, encapsulation, inheritance, and polymorphism all can be represented using UML." }, { "code": null, "e": 6359, "s": 6105, "text": "UML is powerful enough to represent all the concepts that exist in object-oriented analysis and design. UML diagrams are representation of object-oriented concepts only. Thus, before learning UML, it becomes important to understand OO concept in detail." }, { "code": null, "e": 6430, "s": 6359, "text": "Following are some fundamental concepts of the object-oriented world −" }, { "code": null, "e": 6498, "s": 6430, "text": "Objects − Objects represent an entity and the basic building block." }, { "code": null, "e": 6566, "s": 6498, "text": "Objects − Objects represent an entity and the basic building block." }, { "code": null, "e": 6612, "s": 6566, "text": "Class − Class is the blue print of an object." }, { "code": null, "e": 6658, "s": 6612, "text": "Class − Class is the blue print of an object." }, { "code": null, "e": 6733, "s": 6658, "text": "Abstraction − Abstraction represents the behavior of an real world entity." }, { "code": null, "e": 6808, "s": 6733, "text": "Abstraction − Abstraction represents the behavior of an real world entity." }, { "code": null, "e": 6924, "s": 6808, "text": "Encapsulation − Encapsulation is the mechanism of binding the data together and\nhiding them from the outside world." }, { "code": null, "e": 7040, "s": 6924, "text": "Encapsulation − Encapsulation is the mechanism of binding the data together and\nhiding them from the outside world." }, { "code": null, "e": 7125, "s": 7040, "text": "Inheritance − Inheritance is the mechanism of making new classes from existing ones." }, { "code": null, "e": 7210, "s": 7125, "text": "Inheritance − Inheritance is the mechanism of making new classes from existing ones." }, { "code": null, "e": 7280, "s": 7210, "text": "Polymorphism − It defines the mechanism to exists in different forms." }, { "code": null, "e": 7350, "s": 7280, "text": "Polymorphism − It defines the mechanism to exists in different forms." }, { "code": null, "e": 7499, "s": 7350, "text": "OO can be defined as an investigation and to be more specific, it is the investigation of objects. Design means collaboration of identified objects." }, { "code": null, "e": 7938, "s": 7499, "text": "Thus, it is important to understand the OO analysis and design concepts. The most important purpose of OO analysis is to identify objects of a system to be designed. This analysis is also done for an existing system. Now an efficient analysis is only possible when we are able to start thinking in a way where objects can be identified. After identifying the objects, their relationships are identified and finally the design is produced." }, { "code": null, "e": 7995, "s": 7938, "text": "The purpose of OO analysis and design can described as −" }, { "code": null, "e": 8032, "s": 7995, "text": "Identifying the objects of a system." }, { "code": null, "e": 8069, "s": 8032, "text": "Identifying the objects of a system." }, { "code": null, "e": 8102, "s": 8069, "text": "Identifying their relationships." }, { "code": null, "e": 8135, "s": 8102, "text": "Identifying their relationships." }, { "code": null, "e": 8210, "s": 8135, "text": "Making a design, which can be converted to executables using OO languages." }, { "code": null, "e": 8285, "s": 8210, "text": "Making a design, which can be converted to executables using OO languages." }, { "code": null, "e": 8392, "s": 8285, "text": "There are three basic steps where the OO concepts are applied and implemented. The steps can be defined as" }, { "code": null, "e": 8455, "s": 8392, "text": "OO Analysis → OO Design → OO implementation using OO languages" }, { "code": null, "e": 8510, "s": 8455, "text": "The above three points can be described in detail as −" }, { "code": null, "e": 8972, "s": 8510, "text": "During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are\ncollaborated, the purpose of the system is fulfilled." }, { "code": null, "e": 9434, "s": 8972, "text": "During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are\ncollaborated, the purpose of the system is fulfilled." }, { "code": null, "e": 9694, "s": 9434, "text": "The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the\ndesign is also complete." }, { "code": null, "e": 9954, "s": 9694, "text": "The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the\ndesign is also complete." }, { "code": null, "e": 10076, "s": 9954, "text": "The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc." }, { "code": null, "e": 10198, "s": 10076, "text": "The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc." }, { "code": null, "e": 10550, "s": 10198, "text": "UML is a modeling language used to model software and non-software systems. Although UML is used for non-software systems, the emphasis is on modeling OO software applications. Most of the UML diagrams discussed so far are used to model different\naspects such as static, dynamic, etc. Now whatever be the aspect, the artifacts are nothing but objects." }, { "code": null, "e": 10695, "s": 10550, "text": "If we look into class diagram, object diagram, collaboration diagram, interaction diagrams all would basically be designed based on the objects." }, { "code": null, "e": 11071, "s": 10695, "text": "Hence, the relation between OO design and UML is very important to understand. The OO design is transformed into UML diagrams according to the requirement. Before understanding the UML in detail, the OO concept should be learned properly. Once the OO analysis and design is done, the next step is very easy. The input from OO analysis and\ndesign is the input to UML diagrams." }, { "code": null, "e": 11106, "s": 11071, "text": "\n 77 Lectures \n 6.5 hours \n" }, { "code": null, "e": 11125, "s": 11106, "text": " Arnab Chakraborty" }, { "code": null, "e": 11160, "s": 11125, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11177, "s": 11160, "text": " Axel Mammitzsch" }, { "code": null, "e": 11208, "s": 11177, "text": "\n 7 Lectures \n 59 mins\n" }, { "code": null, "e": 11225, "s": 11208, "text": " Axel Mammitzsch" }, { "code": null, "e": 11258, "s": 11225, "text": "\n 37 Lectures \n 2 hours \n" }, { "code": null, "e": 11270, "s": 11258, "text": " Felix Tuna" }, { "code": null, "e": 11277, "s": 11270, "text": " Print" }, { "code": null, "e": 11288, "s": 11277, "text": " Add Notes" } ]
Binary Operators Overloading in C++
The binary operators take two arguments and following are the examples of Binary operators. You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator. Following example explains how addition (+) operator can be overloaded. Similar way, you can overload subtraction (-) and division (/) operators. #include <iostream> using namespace std; class Box { double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box public: double getVolume(void) { return length * breadth * height; } void setLength( double len ) { length = len; } void setBreadth( double bre ) { breadth = bre; } void setHeight( double hei ) { height = hei; } // Overload + operator to add two Box objects. Box operator+(const Box& b) { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } }; // Main function for the program int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2531, "s": 2318, "text": "The binary operators take two arguments and following are the examples of Binary operators. You use binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/) operator." }, { "code": null, "e": 2677, "s": 2531, "text": "Following example explains how addition (+) operator can be overloaded. Similar way, you can overload subtraction (-) and division (/) operators." }, { "code": null, "e": 4269, "s": 2677, "text": "#include <iostream>\nusing namespace std;\n \nclass Box {\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n \n public:\n \n double getVolume(void) {\n return length * breadth * height;\n }\n \n void setLength( double len ) {\n length = len;\n }\n \n void setBreadth( double bre ) {\n breadth = bre;\n }\n \n void setHeight( double hei ) {\n height = hei;\n }\n \n // Overload + operator to add two Box objects.\n Box operator+(const Box& b) {\n Box box;\n box.length = this->length + b.length;\n box.breadth = this->breadth + b.breadth;\n box.height = this->height + b.height;\n return box;\n }\n};\n\n// Main function for the program\nint main() {\n Box Box1; // Declare Box1 of type Box\n Box Box2; // Declare Box2 of type Box\n Box Box3; // Declare Box3 of type Box\n double volume = 0.0; // Store the volume of a box here\n \n // box 1 specification\n Box1.setLength(6.0); \n Box1.setBreadth(7.0); \n Box1.setHeight(5.0);\n \n // box 2 specification\n Box2.setLength(12.0); \n Box2.setBreadth(13.0); \n Box2.setHeight(10.0);\n \n // volume of box 1\n volume = Box1.getVolume();\n cout << \"Volume of Box1 : \" << volume <<endl;\n \n // volume of box 2\n volume = Box2.getVolume();\n cout << \"Volume of Box2 : \" << volume <<endl;\n \n // Add two object as follows:\n Box3 = Box1 + Box2;\n \n // volume of box 3\n volume = Box3.getVolume();\n cout << \"Volume of Box3 : \" << volume <<endl;\n \n return 0;\n}" }, { "code": null, "e": 4350, "s": 4269, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4416, "s": 4350, "text": "Volume of Box1 : 210\nVolume of Box2 : 1560\nVolume of Box3 : 5400\n" }, { "code": null, "e": 4453, "s": 4416, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4472, "s": 4453, "text": " Arnab Chakraborty" }, { "code": null, "e": 4504, "s": 4472, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4527, "s": 4504, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4563, "s": 4527, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4580, "s": 4563, "text": " Frahaan Hussain" }, { "code": null, "e": 4615, "s": 4580, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4632, "s": 4615, "text": " Frahaan Hussain" }, { "code": null, "e": 4667, "s": 4632, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4684, "s": 4667, "text": " Frahaan Hussain" }, { "code": null, "e": 4719, "s": 4684, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4736, "s": 4719, "text": " Frahaan Hussain" }, { "code": null, "e": 4743, "s": 4736, "text": " Print" }, { "code": null, "e": 4754, "s": 4743, "text": " Add Notes" } ]
Different types of MySQL Triggers (with examples) - GeeksforGeeks
04 Jul, 2019 A MySQL trigger is a stored program (with queries) which is executed automatically to respond to a specific event such as insertion, updation or deletion occurring in a table. There are 6 different types of triggers in MySQL: 1. Before Update Trigger:As the name implies, it is a trigger which enacts before an update is invoked. If we write an update statement, then the actions of the trigger will be performed before the update is implemented. Example:Considering tables: create table customer (acc_no integer primary key, cust_name varchar(20), avail_balance decimal); create table mini_statement (acc_no integer, avail_balance decimal, foreign key(acc_no) references customer(acc_no) on delete cascade); Inserting values in them: insert into customer values (1000, "Fanny", 7000); insert into customer values (1001, "Peter", 12000); Trigger to insert (old) values into a mini_statement record (including account number and available balance as parameters) before updating any record in customer record/table: delimiter // create trigger update_cus -> before update on customer -> for each row -> begin -> insert into mini_statement values (old.acc_no, old.avail_balance); -> end; // Making updates to invoke trigger: delimiter; update customer set avail_balance = avail_balance + 3000 where acc_no = 1001; update customer set avail_balance = avail_balance + 3000 where acc_no = 1000; Output: select *from mini_statement; +--------+---------------+ | acc_no | avail_balance | +--------+---------------+ | 1001 | 12000 | | 1000 | 7000 | +--------+---------------+ 2 rows in set (0.0007 sec) 2. After Update Trigger:As the name implies, this trigger is invoked after an updation occurs. (i.e., it gets implemented after an update statement is executed.). Example:We create another table: create table micro_statement (acc_no integer, avail_balance decimal, foreign key(acc_no) references customer(acc_no) on delete cascade); Insert another value into customer: insert into customer values (1002, "Janitor", 4500); Query OK, 1 row affected (0.0786 sec) Trigger to insert (new) values of account number and available balance into micro_statement record after an update has occurred: delimiter // create trigger update_after -> after update on customer -> for each row -> begin -> insert into micro_statement values(new.acc_no, new.avail_balance); -> end; // Making an update to invoke trigger: delimiter ; update customer set avail_balance = avail_balance + 1500 where acc_no = 1002; Output: select *from micro_statement; +--------+---------------+ | acc_no | avail_balance | +--------+---------------+ | 1002 | 6000 | +--------+---------------+ 1 row in set (0.0007 sec) 3. Before Insert Trigger:As the name implies, this trigger is invoked before an insert, or before an insert statement is executed. Example:Considering tables: create table contacts (contact_id INT (11) NOT NULL AUTO_INCREMENT, last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25), ->birthday DATE, created_date DATE, created_by VARCHAR(30), CONSTRAINT contacts_pk PRIMARY KEY (contact_id)); Trigger to insert contact information such as name, birthday and creation-date/user into a table contact before an insert occurs: delimiter // create trigger contacts_before_insert -> before insert -> on contacts for each row -> begin -> DECLARE vUser varchar(50); -> -> -- Find username of person performing INSERT into table -> select USER() into vUser; -> -> -- Update create_date field to current system date -> SET NEW.created_date = SYSDATE(); -> -> -- Update created_by field to the username of the person performing the INSERT -> SET NEW.created_by = vUser; -> end; // Making an insert to invoke the trigger: delimiter; insert into contacts values (1, "Newton", "Enigma", str_to_date ("19-08-1999", "%d-%m-%Y"), str_to_date ("17-03-2018", "%d-%m-%Y"), "xyz"); Output: select *from contacts; +------------+-----------+------------+------------+--------------+----------------+ | contact_id | last_name | first_name | birthday | created_date | created_by | +------------+-----------+------------+------------+--------------+----------------+ | 1 | Newton | Enigma | 1999-08-19 | 2019-05-11 | root@localhost | +------------+-----------+------------+------------+--------------+----------------+ 4. After Insert Trigger:As the name implies, this trigger gets invoked after an insert is implemented. Example:Consider tables: create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, last_name VARCHAR(30) NOT NULL, first_name VARCHAR(25), birthday DATE, ->CONSTRAINT contacts_pk PRIMARY KEY (contact_id)); create table contacts_audit (contact_id integer, created_date date, created_by varchar (30)); Trigger to insert contact_id and contact creation-date/user information into contacts_audit record after an insert occurs: delimiter // create trigger contacts_after_insert -> after insert -> on contacts for each row -> begin -> DECLARE vUser varchar(50); -> -> -- Find username of person performing the INSERT into table -> SELECT USER() into vUser; -> -> -- Insert record into audit table -> INSERT into contacts_audit -> ( contact_id, -> created_date, -> created_by) -> VALUES -> ( NEW.contact_id, -> SYSDATE(), -> vUser ); -> END; // Making an insert to invoke the trigger: insert into contacts values (1, "Kumar", "Rupesh", str_to_date("20-06-1999", "%d-%m-%Y")); Output: select *from contacts_audit; +------------+--------------+----------------+ | contact_id | created_date | created_by | +------------+--------------+----------------+ | 1 | 2019-05-11 | root@localhost | +------------+--------------+----------------+ 1 row in set (0.0006 sec) 5. Before Delete Trigger:As the name implies, this trigger is invoked before a delete occurs, or before deletion statement is implemented. Example:Consider tables: create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25), birthday DATE, created_date DATE, created_by VARCHAR(30), CONSTRAINT contacts_pk PRIMARY KEY (contact_id)); create table contacts_audit (contact_id integer, deleted_date date, deleted_by varchar(20)); Trigger to insert contact_id and contact deletion-date/user information into contacts_audit record before a delete occurs: delimiter // create trigger contacts_before_delete -> before delete -> on contacts for each row -> begin -> -> DECLARE vUser varchar(50); -> -> -- Find username of person performing the DELETE into table -> SELECT USER() into vUser; -> -> -- Insert record into audit table -> INSERT into contacts_audit -> ( contact_id, -> deleted_date, -> deleted_by) -> VALUES -> ( OLD.contact_id, -> SYSDATE(), -> vUser ); -> end; // Making an insert and then deleting the same to invoke the trigger: delimiter; insert into contacts values (1, "Bond", "Ruskin", str_to_date ("19-08-1995", "%d-%m-%Y"), str_to_date ("27-04-2018", "%d-%m-%Y"), "xyz"); delete from contacts where last_name="Bond"; Output: select *from contacts_audit; +------------+--------------+----------------+ | contact_id | deleted_date | deleted_by | +------------+--------------+----------------+ | 1 | 2019-05-11 | root@localhost | +------------+--------------+----------------+ 1 row in set (0.0007 sec) 6. After Delete Trigger:As the name implies, this trigger is invoked after a delete occurs, or after a delete operation is implemented. Example:Consider the tables: create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25), birthday DATE, created_date DATE, created_by VARCHAR (30), CONSTRAINT contacts_pk PRIMARY KEY (contact_id)); create table contacts_audit (contact_id integer, deleted_date date, deleted_by varchar(20)); Trigger to insert contact_id and contact deletion-date/user information into contacts_audit record after a delete occurs: create trigger contacts_after_delete -> after delete -> on contacts for each row -> begin -> -> DECLARE vUser varchar(50); -> -> -- Find username of person performing the DELETE into table -> SELECT USER() into vUser; -> -> -- Insert record into audit table -> INSERT into contacts_audit -> ( contact_id, -> deleted_date, -> deleted_by) -> VALUES -> ( OLD.contact_id, -> SYSDATE(), -> vUser ); -> end; // Making an insert and deleting the same to invoke the trigger: delimiter; insert into contacts values (1, "Newton", "Isaac", str_to_date ("19-08-1985", "%d-%m-%Y"), str_to_date ("23-07-2018", "%d-%m-%Y"), "xyz"); delete from contacts where first_name="Isaac"; Output: select *from contacts_audit; +------------+--------------+----------------+ | contact_id | deleted_date | deleted_by | +------------+--------------+----------------+ | 1 | 2019-05-11 | root@localhost | +------------+--------------+----------------+ 1 row in set (0.0009 sec) DBMS-SQL mysql DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS KDD Process in Data Mining Structure of Database Management System Difference between File System and DBMS What is Temporary Table in SQL? Difference between Star Schema and Snowflake Schema Insert Operation in B-Tree Relational Model in DBMS Nested Queries in SQL
[ { "code": null, "e": 24330, "s": 24302, "text": "\n04 Jul, 2019" }, { "code": null, "e": 24506, "s": 24330, "text": "A MySQL trigger is a stored program (with queries) which is executed automatically to respond to a specific event such as insertion, updation or deletion occurring in a table." }, { "code": null, "e": 24556, "s": 24506, "text": "There are 6 different types of triggers in MySQL:" }, { "code": null, "e": 24777, "s": 24556, "text": "1. Before Update Trigger:As the name implies, it is a trigger which enacts before an update is invoked. If we write an update statement, then the actions of the trigger will be performed before the update is implemented." }, { "code": null, "e": 24805, "s": 24777, "text": "Example:Considering tables:" }, { "code": null, "e": 25162, "s": 24805, "text": "create table customer (acc_no integer primary key, \n cust_name varchar(20), \n avail_balance decimal);\ncreate table mini_statement (acc_no integer, \n avail_balance decimal, \n foreign key(acc_no) references customer(acc_no) on delete cascade); " }, { "code": null, "e": 25188, "s": 25162, "text": "Inserting values in them:" }, { "code": null, "e": 25292, "s": 25188, "text": "insert into customer values (1000, \"Fanny\", 7000);\ninsert into customer values (1001, \"Peter\", 12000); " }, { "code": null, "e": 25468, "s": 25292, "text": "Trigger to insert (old) values into a mini_statement record (including account number and available balance as parameters) before updating any record in customer record/table:" }, { "code": null, "e": 25673, "s": 25468, "text": "delimiter //\ncreate trigger update_cus\n -> before update on customer\n -> for each row\n -> begin\n -> insert into mini_statement values (old.acc_no, old.avail_balance);\n -> end; // " }, { "code": null, "e": 25707, "s": 25673, "text": "Making updates to invoke trigger:" }, { "code": null, "e": 25875, "s": 25707, "text": "delimiter;\nupdate customer set avail_balance = avail_balance + 3000 where acc_no = 1001;\nupdate customer set avail_balance = avail_balance + 3000 where acc_no = 1000; " }, { "code": null, "e": 25883, "s": 25875, "text": "Output:" }, { "code": null, "e": 26102, "s": 25883, "text": "select *from mini_statement;\n+--------+---------------+\n| acc_no | avail_balance |\n+--------+---------------+\n| 1001 | 12000 |\n| 1000 | 7000 |\n+--------+---------------+\n2 rows in set (0.0007 sec) " }, { "code": null, "e": 26265, "s": 26102, "text": "2. After Update Trigger:As the name implies, this trigger is invoked after an updation occurs. (i.e., it gets implemented after an update statement is executed.)." }, { "code": null, "e": 26298, "s": 26265, "text": "Example:We create another table:" }, { "code": null, "e": 26484, "s": 26298, "text": "create table micro_statement (acc_no integer, \n avail_balance decimal, \n foreign key(acc_no) references customer(acc_no) on delete cascade); " }, { "code": null, "e": 26520, "s": 26484, "text": "Insert another value into customer:" }, { "code": null, "e": 26612, "s": 26520, "text": "insert into customer values (1002, \"Janitor\", 4500);\nQuery OK, 1 row affected (0.0786 sec) " }, { "code": null, "e": 26741, "s": 26612, "text": "Trigger to insert (new) values of account number and available balance into micro_statement record after an update has occurred:" }, { "code": null, "e": 26952, "s": 26741, "text": "delimiter //\ncreate trigger update_after\n -> after update on customer\n -> for each row\n -> begin\n -> insert into micro_statement values(new.acc_no, new.avail_balance);\n -> end; // " }, { "code": null, "e": 26988, "s": 26952, "text": "Making an update to invoke trigger:" }, { "code": null, "e": 27079, "s": 26988, "text": "delimiter ;\nupdate customer set avail_balance = avail_balance + 1500 where acc_no = 1002; " }, { "code": null, "e": 27087, "s": 27079, "text": "Output:" }, { "code": null, "e": 27279, "s": 27087, "text": "select *from micro_statement;\n+--------+---------------+\n| acc_no | avail_balance |\n+--------+---------------+\n| 1002 | 6000 |\n+--------+---------------+\n1 row in set (0.0007 sec) " }, { "code": null, "e": 27410, "s": 27279, "text": "3. Before Insert Trigger:As the name implies, this trigger is invoked before an insert, or before an insert statement is executed." }, { "code": null, "e": 27438, "s": 27410, "text": "Example:Considering tables:" }, { "code": null, "e": 27777, "s": 27438, "text": "create table contacts (contact_id INT (11) NOT NULL AUTO_INCREMENT, \n last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25),\n ->birthday DATE, created_date DATE, \n created_by VARCHAR(30), \n CONSTRAINT contacts_pk PRIMARY KEY (contact_id)); " }, { "code": null, "e": 27907, "s": 27777, "text": "Trigger to insert contact information such as name, birthday and creation-date/user into a table contact before an insert occurs:" }, { "code": null, "e": 28544, "s": 27907, "text": "delimiter //\ncreate trigger contacts_before_insert\n -> before insert\n -> on contacts for each row\n -> begin\n -> DECLARE vUser varchar(50);\n ->\n -> -- Find username of person performing INSERT into table\n -> select USER() into vUser;\n ->\n -> -- Update create_date field to current system date\n -> SET NEW.created_date = SYSDATE();\n ->\n -> -- Update created_by field to the username of the person performing the INSERT\n -> SET NEW.created_by = vUser;\n -> end; // " }, { "code": null, "e": 28584, "s": 28544, "text": "Making an insert to invoke the trigger:" }, { "code": null, "e": 28796, "s": 28584, "text": "delimiter;\ninsert into contacts values (1, \"Newton\", \"Enigma\", \n str_to_date (\"19-08-1999\", \"%d-%m-%Y\"), \n str_to_date (\"17-03-2018\", \"%d-%m-%Y\"), \"xyz\"); " }, { "code": null, "e": 28804, "s": 28796, "text": "Output:" }, { "code": null, "e": 29253, "s": 28804, "text": "select *from contacts;\n+------------+-----------+------------+------------+--------------+----------------+\n| contact_id | last_name | first_name | birthday | created_date | created_by |\n+------------+-----------+------------+------------+--------------+----------------+\n| 1 | Newton | Enigma | 1999-08-19 | 2019-05-11 | root@localhost |\n+------------+-----------+------------+------------+--------------+----------------+ " }, { "code": null, "e": 29356, "s": 29253, "text": "4. After Insert Trigger:As the name implies, this trigger gets invoked after an insert is implemented." }, { "code": null, "e": 29381, "s": 29356, "text": "Example:Consider tables:" }, { "code": null, "e": 29819, "s": 29381, "text": "create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, \n last_name VARCHAR(30) NOT NULL, \n first_name VARCHAR(25), birthday DATE,\n ->CONSTRAINT contacts_pk PRIMARY KEY (contact_id));\ncreate table contacts_audit (contact_id integer, \n created_date date, \n created_by varchar (30)); " }, { "code": null, "e": 29942, "s": 29819, "text": "Trigger to insert contact_id and contact creation-date/user information into contacts_audit record after an insert occurs:" }, { "code": null, "e": 30618, "s": 29942, "text": "delimiter //\ncreate trigger contacts_after_insert\n -> after insert\n -> on contacts for each row\n -> begin\n -> DECLARE vUser varchar(50);\n ->\n -> -- Find username of person performing the INSERT into table\n -> SELECT USER() into vUser;\n ->\n -> -- Insert record into audit table\n -> INSERT into contacts_audit\n -> ( contact_id,\n -> created_date,\n -> created_by)\n -> VALUES\n -> ( NEW.contact_id,\n -> SYSDATE(),\n -> vUser );\n -> END; // " }, { "code": null, "e": 30658, "s": 30618, "text": "Making an insert to invoke the trigger:" }, { "code": null, "e": 30776, "s": 30658, "text": "insert into contacts values (1, \"Kumar\", \"Rupesh\", \n str_to_date(\"20-06-1999\", \"%d-%m-%Y\")); " }, { "code": null, "e": 30784, "s": 30776, "text": "Output:" }, { "code": null, "e": 31075, "s": 30784, "text": "select *from contacts_audit;\n+------------+--------------+----------------+\n| contact_id | created_date | created_by |\n+------------+--------------+----------------+\n| 1 | 2019-05-11 | root@localhost |\n+------------+--------------+----------------+\n1 row in set (0.0006 sec) " }, { "code": null, "e": 31214, "s": 31075, "text": "5. Before Delete Trigger:As the name implies, this trigger is invoked before a delete occurs, or before deletion statement is implemented." }, { "code": null, "e": 31239, "s": 31214, "text": "Example:Consider tables:" }, { "code": null, "e": 31657, "s": 31239, "text": "create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, \n last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25), \n birthday DATE, created_date DATE, created_by VARCHAR(30), \n CONSTRAINT contacts_pk PRIMARY KEY (contact_id));\ncreate table contacts_audit (contact_id integer, deleted_date date, deleted_by varchar(20)); " }, { "code": null, "e": 31780, "s": 31657, "text": "Trigger to insert contact_id and contact deletion-date/user information into contacts_audit record before a delete occurs:" }, { "code": null, "e": 32473, "s": 31780, "text": "delimiter //\ncreate trigger contacts_before_delete\n -> before delete\n -> on contacts for each row\n -> begin\n ->\n -> DECLARE vUser varchar(50);\n ->\n -> -- Find username of person performing the DELETE into table\n -> SELECT USER() into vUser;\n ->\n -> -- Insert record into audit table\n -> INSERT into contacts_audit\n -> ( contact_id,\n -> deleted_date,\n -> deleted_by)\n -> VALUES\n -> ( OLD.contact_id,\n -> SYSDATE(),\n -> vUser );\n -> end; // " }, { "code": null, "e": 32540, "s": 32473, "text": "Making an insert and then deleting the same to invoke the trigger:" }, { "code": null, "e": 32795, "s": 32540, "text": "delimiter;\ninsert into contacts values (1, \"Bond\", \"Ruskin\", \n str_to_date (\"19-08-1995\", \"%d-%m-%Y\"), \n str_to_date (\"27-04-2018\", \"%d-%m-%Y\"), \"xyz\");\ndelete from contacts where last_name=\"Bond\"; " }, { "code": null, "e": 32803, "s": 32795, "text": "Output:" }, { "code": null, "e": 33094, "s": 32803, "text": "select *from contacts_audit;\n+------------+--------------+----------------+\n| contact_id | deleted_date | deleted_by |\n+------------+--------------+----------------+\n| 1 | 2019-05-11 | root@localhost |\n+------------+--------------+----------------+\n1 row in set (0.0007 sec) " }, { "code": null, "e": 33230, "s": 33094, "text": "6. After Delete Trigger:As the name implies, this trigger is invoked after a delete occurs, or after a delete operation is implemented." }, { "code": null, "e": 33259, "s": 33230, "text": "Example:Consider the tables:" }, { "code": null, "e": 33674, "s": 33259, "text": "create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, \n last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25), \n birthday DATE, created_date DATE, created_by VARCHAR (30), \n CONSTRAINT contacts_pk PRIMARY KEY (contact_id));\ncreate table contacts_audit (contact_id integer, deleted_date date, deleted_by varchar(20));" }, { "code": null, "e": 33796, "s": 33674, "text": "Trigger to insert contact_id and contact deletion-date/user information into contacts_audit record after a delete occurs:" }, { "code": null, "e": 34455, "s": 33796, "text": "create trigger contacts_after_delete\n -> after delete\n -> on contacts for each row\n -> begin\n ->\n -> DECLARE vUser varchar(50);\n ->\n -> -- Find username of person performing the DELETE into table\n -> SELECT USER() into vUser;\n ->\n -> -- Insert record into audit table\n -> INSERT into contacts_audit\n -> ( contact_id,\n -> deleted_date,\n -> deleted_by)\n -> VALUES\n -> ( OLD.contact_id,\n -> SYSDATE(),\n -> vUser );\n -> end; // " }, { "code": null, "e": 34517, "s": 34455, "text": "Making an insert and deleting the same to invoke the trigger:" }, { "code": null, "e": 34775, "s": 34517, "text": "delimiter;\ninsert into contacts values (1, \"Newton\", \"Isaac\", \n str_to_date (\"19-08-1985\", \"%d-%m-%Y\"), \n str_to_date (\"23-07-2018\", \"%d-%m-%Y\"), \"xyz\");\ndelete from contacts where first_name=\"Isaac\"; " }, { "code": null, "e": 34783, "s": 34775, "text": "Output:" }, { "code": null, "e": 35074, "s": 34783, "text": "select *from contacts_audit;\n+------------+--------------+----------------+\n| contact_id | deleted_date | deleted_by |\n+------------+--------------+----------------+\n| 1 | 2019-05-11 | root@localhost |\n+------------+--------------+----------------+\n1 row in set (0.0009 sec) " }, { "code": null, "e": 35083, "s": 35074, "text": "DBMS-SQL" }, { "code": null, "e": 35089, "s": 35083, "text": "mysql" }, { "code": null, "e": 35094, "s": 35089, "text": "DBMS" }, { "code": null, "e": 35099, "s": 35094, "text": "DBMS" }, { "code": null, "e": 35197, "s": 35099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35206, "s": 35197, "text": "Comments" }, { "code": null, "e": 35219, "s": 35206, "text": "Old Comments" }, { "code": null, "e": 35260, "s": 35219, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 35303, "s": 35260, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 35330, "s": 35303, "text": "KDD Process in Data Mining" }, { "code": null, "e": 35370, "s": 35330, "text": "Structure of Database Management System" }, { "code": null, "e": 35410, "s": 35370, "text": "Difference between File System and DBMS" }, { "code": null, "e": 35442, "s": 35410, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 35494, "s": 35442, "text": "Difference between Star Schema and Snowflake Schema" }, { "code": null, "e": 35521, "s": 35494, "text": "Insert Operation in B-Tree" }, { "code": null, "e": 35546, "s": 35521, "text": "Relational Model in DBMS" } ]
k nearest neighbors computational complexity | by Jakub Adamczyk | Towards Data Science
kNN (k nearest neighbors) is one of the simplest ML algorithms, often taught as one of the first algorithms during introductory courses. It’s relatively simple but quite powerful, although rarely time is spent on understanding its computational complexity and practical issues. It can be used both for classification and regression with the same complexity, so for simplicity, we’ll consider the kNN classifier. kNN is an associative algorithm — during prediction it searches for the nearest neighbors and takes their majority vote as the class predicted for the sample. Training phase may or may not exist at all, as in general, we have 2 possibilities: Brute force method — calculate distance from new point to every point in training data matrix X, sort distances and take k nearest, then do a majority vote. There is no need for separate training, so we only consider prediction complexity.Using data structure — organize the training points from X into the auxiliary data structure for faster nearest neighbors lookup. This approach uses additional space and time (for creating data structure during training phase) for faster predictions. Brute force method — calculate distance from new point to every point in training data matrix X, sort distances and take k nearest, then do a majority vote. There is no need for separate training, so we only consider prediction complexity. Using data structure — organize the training points from X into the auxiliary data structure for faster nearest neighbors lookup. This approach uses additional space and time (for creating data structure during training phase) for faster predictions. We focus on the methods implemented in Scikit-learn, the most popular ML library for Python. It supports brute force, k-d tree and ball tree data structures. These are relatively simple, efficient and perfectly suited for the kNN algorithm. Construction of these trees stems from computational geometry, not from machine learning, and does not concern us that much, so I’ll cover it in less detail, more on the conceptual level. For more details on that, see links at the end of the article. In all complexities below, times of calculating the distance were omitted, since they are in most cases negligible compared to the rest of the algorithm. Additionally, we mark: n: number of points in the training dataset d: data dimensionality k: number of neighbors that we consider for voting Training time complexity: O(1) Training space complexity: O(1) Prediction time complexity: O(k * n * d) Prediction space complexity: O(1) Training phase technically does not exist, since all computation is done during prediction, so we have O(1) for both time and space. Prediction phase is, as method name suggest, a simple exhaustive search, which in pseudocode is: Loop through all points k times: 1. Compute the distance between currently classifier sample and training points, remember the index of the element with the smallest distance (ignore previously selected points) 2. Add the class at found index to the counterReturn the class with the most votes as a prediction This is a nested loop structure, where the outer loop takes k steps and the inner loop takes n steps. 3rd point is O(1) and 4th is O(# of classes), so they are smaller. Additionally, we have to take into consideration the numer of dimensions d, more directions mean longer vectors to compute distances. Therefore, we have O(n * k * d) time complexity. As for space complexity, we need a small vector to count the votes for each class. It’s almost always very small and is fixed, so we can treat it as a O(1) space complexity. Training time complexity: O(d * n * log(n)) Training space complexity: O(d * n) Prediction time complexity: O(k * log(n)) Prediction space complexity: O(1) During the training phase, we have to construct the k-d tree. This data structure splits the k-dimensional space (here k means k dimensions of space, don’t confuse this with k as a number of nearest neighbors!) and allows faster search for nearest points, since we “know where to look” in that space. You may think of it like a generalization of BST for many dimensions. It “cuts” space with axis-aligned cuts, dividing points into groups in children nodes. Constructing the k-d tree is not a machine learning task itself, since it stems from computational geometry domain, so we won’t cover this in detail, only on conceptual level. The time complexity is usually O(d * n * log(n)), because insertion is O(log(n)) (similar to regular BST) and we have n points from the training dataset, each with d dimensions. I assume the efficient implementation of the data structure, i. e. it finds the optimal split point (median in the dimension) in O(n), which is possible with the median of medians algorithm. Space complexity is O(d * n) — note that it depends on dimensionality d, which makes sense, since more dimensions correspond to more space divisions and larger trees (in addition to larger time complexity for the same reason). As for the prediction phase, the k-d tree structure naturally supports “k nearest point neighbors query” operation, which is exactly what we need for kNN. The simple approach is to just query k times, removing the point found each time — since query takes O(log(n)), it is O(k * log(n)) in total. But since the k-d tree already cuts space during construction, after a single query we approximately know where to look — we can just search the “surroundings” around that point. Therefore, practical implementations of k-d tree support querying for whole k neighbors at one time and with complexity O(sqrt(n) + k), which is much better for larger dimensionalities, which are very common in machine learning. The above complexities are the average ones, assuming the balanced k-d tree. The O(log(n)) times assumed above may degrade up to O(n) for unbalanced trees, but if the median is used during the tree construction, we should always get a tree with approximately O(log(n)) insertion/deletion/search complexity. Training time complexity: O(d * n * log(n)) Training space complexity: O(d * n) Prediction time complexity: O(k * log(n)) Prediction space complexity: O(1) Ball tree algorithm takes another approach to dividing space where training points lie. In contrast to k-d trees, which divides space with median value “cuts”, ball tree groups points into “balls” organized into a tree structure. They go from the largest (root, with all points) to the smallest (leaves, with only a few or even 1 point). It allows fast nearest neighbor lookup because nearby neighbors are in the same or at least close “balls”. During the training phase, we only need to construct the ball tree. There are a few algorithms for constructing the ball tree, but the one most similar to k-d tree (called “k-d construction algorithm” for that reason) is O(d * n * log(n)), the same as k-d tree. Because of the tree building similarity, the complexities of the prediction phase are also the same as for k-d tree. To summarize the complexities: brute force is the slowest in the big O notation, while both k-d tree and ball tree have the same lower complexity. How do we know which one to use then? To get the answer, we have to look at both training and prediction times, that’s why I have provided both. The brute force algorithm has only one complexity, for prediction, O(k * n). Other algorithms need to create the data structure first, so for training and prediction they get O(d * n * log(n) + k * log(n)), not taking into account the space complexity, which may also be important. Therefore, where the construction of the trees is frequent, the training phase may outweigh their advantage of faster nearest neighbor lookup. Should we use k-d tree or ball tree? It depends on the data structure — relatively uniform or “well behaved” data will make better use of k-d tree, since the cuts of space will work well (near points will be close in the leaves after all cuts). For more clustered data the “balls” from the ball tree will reflect the structure better and therefore allow for faster nearest neighbor search. Fortunately, Scikit-learn supports “auto” option, which will automatically infer the best data structure from the data. Let’s see this in practice on two case studies, which I’ve encountered in practice during my studies and job. The more “traditional” application of the kNN is the classification of data. It often has quite a lot of points, e. g. MNIST has 60k training images and 10k test images. Classification is done offline, which means we first do the training phase, then just use the results during prediction. Therefore, if we want to construct the data structure, we only need to do so once. For 10k test images, let’s compare the brute force (which calculates all distances every time) and k-d tree for 3 neighbors: Brute force (O(k * n)): 3 * 10,000 = 30,000 k-d tree (O(k * log(n))): 3 * log(10,000) ~ 3 * 13 = 39 Comparison: 39 / 30,000 = 0.0013 As you can see, the performance gain is huge! The data structure method uses only a tiny fraction of the brute force time. For most datasets this method is a clear winner. Machine Learning is commonly used for image recognition, often using neural networks. It’s very useful for real-time applications, where it’s often integrated with cameras, alarms etc. The problem with neural networks is that they often detect the same object 2 or more times — even the best architectures like YOLO have this problem. We can actually solve it with nearest neighbor search with a simple approach: Calculate the center of each bounding box (rectangle)For each rectangle, search for its nearest neighbor (1NN)If points are closer than the selected threshold, merge them (they detect the same object) Calculate the center of each bounding box (rectangle) For each rectangle, search for its nearest neighbor (1NN) If points are closer than the selected threshold, merge them (they detect the same object) The crucial part is searching for the closest center of another bounding box (point 2). Which algorithm should be used here? Typically we have only a few moving objects on camera, maybe up to 30–40. For such a small number, speedup from using data structures for faster lookup is negligible. Each frame is a separate image, so if we wanted to construct a k-d tree for example, we would have to do so for every frame, which may mean 30 times per second — a huge cost overall. Therefore, for such situations a simple brute force method works fastest and also has the smallest space requirement (which, with heavy neural networks or for embedded CPUs in cameras, may be important). kNN algorithm is a popular, easy and useful technique in Machine Learning, and I hope after reading this article you understand it’s complexities and real world scenarios where and how you can use this method.
[ { "code": null, "e": 583, "s": 171, "text": "kNN (k nearest neighbors) is one of the simplest ML algorithms, often taught as one of the first algorithms during introductory courses. It’s relatively simple but quite powerful, although rarely time is spent on understanding its computational complexity and practical issues. It can be used both for classification and regression with the same complexity, so for simplicity, we’ll consider the kNN classifier." }, { "code": null, "e": 826, "s": 583, "text": "kNN is an associative algorithm — during prediction it searches for the nearest neighbors and takes their majority vote as the class predicted for the sample. Training phase may or may not exist at all, as in general, we have 2 possibilities:" }, { "code": null, "e": 1316, "s": 826, "text": "Brute force method — calculate distance from new point to every point in training data matrix X, sort distances and take k nearest, then do a majority vote. There is no need for separate training, so we only consider prediction complexity.Using data structure — organize the training points from X into the auxiliary data structure for faster nearest neighbors lookup. This approach uses additional space and time (for creating data structure during training phase) for faster predictions." }, { "code": null, "e": 1556, "s": 1316, "text": "Brute force method — calculate distance from new point to every point in training data matrix X, sort distances and take k nearest, then do a majority vote. There is no need for separate training, so we only consider prediction complexity." }, { "code": null, "e": 1807, "s": 1556, "text": "Using data structure — organize the training points from X into the auxiliary data structure for faster nearest neighbors lookup. This approach uses additional space and time (for creating data structure during training phase) for faster predictions." }, { "code": null, "e": 2299, "s": 1807, "text": "We focus on the methods implemented in Scikit-learn, the most popular ML library for Python. It supports brute force, k-d tree and ball tree data structures. These are relatively simple, efficient and perfectly suited for the kNN algorithm. Construction of these trees stems from computational geometry, not from machine learning, and does not concern us that much, so I’ll cover it in less detail, more on the conceptual level. For more details on that, see links at the end of the article." }, { "code": null, "e": 2476, "s": 2299, "text": "In all complexities below, times of calculating the distance were omitted, since they are in most cases negligible compared to the rest of the algorithm. Additionally, we mark:" }, { "code": null, "e": 2520, "s": 2476, "text": "n: number of points in the training dataset" }, { "code": null, "e": 2543, "s": 2520, "text": "d: data dimensionality" }, { "code": null, "e": 2594, "s": 2543, "text": "k: number of neighbors that we consider for voting" }, { "code": null, "e": 2625, "s": 2594, "text": "Training time complexity: O(1)" }, { "code": null, "e": 2657, "s": 2625, "text": "Training space complexity: O(1)" }, { "code": null, "e": 2698, "s": 2657, "text": "Prediction time complexity: O(k * n * d)" }, { "code": null, "e": 2732, "s": 2698, "text": "Prediction space complexity: O(1)" }, { "code": null, "e": 2865, "s": 2732, "text": "Training phase technically does not exist, since all computation is done during prediction, so we have O(1) for both time and space." }, { "code": null, "e": 2962, "s": 2865, "text": "Prediction phase is, as method name suggest, a simple exhaustive search, which in pseudocode is:" }, { "code": null, "e": 3292, "s": 2962, "text": "Loop through all points k times: 1. Compute the distance between currently classifier sample and training points, remember the index of the element with the smallest distance (ignore previously selected points) 2. Add the class at found index to the counterReturn the class with the most votes as a prediction" }, { "code": null, "e": 3644, "s": 3292, "text": "This is a nested loop structure, where the outer loop takes k steps and the inner loop takes n steps. 3rd point is O(1) and 4th is O(# of classes), so they are smaller. Additionally, we have to take into consideration the numer of dimensions d, more directions mean longer vectors to compute distances. Therefore, we have O(n * k * d) time complexity." }, { "code": null, "e": 3818, "s": 3644, "text": "As for space complexity, we need a small vector to count the votes for each class. It’s almost always very small and is fixed, so we can treat it as a O(1) space complexity." }, { "code": null, "e": 3862, "s": 3818, "text": "Training time complexity: O(d * n * log(n))" }, { "code": null, "e": 3898, "s": 3862, "text": "Training space complexity: O(d * n)" }, { "code": null, "e": 3940, "s": 3898, "text": "Prediction time complexity: O(k * log(n))" }, { "code": null, "e": 3974, "s": 3940, "text": "Prediction space complexity: O(1)" }, { "code": null, "e": 4432, "s": 3974, "text": "During the training phase, we have to construct the k-d tree. This data structure splits the k-dimensional space (here k means k dimensions of space, don’t confuse this with k as a number of nearest neighbors!) and allows faster search for nearest points, since we “know where to look” in that space. You may think of it like a generalization of BST for many dimensions. It “cuts” space with axis-aligned cuts, dividing points into groups in children nodes." }, { "code": null, "e": 5204, "s": 4432, "text": "Constructing the k-d tree is not a machine learning task itself, since it stems from computational geometry domain, so we won’t cover this in detail, only on conceptual level. The time complexity is usually O(d * n * log(n)), because insertion is O(log(n)) (similar to regular BST) and we have n points from the training dataset, each with d dimensions. I assume the efficient implementation of the data structure, i. e. it finds the optimal split point (median in the dimension) in O(n), which is possible with the median of medians algorithm. Space complexity is O(d * n) — note that it depends on dimensionality d, which makes sense, since more dimensions correspond to more space divisions and larger trees (in addition to larger time complexity for the same reason)." }, { "code": null, "e": 5909, "s": 5204, "text": "As for the prediction phase, the k-d tree structure naturally supports “k nearest point neighbors query” operation, which is exactly what we need for kNN. The simple approach is to just query k times, removing the point found each time — since query takes O(log(n)), it is O(k * log(n)) in total. But since the k-d tree already cuts space during construction, after a single query we approximately know where to look — we can just search the “surroundings” around that point. Therefore, practical implementations of k-d tree support querying for whole k neighbors at one time and with complexity O(sqrt(n) + k), which is much better for larger dimensionalities, which are very common in machine learning." }, { "code": null, "e": 6216, "s": 5909, "text": "The above complexities are the average ones, assuming the balanced k-d tree. The O(log(n)) times assumed above may degrade up to O(n) for unbalanced trees, but if the median is used during the tree construction, we should always get a tree with approximately O(log(n)) insertion/deletion/search complexity." }, { "code": null, "e": 6260, "s": 6216, "text": "Training time complexity: O(d * n * log(n))" }, { "code": null, "e": 6296, "s": 6260, "text": "Training space complexity: O(d * n)" }, { "code": null, "e": 6338, "s": 6296, "text": "Prediction time complexity: O(k * log(n))" }, { "code": null, "e": 6372, "s": 6338, "text": "Prediction space complexity: O(1)" }, { "code": null, "e": 6817, "s": 6372, "text": "Ball tree algorithm takes another approach to dividing space where training points lie. In contrast to k-d trees, which divides space with median value “cuts”, ball tree groups points into “balls” organized into a tree structure. They go from the largest (root, with all points) to the smallest (leaves, with only a few or even 1 point). It allows fast nearest neighbor lookup because nearby neighbors are in the same or at least close “balls”." }, { "code": null, "e": 7079, "s": 6817, "text": "During the training phase, we only need to construct the ball tree. There are a few algorithms for constructing the ball tree, but the one most similar to k-d tree (called “k-d construction algorithm” for that reason) is O(d * n * log(n)), the same as k-d tree." }, { "code": null, "e": 7196, "s": 7079, "text": "Because of the tree building similarity, the complexities of the prediction phase are also the same as for k-d tree." }, { "code": null, "e": 7381, "s": 7196, "text": "To summarize the complexities: brute force is the slowest in the big O notation, while both k-d tree and ball tree have the same lower complexity. How do we know which one to use then?" }, { "code": null, "e": 7913, "s": 7381, "text": "To get the answer, we have to look at both training and prediction times, that’s why I have provided both. The brute force algorithm has only one complexity, for prediction, O(k * n). Other algorithms need to create the data structure first, so for training and prediction they get O(d * n * log(n) + k * log(n)), not taking into account the space complexity, which may also be important. Therefore, where the construction of the trees is frequent, the training phase may outweigh their advantage of faster nearest neighbor lookup." }, { "code": null, "e": 8423, "s": 7913, "text": "Should we use k-d tree or ball tree? It depends on the data structure — relatively uniform or “well behaved” data will make better use of k-d tree, since the cuts of space will work well (near points will be close in the leaves after all cuts). For more clustered data the “balls” from the ball tree will reflect the structure better and therefore allow for faster nearest neighbor search. Fortunately, Scikit-learn supports “auto” option, which will automatically infer the best data structure from the data." }, { "code": null, "e": 8533, "s": 8423, "text": "Let’s see this in practice on two case studies, which I’ve encountered in practice during my studies and job." }, { "code": null, "e": 9032, "s": 8533, "text": "The more “traditional” application of the kNN is the classification of data. It often has quite a lot of points, e. g. MNIST has 60k training images and 10k test images. Classification is done offline, which means we first do the training phase, then just use the results during prediction. Therefore, if we want to construct the data structure, we only need to do so once. For 10k test images, let’s compare the brute force (which calculates all distances every time) and k-d tree for 3 neighbors:" }, { "code": null, "e": 9076, "s": 9032, "text": "Brute force (O(k * n)): 3 * 10,000 = 30,000" }, { "code": null, "e": 9132, "s": 9076, "text": "k-d tree (O(k * log(n))): 3 * log(10,000) ~ 3 * 13 = 39" }, { "code": null, "e": 9165, "s": 9132, "text": "Comparison: 39 / 30,000 = 0.0013" }, { "code": null, "e": 9337, "s": 9165, "text": "As you can see, the performance gain is huge! The data structure method uses only a tiny fraction of the brute force time. For most datasets this method is a clear winner." }, { "code": null, "e": 9750, "s": 9337, "text": "Machine Learning is commonly used for image recognition, often using neural networks. It’s very useful for real-time applications, where it’s often integrated with cameras, alarms etc. The problem with neural networks is that they often detect the same object 2 or more times — even the best architectures like YOLO have this problem. We can actually solve it with nearest neighbor search with a simple approach:" }, { "code": null, "e": 9951, "s": 9750, "text": "Calculate the center of each bounding box (rectangle)For each rectangle, search for its nearest neighbor (1NN)If points are closer than the selected threshold, merge them (they detect the same object)" }, { "code": null, "e": 10005, "s": 9951, "text": "Calculate the center of each bounding box (rectangle)" }, { "code": null, "e": 10063, "s": 10005, "text": "For each rectangle, search for its nearest neighbor (1NN)" }, { "code": null, "e": 10154, "s": 10063, "text": "If points are closer than the selected threshold, merge them (they detect the same object)" }, { "code": null, "e": 10833, "s": 10154, "text": "The crucial part is searching for the closest center of another bounding box (point 2). Which algorithm should be used here? Typically we have only a few moving objects on camera, maybe up to 30–40. For such a small number, speedup from using data structures for faster lookup is negligible. Each frame is a separate image, so if we wanted to construct a k-d tree for example, we would have to do so for every frame, which may mean 30 times per second — a huge cost overall. Therefore, for such situations a simple brute force method works fastest and also has the smallest space requirement (which, with heavy neural networks or for embedded CPUs in cameras, may be important)." } ]
What is XMLHTTPRequest Object ? - GeeksforGeeks
08 Apr, 2022 XMLHTTPRequest object is an API which is used for fetching data from the server. XMLHTTPRequest is basically used in Ajax programming. It retrieve any type of data such as json, xml, text etc. It request for data in background and update the page without reloading page on client side. An object of XMLHTTPRequest is used for asynchronous communication between client and server. The $.ajax() method is used for the creation of XMLHTTPRequest object. The $.ajax() does following steps in background: Send data from background. Receives the data from the server. Update webpage without reloading the page. Below we will see how to create XMLHTTPRequest object with $.ajax() method: Syntax: var XHR = $.ajax({configs}); Example: JavaScript // Example showing how XMLHTTPRequest object createdvar XMLO = $.ajax({ // Our sample URL to make the request url: 'https://jsonplaceholder.typicode.com/todos/1', // type of Request type: "GET"}); Now we will see the data-type of data that we can retrieve from the server and what pre-processor we have for respective data-type. Data-type: These are the data-type for we can request to the server. The available data types are text, xml, html, script, jsonp and json. On the basis of these data type, we specify the pre-processor to the response before handling it to the handler of XMLHTTPRequest object. Following are the pre-processor to the specified data-type: Text: If data-type is text no pre-processor is applied to the response. It can be access through responseText property of XMLHTTPRequest object. xml: In case of XML, pre-processor jQuery.parseXML is applied to the response and then passed to the handler as xml document. It can be access through responseXML property of the XMLRequestHTTPRequest object. html: In case of html data-type, we don’t specify any pre-processor to response. It can be accessed to with the responseText property. string: In case of script, script will first run and then it is handled to the handler in form of string. jsonp: In case of requesting jsong, we have to specify the jsonpCallback property of $.ajax() method. which will be execute before passing the json object to the successor handler. json: In case of json, response is parsed to jQuery.parseJSON before passing an object to the handler. Properties: XMLHTTPRequest object have many useful class properties which helps in the flexible handling of response. The XMLHTTPRequest object properties are: readyState: This property indicate the status of the connection. status: It contains the http response code from the server. statusText: It contains the http response string from the server.responseText: It contains the response in text format from the server. responseXML: It contains the response Xml from server. getAllResponseHeaders: This property returns all the headers name as string. getResponseHeader: It takes name of header and returns the text text value of header. setReaquestHeader: It is used for setting the value of request header. overrideMimeType: This property is used to set the mime type which is used to treat the response data-type to be treated as Text or XML type. Example: JavaScript // Demonstrating Properties of XMLHTTPRequest object<script> var xmlObj = $.ajax({ // Our sample url to make request url: 'https://jsonplaceholder.typicode.com/todos/1', // type of Request type: "GET"}); xmlObj.always(function(a, b, c) { console.log(" # Status of request is : ", c.status); console.log(" # readyState of request is : ", c.readyState); console.log(" # statusText of request is : ", c.statusText); console.log(" # All Response Headers of request is : ", c.getAllResponseHeaders); });</script> Output: # Status of request is : 200 # readyState of request is : 4 # statusText of request is : success # All Response Headers of request is : function(){return h?p:null} Below is the example of some properties of XMLHTTPRequest object: Methods: As we know XMLHTTPRequest make asynchronous communication and as a result it returns promise. We have many promise method of the jQuery XMLHTTPRequest object. Available promise methods are: xmlObject.then(): This method takes two callback function func1, func2 as a parameters. func1 call when promise is successfully resolved. And func2 is call when request fails. xmlObject.always(): This method take single callback function. This method makes handler to call when request is either resolve or rejected. Parameter function is call always without concern about request. xmlObject.then(): This method accept single callback function. This method will be call when our request is resolved. Parameter function will be run with resolve of request. xmlObject.fail(): this method accept single callback function. This method is call when our request is rejected. after refection of request callback function is resolve. Below is the example of some of the method of XMLHTTPRequest object: Example: JavaScript // Example demonstrating methods of XMLHTTPRequest// object<script> var xmlObj = $.ajax({ // Our sample url to make request url: 'https://jsonplaceholder.typicode.com/todos/1', // type of Request type: "GET",}); xmlObj.then(function(){ console.log(" #Then is resolved ");}); xmlObj.fail(function(){ console.log(" #Fail is resolved ");}); xmlObj.always(function(){ console.log(" #Always is resolved ");}); xmlObj.done(function(){ console.log(" #Done is resolved ");}); </script> Output: #Always is resolved #Done is resolved #Then is resolved anikakapoor varshagumber28 sweetyty adnanirshad158 simranarora5sos Blogathon-2021 jQuery-Questions Picked Blogathon JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to Install Tkinter in Windows? Python program to convert XML to Dictionary JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26160, "s": 26132, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26611, "s": 26160, "text": "XMLHTTPRequest object is an API which is used for fetching data from the server. XMLHTTPRequest is basically used in Ajax programming. It retrieve any type of data such as json, xml, text etc. It request for data in background and update the page without reloading page on client side. An object of XMLHTTPRequest is used for asynchronous communication between client and server. The $.ajax() method is used for the creation of XMLHTTPRequest object." }, { "code": null, "e": 26660, "s": 26611, "text": "The $.ajax() does following steps in background:" }, { "code": null, "e": 26687, "s": 26660, "text": "Send data from background." }, { "code": null, "e": 26722, "s": 26687, "text": "Receives the data from the server." }, { "code": null, "e": 26765, "s": 26722, "text": "Update webpage without reloading the page." }, { "code": null, "e": 26842, "s": 26765, "text": "Below we will see how to create XMLHTTPRequest object with $.ajax() method: " }, { "code": null, "e": 26851, "s": 26842, "text": "Syntax: " }, { "code": null, "e": 26880, "s": 26851, "text": "var XHR = $.ajax({configs});" }, { "code": null, "e": 26890, "s": 26880, "text": "Example: " }, { "code": null, "e": 26901, "s": 26890, "text": "JavaScript" }, { "code": "// Example showing how XMLHTTPRequest object createdvar XMLO = $.ajax({ // Our sample URL to make the request url: 'https://jsonplaceholder.typicode.com/todos/1', // type of Request type: \"GET\"});", "e": 27112, "s": 26901, "text": null }, { "code": null, "e": 27244, "s": 27112, "text": "Now we will see the data-type of data that we can retrieve from the server and what pre-processor we have for respective data-type." }, { "code": null, "e": 27581, "s": 27244, "text": "Data-type: These are the data-type for we can request to the server. The available data types are text, xml, html, script, jsonp and json. On the basis of these data type, we specify the pre-processor to the response before handling it to the handler of XMLHTTPRequest object. Following are the pre-processor to the specified data-type:" }, { "code": null, "e": 27726, "s": 27581, "text": "Text: If data-type is text no pre-processor is applied to the response. It can be access through responseText property of XMLHTTPRequest object." }, { "code": null, "e": 27935, "s": 27726, "text": "xml: In case of XML, pre-processor jQuery.parseXML is applied to the response and then passed to the handler as xml document. It can be access through responseXML property of the XMLRequestHTTPRequest object." }, { "code": null, "e": 28070, "s": 27935, "text": "html: In case of html data-type, we don’t specify any pre-processor to response. It can be accessed to with the responseText property." }, { "code": null, "e": 28176, "s": 28070, "text": "string: In case of script, script will first run and then it is handled to the handler in form of string." }, { "code": null, "e": 28358, "s": 28176, "text": "jsonp: In case of requesting jsong, we have to specify the jsonpCallback property of $.ajax() method. which will be execute before passing the json object to the successor handler." }, { "code": null, "e": 28461, "s": 28358, "text": "json: In case of json, response is parsed to jQuery.parseJSON before passing an object to the handler." }, { "code": null, "e": 28621, "s": 28461, "text": "Properties: XMLHTTPRequest object have many useful class properties which helps in the flexible handling of response. The XMLHTTPRequest object properties are:" }, { "code": null, "e": 28686, "s": 28621, "text": "readyState: This property indicate the status of the connection." }, { "code": null, "e": 28746, "s": 28686, "text": "status: It contains the http response code from the server." }, { "code": null, "e": 28882, "s": 28746, "text": "statusText: It contains the http response string from the server.responseText: It contains the response in text format from the server." }, { "code": null, "e": 28937, "s": 28882, "text": "responseXML: It contains the response Xml from server." }, { "code": null, "e": 29014, "s": 28937, "text": "getAllResponseHeaders: This property returns all the headers name as string." }, { "code": null, "e": 29100, "s": 29014, "text": "getResponseHeader: It takes name of header and returns the text text value of header." }, { "code": null, "e": 29171, "s": 29100, "text": "setReaquestHeader: It is used for setting the value of request header." }, { "code": null, "e": 29313, "s": 29171, "text": "overrideMimeType: This property is used to set the mime type which is used to treat the response data-type to be treated as Text or XML type." }, { "code": null, "e": 29322, "s": 29313, "text": "Example:" }, { "code": null, "e": 29333, "s": 29322, "text": "JavaScript" }, { "code": "// Demonstrating Properties of XMLHTTPRequest object<script> var xmlObj = $.ajax({ // Our sample url to make request url: 'https://jsonplaceholder.typicode.com/todos/1', // type of Request type: \"GET\"}); xmlObj.always(function(a, b, c) { console.log(\" # Status of request is : \", c.status); console.log(\" # readyState of request is : \", c.readyState); console.log(\" # statusText of request is : \", c.statusText); console.log(\" # All Response Headers of request is : \", c.getAllResponseHeaders); });</script>", "e": 29877, "s": 29333, "text": null }, { "code": null, "e": 29885, "s": 29877, "text": "Output:" }, { "code": null, "e": 30049, "s": 29885, "text": "# Status of request is : 200\n# readyState of request is : 4\n# statusText of request is : success\n# All Response Headers of request is : function(){return h?p:null}" }, { "code": null, "e": 30115, "s": 30049, "text": "Below is the example of some properties of XMLHTTPRequest object:" }, { "code": null, "e": 30315, "s": 30115, "text": "Methods: As we know XMLHTTPRequest make asynchronous communication and as a result it returns promise. We have many promise method of the jQuery XMLHTTPRequest object. Available promise methods are: " }, { "code": null, "e": 30491, "s": 30315, "text": "xmlObject.then(): This method takes two callback function func1, func2 as a parameters. func1 call when promise is successfully resolved. And func2 is call when request fails." }, { "code": null, "e": 30697, "s": 30491, "text": "xmlObject.always(): This method take single callback function. This method makes handler to call when request is either resolve or rejected. Parameter function is call always without concern about request." }, { "code": null, "e": 30871, "s": 30697, "text": "xmlObject.then(): This method accept single callback function. This method will be call when our request is resolved. Parameter function will be run with resolve of request." }, { "code": null, "e": 31041, "s": 30871, "text": "xmlObject.fail(): this method accept single callback function. This method is call when our request is rejected. after refection of request callback function is resolve." }, { "code": null, "e": 31110, "s": 31041, "text": "Below is the example of some of the method of XMLHTTPRequest object:" }, { "code": null, "e": 31120, "s": 31110, "text": "Example: " }, { "code": null, "e": 31131, "s": 31120, "text": "JavaScript" }, { "code": "// Example demonstrating methods of XMLHTTPRequest// object<script> var xmlObj = $.ajax({ // Our sample url to make request url: 'https://jsonplaceholder.typicode.com/todos/1', // type of Request type: \"GET\",}); xmlObj.then(function(){ console.log(\" #Then is resolved \");}); xmlObj.fail(function(){ console.log(\" #Fail is resolved \");}); xmlObj.always(function(){ console.log(\" #Always is resolved \");}); xmlObj.done(function(){ console.log(\" #Done is resolved \");}); </script>", "e": 31647, "s": 31131, "text": null }, { "code": null, "e": 31656, "s": 31647, "text": "Output: " }, { "code": null, "e": 31714, "s": 31656, "text": "#Always is resolved \n#Done is resolved \n#Then is resolved" }, { "code": null, "e": 31726, "s": 31714, "text": "anikakapoor" }, { "code": null, "e": 31741, "s": 31726, "text": "varshagumber28" }, { "code": null, "e": 31750, "s": 31741, "text": "sweetyty" }, { "code": null, "e": 31765, "s": 31750, "text": "adnanirshad158" }, { "code": null, "e": 31781, "s": 31765, "text": "simranarora5sos" }, { "code": null, "e": 31796, "s": 31781, "text": "Blogathon-2021" }, { "code": null, "e": 31813, "s": 31796, "text": "jQuery-Questions" }, { "code": null, "e": 31820, "s": 31813, "text": "Picked" }, { "code": null, "e": 31830, "s": 31820, "text": "Blogathon" }, { "code": null, "e": 31837, "s": 31830, "text": "JQuery" }, { "code": null, "e": 31854, "s": 31837, "text": "Web Technologies" }, { "code": null, "e": 31952, "s": 31854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32009, "s": 31952, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 32050, "s": 32009, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 32080, "s": 32050, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 32115, "s": 32080, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 32159, "s": 32115, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 32205, "s": 32159, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 32234, "s": 32205, "text": "Form validation using jQuery" }, { "code": null, "e": 32297, "s": 32234, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 32374, "s": 32297, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Perl | int() function - GeeksforGeeks
25 Jun, 2019 int() function in Perl returns the integer part of given value. It returns $_ if no value provided. Note that $_ is default input which is 0 in this case. The int() function does not do rounding. For rounding up a value to an integer, sprintf is used. Syntax: int(VAR) Parameters:VAR: value which is to be converted into integer Returns: Returns the integer part of VAR Example 1: #!/usr/bin/perl # Passing positive decimal value$int_val = int(19.8547);print"Integer value is $int_val\n"; # Passing negative decimal value$int_val = int(-18.659);print"Integer value is $int_val\n"; Output: Integer value is 19 Integer value is -18 Example 2: #!/usr/bin/perl # Passing fractional positive value$int_val = int(17 / 4);print"Integer value is $int_val\n"; # Passing fractional negative value$int_val = int(-17 / 4);print"Integer value is $int_val\n"; Output: Integer value is 4 Integer value is -4 Perl-function Perl-Math-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | join() Function Perl | length() Function Perl | Basic Syntax of a Perl Program Perl | Boolean Values Perl | sleep() Function Perl | Subroutines or Functions
[ { "code": null, "e": 25367, "s": 25339, "text": "\n25 Jun, 2019" }, { "code": null, "e": 25619, "s": 25367, "text": "int() function in Perl returns the integer part of given value. It returns $_ if no value provided. Note that $_ is default input which is 0 in this case. The int() function does not do rounding. For rounding up a value to an integer, sprintf is used." }, { "code": null, "e": 25636, "s": 25619, "text": "Syntax: int(VAR)" }, { "code": null, "e": 25696, "s": 25636, "text": "Parameters:VAR: value which is to be converted into integer" }, { "code": null, "e": 25737, "s": 25696, "text": "Returns: Returns the integer part of VAR" }, { "code": null, "e": 25748, "s": 25737, "text": "Example 1:" }, { "code": "#!/usr/bin/perl # Passing positive decimal value$int_val = int(19.8547);print\"Integer value is $int_val\\n\"; # Passing negative decimal value$int_val = int(-18.659);print\"Integer value is $int_val\\n\";", "e": 25950, "s": 25748, "text": null }, { "code": null, "e": 25958, "s": 25950, "text": "Output:" }, { "code": null, "e": 26000, "s": 25958, "text": "Integer value is 19\nInteger value is -18\n" }, { "code": null, "e": 26011, "s": 26000, "text": "Example 2:" }, { "code": "#!/usr/bin/perl # Passing fractional positive value$int_val = int(17 / 4);print\"Integer value is $int_val\\n\"; # Passing fractional negative value$int_val = int(-17 / 4);print\"Integer value is $int_val\\n\";", "e": 26218, "s": 26011, "text": null }, { "code": null, "e": 26226, "s": 26218, "text": "Output:" }, { "code": null, "e": 26265, "s": 26226, "text": "Integer value is 4\nInteger value is -4" }, { "code": null, "e": 26279, "s": 26265, "text": "Perl-function" }, { "code": null, "e": 26299, "s": 26279, "text": "Perl-Math-Functions" }, { "code": null, "e": 26304, "s": 26299, "text": "Perl" }, { "code": null, "e": 26309, "s": 26304, "text": "Perl" }, { "code": null, "e": 26407, "s": 26309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26449, "s": 26407, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 26463, "s": 26449, "text": "Perl | Arrays" }, { "code": null, "e": 26504, "s": 26463, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 26537, "s": 26504, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 26560, "s": 26537, "text": "Perl | join() Function" }, { "code": null, "e": 26585, "s": 26560, "text": "Perl | length() Function" }, { "code": null, "e": 26623, "s": 26585, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 26645, "s": 26623, "text": "Perl | Boolean Values" }, { "code": null, "e": 26669, "s": 26645, "text": "Perl | sleep() Function" } ]
Why are Python Strings Immutable? - GeeksforGeeks
26 Dec, 2020 An unchanging article alludes to the item which is once made can’t change its worth all its lifetime. Attempt to execute the accompanying code: Python3 name_1 = "Aarun" name_1[0] = 'T' You will get a mistake message when you need to change the substance of the string. Traceback (latest call last): Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in <module> name_1[0] = 'T' TypeError: 'str' object doesn't uphold thing task Arrangement One potential arrangement is to make another string object with vital alterations: Python3 name_1 = "Aarun" name_2 = "T" + name_1[1:] print("name_1 = ", name_1, "and name_2 = ", name_2) Output: name_1 = Aarun and name_2 = Tarun To watch that they are various strings, check with the id() work: Python3 name_1 = "Aarun"name_2 = "T" + name_1[1:] print("id of name_1 = ", id(name_1))print("id of name_2 = ", id(name_2)) Output: id of name_1 = 2342565667256 id of name_2 = 2342565669888 To see more about the idea of string permanence, think about the accompanying code: Python3 name_1 = "Aarun"name_2 = "Aarun" print("id of name_1 = ", id(name_1))print("id of name_2 = ", id(name_2)) At the point when the above lines of code are executed, you will find that the id’s of both name_1 and name_2 objects, which allude to the string “Aarun”, are the equivalent. To burrow further, execute the accompanying assertions: Python3 name_1 = "Aarun"print("id of name_1 = ", id(name_1)) name_1 = "Tarun"print("id of name_1 with new value = ", id(name_1)) Output: id of name_1 = 2342565667256 id of name_1 with new value = 2342565668656 As can be found in the above model, when a string reference is reinitialized with another worth, it is making another article instead of overwriting the past worth. Note: In Python, strings are made changeless so software engineers can’t adjust the substance of the item. This keeps away from superfluous bugs. Picked python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n26 Dec, 2020" }, { "code": null, "e": 25707, "s": 25561, "text": "An unchanging article alludes to the item which is once made can’t change its worth all its lifetime. Attempt to execute the accompanying code: " }, { "code": null, "e": 25715, "s": 25707, "text": "Python3" }, { "code": "name_1 = \"Aarun\" name_1[0] = 'T' ", "e": 25751, "s": 25715, "text": null }, { "code": null, "e": 25836, "s": 25751, "text": "You will get a mistake message when you need to change the substance of the string. " }, { "code": null, "e": 26012, "s": 25836, "text": "Traceback (latest call last): \nRecord \"/home/ca508dc8fa5ad71190ca982b0e3493a8.py\", line 2, in <module> \nname_1[0] = 'T' \nTypeError: 'str' object doesn't uphold thing task " }, { "code": null, "e": 26026, "s": 26012, "text": "Arrangement " }, { "code": null, "e": 26110, "s": 26026, "text": "One potential arrangement is to make another string object with vital alterations: " }, { "code": null, "e": 26118, "s": 26110, "text": "Python3" }, { "code": "name_1 = \"Aarun\" name_2 = \"T\" + name_1[1:] print(\"name_1 = \", name_1, \"and name_2 = \", name_2)", "e": 26215, "s": 26118, "text": null }, { "code": null, "e": 26223, "s": 26215, "text": "Output:" }, { "code": null, "e": 26259, "s": 26223, "text": "name_1 = Aarun and name_2 = Tarun" }, { "code": null, "e": 26326, "s": 26259, "text": "To watch that they are various strings, check with the id() work: " }, { "code": null, "e": 26334, "s": 26326, "text": "Python3" }, { "code": "name_1 = \"Aarun\"name_2 = \"T\" + name_1[1:] print(\"id of name_1 = \", id(name_1))print(\"id of name_2 = \", id(name_2))", "e": 26450, "s": 26334, "text": null }, { "code": null, "e": 26458, "s": 26450, "text": "Output:" }, { "code": null, "e": 26518, "s": 26458, "text": "id of name_1 = 2342565667256\nid of name_2 = 2342565669888" }, { "code": null, "e": 26603, "s": 26518, "text": "To see more about the idea of string permanence, think about the accompanying code: " }, { "code": null, "e": 26611, "s": 26603, "text": "Python3" }, { "code": "name_1 = \"Aarun\"name_2 = \"Aarun\" print(\"id of name_1 = \", id(name_1))print(\"id of name_2 = \", id(name_2))", "e": 26718, "s": 26611, "text": null }, { "code": null, "e": 26895, "s": 26718, "text": "At the point when the above lines of code are executed, you will find that the id’s of both name_1 and name_2 objects, which allude to the string “Aarun”, are the equivalent. " }, { "code": null, "e": 26952, "s": 26895, "text": "To burrow further, execute the accompanying assertions: " }, { "code": null, "e": 26960, "s": 26952, "text": "Python3" }, { "code": "name_1 = \"Aarun\"print(\"id of name_1 = \", id(name_1)) name_1 = \"Tarun\"print(\"id of name_1 with new value = \", id(name_1))", "e": 27083, "s": 26960, "text": null }, { "code": null, "e": 27091, "s": 27083, "text": "Output:" }, { "code": null, "e": 27167, "s": 27091, "text": "id of name_1 = 2342565667256\nid of name_1 with new value = 2342565668656" }, { "code": null, "e": 27334, "s": 27167, "text": "As can be found in the above model, when a string reference is reinitialized with another worth, it is making another article instead of overwriting the past worth. " }, { "code": null, "e": 27480, "s": 27334, "text": "Note: In Python, strings are made changeless so software engineers can’t adjust the substance of the item. This keeps away from superfluous bugs." }, { "code": null, "e": 27487, "s": 27480, "text": "Picked" }, { "code": null, "e": 27501, "s": 27487, "text": "python-string" }, { "code": null, "e": 27508, "s": 27501, "text": "Python" }, { "code": null, "e": 27606, "s": 27508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27638, "s": 27606, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27680, "s": 27638, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27722, "s": 27680, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27778, "s": 27722, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27805, "s": 27778, "text": "Python Classes and Objects" }, { "code": null, "e": 27844, "s": 27805, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27875, "s": 27844, "text": "Python | os.path.join() method" }, { "code": null, "e": 27904, "s": 27875, "text": "Create a directory in Python" }, { "code": null, "e": 27926, "s": 27904, "text": "Defaultdict in Python" } ]
Working with Date and Time in Julia - GeeksforGeeks
28 Jul, 2020 Julia provides a library to use Dates for dealing with date and time. The Dates module comes inbuilt with the Julia we just need to import it in order to use it. Now we need to prefix every function with an explicit type Dates, e.g Dates.Date. If you don’t want to prefix on each function just add using Dates in your code and then you will be able to use any function of Dates without using Dates as a prefix. The Dates module provides supplies classes to work with date and time. There are many functions available that are used to manipulate Date and Time in Julia. For working with Date the DateTime provides two main Modules: Date and DateTime are mostly used. They both are subtypes of the abstract TimeType. Dates.Date( year, month, date): It returns date with provided parameters. It is independent of time zones. Dates.Date(year): It returns date with the provided year, and the month, the day is set to 01 Dates.Date(year, month): It returns date with the provided year and month, and the date is set to 01. Dates.DateTime( year, month, date, hour, min, sec): It returns date and time and it specifies the exact moment in time. The accuracy is to a millisecond. Dates.today(): It provides the Date object for the current date Dates.now(): It returns a DateTime object for the current instance in time. Dates.now(Dates.UTC): It returns date with Coordinated Universal Time (UTC) time zone. For Example: Julia # import Dates moduleimport Dates # returns date with provided parameter and independent of time zoned = Dates.Date(2001, 12, 12) # returns a date with the provided year, and the month and day are set to 01d = Dates.Date(2001) # returns a date with the provided year and month, and the day is set to 01d = Dates.Date(2001, 11) # returns date and time and it specifies the exact moment in time. The accuracy is to a millisecond.d = Dates.DateTime(2001, 10, 1, 12, 11, 11) # returns the Date object for the current dated = Dates.today() # returns a DateTime object for the current instance in timed = Dates.now() # returns date with Coordinated Universal Time (UTC) time zoned = Dates.now(Dates.UTC) The output of the following code: Different_types_of_dates In order to format Dates, we need to refer the characters which represent/refer date elements. Here is a table for referring to what each character represents. We can these formatting strings with functions such as DateTime(), Dates.format() and Date() The following examples will show various date formatting methods: Using DateTime() Julia import Dates # formatting a string into a DateTime() Dates.DateTime("Tue, 11 Jan 2001 12:10:4", "e, d u y H:M:S") DateTime example Using Date() Julia import Dates # Convert a string date to a d/m/yyyy formatDates.Date("Mon, 12 Jan 2002", "e, d u y") Date_Example Using format() Julia import Dates # getting current timemy_time = Dates.now() # using format() to format string into timeDates.format(my_time, "e, dd u yyyy HH:MM:SS") format_example Sometimes we require leading zeros for single date element. This example shows how we can add leading zero. Julia import Dates my_time = Dates.DateTime("Mon, 1 Jun 2001 1:2:4", "e, d u y H:M:S") # with leading zerosDates.format(my_time, "e: dd u yy, HH.MM.SS") # without leading zeroDates.format(my_time, "e: d u yy, H.M.S") leading_zero_example Also, we can convert a date string from one format to other by using DateTime() to convert into DateTime object and then use DateFormat() to display/output to a different format. Julia import Dates # date that needs to be formatteddate = "Mon, 12 Jul 2001 12:13:14" # using DateTime() to obtain DateTime() obj.temp = Dates.DateTime(date, "e, dd u yyyy HH:MM:SS") # Using Dates.format()Dates.format(temp, "dd, U, yyyy HH:MM, e") one_form_to_another When we have a lot of dates to handle we use a DateFormat object to handle an array of string dates Julia import Dates # defining general format for datesdateformat = Dates.DateFormat("y-m-d"); Dates.Date.([ "2001-11-01", "2002-12-12", "2003-02-6", "2004-04-7", "2005-12-9", "2006-11-12" ], dateformat) array_of_dates We can also use Dates.ISODateTimeFormat which provides an ISO8601 format. The example is given below: Julia import Dates # ISODateTimeFormatDates.Date.([ "2001-11-01", "2002-12-12", "2003-02-6", "2004-04-7", "2005-12-9", "2006-11-12" ], Dates.ISODateTimeFormat) ISOFORMAT_format_example For obtaining time in Julia we use Dates.Time() function mostly. which follows the proleptic Gregorian calendar. The different types of time are as follows: Dates.Time(Dates.now()) it returns a time in HH:MM:SS:ss and it takes Date object. Dates.minute( t) it gives the minute of the Dates.Time object passed. Dates.hour(t) it gives the hour of the Dates.Time object passed. Dates.second(t) it gives the second of the Dates.Time object passed. Julia import Dates # creating a Dates objectt = Dates.now() # Provides the current timeDates.Time(t) # Provides the hour of date objectDates.hour(t) # Provides the second of date objectDates.second(t) # Provides the minutes of date objectDates.minute(t) time_module_example It is also referred to as UNIX time. It is used to deal with timekeeping. It is a count of the number of seconds that have elapsed since the beginning of the year 1970. The time() function, when used without any arguments, returns the Unix/Epoch time value of the current second. Julia # provides unix time of current secondtime() time()_output To convert UNIX time into more readable form we use strftime() (“string format time”) function. Julia # 1 year worth of UNIX timeLibc.strftime(86400 * 365.25 * 1) strftime() example The function unix2datetime() converts a UNIX time into date/time object. Julia import Dates # To convert from unix to date/time objectDates.unix2datetime(time()) unix2datetime() example There are many other functions for manipulating date and time. Refer to the official documentation to learn more about different implementation. Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia String concatenation in Julia Getting rounded value of a number in Julia - round() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Storing Output on a File in Julia Formatting of Strings in Julia Manipulating matrices in Julia while loop in Julia Creating array with repeated elements in Julia - repeat() Method Reshaping array dimensions in Julia | Array reshape() Method
[ { "code": null, "e": 25601, "s": 25573, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26012, "s": 25601, "text": "Julia provides a library to use Dates for dealing with date and time. The Dates module comes inbuilt with the Julia we just need to import it in order to use it. Now we need to prefix every function with an explicit type Dates, e.g Dates.Date. If you don’t want to prefix on each function just add using Dates in your code and then you will be able to use any function of Dates without using Dates as a prefix." }, { "code": null, "e": 26170, "s": 26012, "text": "The Dates module provides supplies classes to work with date and time. There are many functions available that are used to manipulate Date and Time in Julia." }, { "code": null, "e": 26316, "s": 26170, "text": "For working with Date the DateTime provides two main Modules: Date and DateTime are mostly used. They both are subtypes of the abstract TimeType." }, { "code": null, "e": 26423, "s": 26316, "text": "Dates.Date( year, month, date): It returns date with provided parameters. It is independent of time zones." }, { "code": null, "e": 26517, "s": 26423, "text": "Dates.Date(year): It returns date with the provided year, and the month, the day is set to 01" }, { "code": null, "e": 26619, "s": 26517, "text": "Dates.Date(year, month): It returns date with the provided year and month, and the date is set to 01." }, { "code": null, "e": 26773, "s": 26619, "text": "Dates.DateTime( year, month, date, hour, min, sec): It returns date and time and it specifies the exact moment in time. The accuracy is to a millisecond." }, { "code": null, "e": 26837, "s": 26773, "text": "Dates.today(): It provides the Date object for the current date" }, { "code": null, "e": 26913, "s": 26837, "text": "Dates.now(): It returns a DateTime object for the current instance in time." }, { "code": null, "e": 27000, "s": 26913, "text": "Dates.now(Dates.UTC): It returns date with Coordinated Universal Time (UTC) time zone." }, { "code": null, "e": 27013, "s": 27000, "text": "For Example:" }, { "code": null, "e": 27019, "s": 27013, "text": "Julia" }, { "code": "# import Dates moduleimport Dates # returns date with provided parameter and independent of time zoned = Dates.Date(2001, 12, 12) # returns a date with the provided year, and the month and day are set to 01d = Dates.Date(2001) # returns a date with the provided year and month, and the day is set to 01d = Dates.Date(2001, 11) # returns date and time and it specifies the exact moment in time. The accuracy is to a millisecond.d = Dates.DateTime(2001, 10, 1, 12, 11, 11) # returns the Date object for the current dated = Dates.today() # returns a DateTime object for the current instance in timed = Dates.now() # returns date with Coordinated Universal Time (UTC) time zoned = Dates.now(Dates.UTC) ", "e": 27726, "s": 27019, "text": null }, { "code": null, "e": 27760, "s": 27726, "text": "The output of the following code:" }, { "code": null, "e": 27785, "s": 27760, "text": "Different_types_of_dates" }, { "code": null, "e": 27945, "s": 27785, "text": "In order to format Dates, we need to refer the characters which represent/refer date elements. Here is a table for referring to what each character represents." }, { "code": null, "e": 28105, "s": 27945, "text": "We can these formatting strings with functions such as DateTime(), Dates.format() and Date() The following examples will show various date formatting methods:" }, { "code": null, "e": 28122, "s": 28105, "text": "Using DateTime()" }, { "code": null, "e": 28128, "s": 28122, "text": "Julia" }, { "code": "import Dates # formatting a string into a DateTime() Dates.DateTime(\"Tue, 11 Jan 2001 12:10:4\", \"e, d u y H:M:S\")", "e": 28243, "s": 28128, "text": null }, { "code": null, "e": 28260, "s": 28243, "text": "DateTime example" }, { "code": null, "e": 28273, "s": 28260, "text": "Using Date()" }, { "code": null, "e": 28279, "s": 28273, "text": "Julia" }, { "code": "import Dates # Convert a string date to a d/m/yyyy formatDates.Date(\"Mon, 12 Jan 2002\", \"e, d u y\")", "e": 28380, "s": 28279, "text": null }, { "code": null, "e": 28393, "s": 28380, "text": "Date_Example" }, { "code": null, "e": 28408, "s": 28393, "text": "Using format()" }, { "code": null, "e": 28414, "s": 28408, "text": "Julia" }, { "code": "import Dates # getting current timemy_time = Dates.now() # using format() to format string into timeDates.format(my_time, \"e, dd u yyyy HH:MM:SS\")", "e": 28567, "s": 28414, "text": null }, { "code": null, "e": 28582, "s": 28567, "text": "format_example" }, { "code": null, "e": 28690, "s": 28582, "text": "Sometimes we require leading zeros for single date element. This example shows how we can add leading zero." }, { "code": null, "e": 28696, "s": 28690, "text": "Julia" }, { "code": "import Dates my_time = Dates.DateTime(\"Mon, 1 Jun 2001 1:2:4\", \"e, d u y H:M:S\") # with leading zerosDates.format(my_time, \"e: dd u yy, HH.MM.SS\") # without leading zeroDates.format(my_time, \"e: d u yy, H.M.S\")", "e": 28911, "s": 28696, "text": null }, { "code": null, "e": 28935, "s": 28914, "text": "leading_zero_example" }, { "code": null, "e": 29114, "s": 28935, "text": "Also, we can convert a date string from one format to other by using DateTime() to convert into DateTime object and then use DateFormat() to display/output to a different format." }, { "code": null, "e": 29120, "s": 29114, "text": "Julia" }, { "code": "import Dates # date that needs to be formatteddate = \"Mon, 12 Jul 2001 12:13:14\" # using DateTime() to obtain DateTime() obj.temp = Dates.DateTime(date, \"e, dd u yyyy HH:MM:SS\") # Using Dates.format()Dates.format(temp, \"dd, U, yyyy HH:MM, e\")", "e": 29366, "s": 29120, "text": null }, { "code": null, "e": 29386, "s": 29366, "text": "one_form_to_another" }, { "code": null, "e": 29486, "s": 29386, "text": "When we have a lot of dates to handle we use a DateFormat object to handle an array of string dates" }, { "code": null, "e": 29492, "s": 29486, "text": "Julia" }, { "code": "import Dates # defining general format for datesdateformat = Dates.DateFormat(\"y-m-d\"); Dates.Date.([ \"2001-11-01\", \"2002-12-12\", \"2003-02-6\", \"2004-04-7\", \"2005-12-9\", \"2006-11-12\" ], dateformat) ", "e": 29735, "s": 29492, "text": null }, { "code": null, "e": 29750, "s": 29735, "text": "array_of_dates" }, { "code": null, "e": 29852, "s": 29750, "text": "We can also use Dates.ISODateTimeFormat which provides an ISO8601 format. The example is given below:" }, { "code": null, "e": 29858, "s": 29852, "text": "Julia" }, { "code": "import Dates # ISODateTimeFormatDates.Date.([ \"2001-11-01\", \"2002-12-12\", \"2003-02-6\", \"2004-04-7\", \"2005-12-9\", \"2006-11-12\" ], Dates.ISODateTimeFormat)", "e": 30055, "s": 29858, "text": null }, { "code": null, "e": 30080, "s": 30055, "text": "ISOFORMAT_format_example" }, { "code": null, "e": 30237, "s": 30080, "text": "For obtaining time in Julia we use Dates.Time() function mostly. which follows the proleptic Gregorian calendar. The different types of time are as follows:" }, { "code": null, "e": 30321, "s": 30237, "text": "Dates.Time(Dates.now()) it returns a time in HH:MM:SS:ss and it takes Date object." }, { "code": null, "e": 30391, "s": 30321, "text": "Dates.minute( t) it gives the minute of the Dates.Time object passed." }, { "code": null, "e": 30457, "s": 30391, "text": "Dates.hour(t) it gives the hour of the Dates.Time object passed." }, { "code": null, "e": 30526, "s": 30457, "text": "Dates.second(t) it gives the second of the Dates.Time object passed." }, { "code": null, "e": 30532, "s": 30526, "text": "Julia" }, { "code": "import Dates # creating a Dates objectt = Dates.now() # Provides the current timeDates.Time(t) # Provides the hour of date objectDates.hour(t) # Provides the second of date objectDates.second(t) # Provides the minutes of date objectDates.minute(t)", "e": 30785, "s": 30532, "text": null }, { "code": null, "e": 30805, "s": 30785, "text": "time_module_example" }, { "code": null, "e": 30975, "s": 30805, "text": "It is also referred to as UNIX time. It is used to deal with timekeeping. It is a count of the number of seconds that have elapsed since the beginning of the year 1970. " }, { "code": null, "e": 31086, "s": 30975, "text": "The time() function, when used without any arguments, returns the Unix/Epoch time value of the current second." }, { "code": null, "e": 31092, "s": 31086, "text": "Julia" }, { "code": "# provides unix time of current secondtime()", "e": 31137, "s": 31092, "text": null }, { "code": null, "e": 31151, "s": 31137, "text": "time()_output" }, { "code": null, "e": 31247, "s": 31151, "text": "To convert UNIX time into more readable form we use strftime() (“string format time”) function." }, { "code": null, "e": 31253, "s": 31247, "text": "Julia" }, { "code": "# 1 year worth of UNIX timeLibc.strftime(86400 * 365.25 * 1)", "e": 31314, "s": 31253, "text": null }, { "code": null, "e": 31333, "s": 31314, "text": "strftime() example" }, { "code": null, "e": 31406, "s": 31333, "text": "The function unix2datetime() converts a UNIX time into date/time object." }, { "code": null, "e": 31412, "s": 31406, "text": "Julia" }, { "code": "import Dates # To convert from unix to date/time objectDates.unix2datetime(time())", "e": 31496, "s": 31412, "text": null }, { "code": null, "e": 31520, "s": 31496, "text": "unix2datetime() example" }, { "code": null, "e": 31665, "s": 31520, "text": "There are many other functions for manipulating date and time. Refer to the official documentation to learn more about different implementation." }, { "code": null, "e": 31672, "s": 31665, "text": "Picked" }, { "code": null, "e": 31678, "s": 31672, "text": "Julia" }, { "code": null, "e": 31776, "s": 31678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31793, "s": 31776, "text": "Vectors in Julia" }, { "code": null, "e": 31823, "s": 31793, "text": "String concatenation in Julia" }, { "code": null, "e": 31883, "s": 31823, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 31956, "s": 31883, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 31990, "s": 31956, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 32021, "s": 31990, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 32052, "s": 32021, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 32072, "s": 32052, "text": "while loop in Julia" }, { "code": null, "e": 32137, "s": 32072, "text": "Creating array with repeated elements in Julia - repeat() Method" } ]
JavaScript TypeError - Can't define property "X": "Obj" is not extensible - GeeksforGeeks
29 Jul, 2020 This JavaScript exception can’t define property “x”: “obj” is not extensible occurs when Object.preventExtensions() used on an object to make it no longer extensible, So now, New properties can not be added to the object. Message: TypeError: Cannot create property for a non-extensible object (Edge) TypeError: can't define property "x": "obj" is not extensible (Firefox) TypeError: Cannot define property: "x", object is not extensible. (Chrome) Error Type: TypeError Cause of Error: After the Object.preventExtensions() method applied on an object, New properties are added to the object, Which is not permissible. Example 1: In this example, the new property is being added after the Object.preventExtensions() method applied, So the error has occurred. HTML <script> 'use strict'; var GFG_Obj = {'name': 'GFG'}; Object.preventExtensions(GFG_Obj); GFG_Obj.age = 22; // error here</script> Output(in console): TypeError: Cannot create property for a non-extensible object Example 2: In this example, the new property is being added using defineProperty() method after the Object.preventExtensions() method applied, So the error has occurred. HTML <script> 'use strict'; var GFG_Obj = {'name': 'GFG'}; Object.preventExtensions(GFG_Obj); // error here Object.defineProperty(GFG_Obj, 'person', { dob: "02/11/1997" } );</script> Output(in console): TypeError: Cannot define property 'person': object is not extensible JavaScript-Errors JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n29 Jul, 2020" }, { "code": null, "e": 26767, "s": 26545, "text": "This JavaScript exception can’t define property “x”: “obj” is not extensible occurs when Object.preventExtensions() used on an object to make it no longer extensible, So now, New properties can not be added to the object." }, { "code": null, "e": 26776, "s": 26767, "text": "Message:" }, { "code": null, "e": 26993, "s": 26776, "text": "TypeError: Cannot create property for a non-extensible object (Edge)\nTypeError: can't define property \"x\": \"obj\" is not extensible (Firefox)\nTypeError: Cannot define property: \"x\", object is not extensible. (Chrome)\n" }, { "code": null, "e": 27005, "s": 26993, "text": "Error Type:" }, { "code": null, "e": 27016, "s": 27005, "text": "TypeError\n" }, { "code": null, "e": 27165, "s": 27016, "text": "Cause of Error: After the Object.preventExtensions() method applied on an object, New properties are added to the object, Which is not permissible. " }, { "code": null, "e": 27305, "s": 27165, "text": "Example 1: In this example, the new property is being added after the Object.preventExtensions() method applied, So the error has occurred." }, { "code": null, "e": 27310, "s": 27305, "text": "HTML" }, { "code": "<script> 'use strict'; var GFG_Obj = {'name': 'GFG'}; Object.preventExtensions(GFG_Obj); GFG_Obj.age = 22; // error here</script>", "e": 27456, "s": 27310, "text": null }, { "code": null, "e": 27476, "s": 27456, "text": "Output(in console):" }, { "code": null, "e": 27539, "s": 27476, "text": "TypeError: Cannot create property for a non-extensible object\n" }, { "code": null, "e": 27709, "s": 27539, "text": "Example 2: In this example, the new property is being added using defineProperty() method after the Object.preventExtensions() method applied, So the error has occurred." }, { "code": null, "e": 27714, "s": 27709, "text": "HTML" }, { "code": "<script> 'use strict'; var GFG_Obj = {'name': 'GFG'}; Object.preventExtensions(GFG_Obj); // error here Object.defineProperty(GFG_Obj, 'person', { dob: \"02/11/1997\" } );</script>", "e": 27920, "s": 27714, "text": null }, { "code": null, "e": 27940, "s": 27920, "text": "Output(in console):" }, { "code": null, "e": 28010, "s": 27940, "text": "TypeError: Cannot define property 'person': object is not extensible\n" }, { "code": null, "e": 28028, "s": 28010, "text": "JavaScript-Errors" }, { "code": null, "e": 28039, "s": 28028, "text": "JavaScript" }, { "code": null, "e": 28056, "s": 28039, "text": "Web Technologies" }, { "code": null, "e": 28154, "s": 28056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28194, "s": 28154, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28255, "s": 28194, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28296, "s": 28255, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28318, "s": 28296, "text": "JavaScript | Promises" }, { "code": null, "e": 28372, "s": 28318, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28412, "s": 28372, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28445, "s": 28412, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28488, "s": 28445, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28538, "s": 28488, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Print characters and their frequencies in order of occurrence - GeeksforGeeks
09 Feb, 2022 Given string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below. Examples: Input : str = "geeksforgeeks" Output : g2 e4 k2 s2 f1 o1 r1 Input : str = "elephant" Output : e2 l1 p1 h1 a1 n1 t1 Source: SAP Interview Experience | Set 26 Approach: Create a count array to store the frequency of each character in the given string str. Traverse the string str again and check whether the frequency of that character is 0 or not. If not 0, then print the character along with its frequency and update its frequency to 0 in the hash table. This is done so that the same character is not printed again. C++ Java Python3 C# PHP Javascript // C++ implementation to print the character and// its frequency in order of its occurrence#include <bits/stdc++.h>using namespace std; #define SIZE 26 // function to print the character and its frequency// in order of its occurrencevoid printCharWithFreq(string str){ // size of the string 'str' int n = str.size(); // 'freq[]' implemented as hash table int freq[SIZE]; // initialize all elements of freq[] to 0 memset(freq, 0, sizeof(freq)); // accumulate frequency of each character in 'str' for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if frequency of character str[i] is not // equal to 0 if (freq[str[i] - 'a'] != 0) { // print the character along with its // frequency cout << str[i] << freq[str[i] - 'a'] << " "; // update frequency of str[i] to 0 so // that the same character is not printed // again freq[str[i] - 'a'] = 0; } }} // Driver program to test aboveint main(){ string str = "geeksforgeeks"; printCharWithFreq(str); return 0;} // Java implementation to print the character and// its frequency in order of its occurrencepublic class Char_frequency { static final int SIZE = 26; // function to print the character and its // frequency in order of its occurrence static void printCharWithFreq(String str) { // size of the string 'str' int n = str.length(); // 'freq[]' implemented as hash table int[] freq = new int[SIZE]; // accumulate frequency of each character // in 'str' for (int i = 0; i < n; i++) freq[str.charAt(i) - 'a']++; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if frequency of character str.charAt(i) // is not equal to 0 if (freq[str.charAt(i) - 'a'] != 0) { // print the character along with its // frequency System.out.print(str.charAt(i)); System.out.print(freq[str.charAt(i) - 'a'] + " "); // update frequency of str.charAt(i) to // 0 so that the same character is not // printed again freq[str.charAt(i) - 'a'] = 0; } } } // Driver program to test above public static void main(String args[]) { String str = "geeksforgeeks"; printCharWithFreq(str); }}// This code is contributed by Sumit Ghosh # Python3 implementation to pr the character and# its frequency in order of its occurrence # import libraryimport numpy as np # Function to print the character and its# frequency in order of its occurrencedef prCharWithFreq(str) : # Size of the 'str' n = len(str) # Initialize all elements of freq[] to 0 freq = np.zeros(26, dtype = np.int) # Accumulate frequency of each # character in 'str' for i in range(0, n) : freq[ord(str[i]) - ord('a')] += 1 # Traverse 'str' from left to right for i in range(0, n) : # if frequency of character str[i] # is not equal to 0 if (freq[ord(str[i])- ord('a')] != 0) : # print the character along # with its frequency print (str[i], freq[ord(str[i]) - ord('a')], end = " ") # Update frequency of str[i] to 0 so that # the same character is not printed again freq[ord(str[i]) - ord('a')] = 0 # Driver Codeif __name__ == "__main__" : str = "geeksforgeeks"; prCharWithFreq(str); # This code is contributed by 'Saloni1297' // C# implementation to print the// character and its frequency in// order of its occurrenceusing System; class GFG { static int SIZE = 26; // function to print the character and its // frequency in order of its occurrence static void printCharWithFreq(String str) { // size of the string 'str' int n = str.Length; // 'freq[]' implemented as hash table int[] freq = new int[SIZE]; // accumulate frequency of each character // in 'str' for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if frequency of character str.charAt(i) // is not equal to 0 if (freq[str[i] - 'a'] != 0) { // print the character along with its // frequency Console.Write(str[i]); Console.Write(freq[str[i] - 'a'] + " "); // update frequency of str.charAt(i) to // 0 so that the same character is not // printed again freq[str[i] - 'a'] = 0; } } } // Driver program to test above public static void Main() { String str = "geeksforgeeks"; printCharWithFreq(str); }} // This code is contributed by Sam007 <?php// PHP implementation to print the// character and its frequency in// order of its occurrence$SIZE = 26; // function to print the character and// its frequency in order of its occurrencefunction printCharWithFreq($str){ global $SIZE; // size of the string 'str' $n = strlen($str); // 'freq[]' implemented as hash table $freq = array_fill(0, $SIZE, NULL); // accumulate frequency of each // character in 'str' for ($i = 0; $i < $n; $i++) $freq[ord($str[$i]) - ord('a')]++; // traverse 'str' from left to right for ($i = 0; $i < $n; $i++) { // if frequency of character str[i] // is not equal to 0 if ($freq[ord($str[$i]) - ord('a')] != 0) { // print the character along with // its frequency echo $str[$i] . $freq[ord($str[$i]) - ord('a')] . " "; // update frequency of str[i] to 0 // so that the same character is // not printed again $freq[ord($str[$i]) - ord('a')] = 0; } }} // Driver Code$str = "geeksforgeeks";printCharWithFreq($str); // This code is contributed by ita_c?> <script>// Javascript implementation to print the character and// its frequency in order of its occurrence let SIZE = 26; // function to print the character and its // frequency in order of its occurrence function printCharWithFreq(str) { // size of the string 'str' let n = str.length; // 'freq[]' implemented as hash table let freq = new Array(SIZE); for(let i = 0; i < freq.length; i++) { freq[i] = 0; } // accumulate frequency of each character // in 'str' for (let i = 0; i < n; i++) freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // traverse 'str' from left to right for (let i = 0; i < n; i++) { // if frequency of character str.charAt(i) // is not equal to 0 if (freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] != 0) { // print the character along with its // frequency document.write(str[i]); document.write(freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] + " "); // update frequency of str.charAt(i) to // 0 so that the same character is not // printed again freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 0; } } } // Driver program to test above let str = "geeksforgeeks"; printCharWithFreq(str); // This code is contributed by rag2127. </script> g2 e4 k2 s2 f1 o1 r1 Time Complexity: O(n), where n is the number of characters in the string. Auxiliary Space: O(1), as there are only lowercase letters. Alternate Solution (Use Hashing) We can also use hashing to solve the problem. C++ Java Python3 C# Javascript // C++ implementation to//print the characters and// frequencies in order// of its occurrence#include <bits/stdc++.h>using namespace std; void prCharWithFreq(string s){ // Store all characters and // their frequencies in dictionary unordered_map<char, int> d; for(char i : s) { d[i]++; } // Print characters and their // frequencies in same order // of their appearance for(char i : s) { // Print only if this // character is not printed // before if(d[i] != 0) { cout << i << d[i] << " "; d[i] = 0; } }} // Driver Codeint main(){ string s="geeksforgeeks"; prCharWithFreq(s);} // This code is contributed by rutvik_56 // Java implementation to// print the characters and// frequencies in order// of its occurrenceimport java.util.*;class Gfg{ public static void prCharWithFreq(String s) { // Store all characters and // their frequencies in dictionary Map<Character, Integer> d = new HashMap<Character, Integer>(); for(int i = 0; i < s.length(); i++) { if(d.containsKey(s.charAt(i))) { d.put(s.charAt(i), d.get(s.charAt(i)) + 1); } else { d.put(s.charAt(i), 1); } } // Print characters and their // frequencies in same order // of their appearance for(int i = 0; i < s.length(); i++) { // Print only if this // character is not printed // before if(d.get(s.charAt(i)) != 0) { System.out.print(s.charAt(i)); System.out.print(d.get(s.charAt(i)) + " "); d.put(s.charAt(i), 0); } } } // Driver code public static void main(String []args) { String S = "geeksforgeeks"; prCharWithFreq(S); }} // This code is contributed by avanitrachhadiya2155 # Python3 implementation to print the characters and# frequencies in order of its occurrence def prCharWithFreq(str): # Store all characters and their frequencies # in dictionary d = {} for i in str: if i in d: d[i] += 1 else: d[i] = 1 # Print characters and their frequencies in # same order of their appearance for i in str: # Print only if this character is not printed # before. if d[i] != 0: print("{}{}".format(i,d[i]), end =" ") d[i] = 0 # Driver Codeif __name__ == "__main__" : str = "geeksforgeeks"; prCharWithFreq(str); # This code is contributed by 'Ankur Tripathi' // C# implementation to// print the characters and// frequencies in order// of its occurrence using System;using System.Collections;using System.Collections.Generic; class GFG{ public static void prCharWithFreq(string s){ // Store all characters and // their frequencies in dictionary Dictionary<char,int> d = new Dictionary<char,int>(); foreach(char i in s) { if(d.ContainsKey(i)) { d[i]++; } else { d[i]=1; } } // Print characters and their // frequencies in same order // of their appearance foreach(char i in s) { // Print only if this // character is not printed // before if(d[i] != 0) { Console.Write(i+d[i].ToString() + " "); d[i] = 0; } }} // Driver Codepublic static void Main(string []args){ string s="geeksforgeeks"; prCharWithFreq(s);}} // This code is contributed by pratham76 <script>// Javascript implementation to//print the characters and// frequencies in order// of its occurrence function prCharWithFreq(s){ // Store all characters and // their frequencies in dictionary var d = new Map(); s.split('').forEach(element => { if(d.has(element)) { d.set(element, d.get(element)+1); } else d.set(element, 1); }); // Print characters and their // frequencies in same order // of their appearance s.split('').forEach(element => { // Print only if this // character is not printed // before if(d.has(element) && d.get(element)!=0) { document.write( element + d.get(element) + " "); d.set(element, 0); } });} // Driver Codevar s="geeksforgeeks";prCharWithFreq(s); </script> g2 e4 k2 s2 f1 o1 r1 We can solve this problem quickly using the python Counter() method. The approach is very simple. 1) First create a dictionary using the Counter method having strings as keys and their frequencies as values. 2)Traverse in this dictionary print keys along with their values Python3 # Python3 implementation to print the characters and# frequencies in order of its occurrencefrom collections import Counter def prCharWithFreq(string): # Store all characters and their # frequencies using Counter function d = Counter(string) # Print characters and their frequencies in # same order of their appearance for i in d: print(i+str(d[i]), end=" ") string = "geeksforgeeks"prCharWithFreq(string) # This code is contributed by vikkycirus g2 e4 k2 s2 f1 o1 r1 This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp ManasChhabra2 ankurtripathi rutvik_56 pratham76 avanitrachhadiya2155 vikkycirus rag2127 famously avtarkumar719 varshagumber28 SAP Labs Strings SAP Labs Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26043, "s": 26015, "text": "\n09 Feb, 2022" }, { "code": null, "e": 26254, "s": 26043, "text": "Given string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below." }, { "code": null, "e": 26265, "s": 26254, "text": "Examples: " }, { "code": null, "e": 26381, "s": 26265, "text": "Input : str = \"geeksforgeeks\"\nOutput : g2 e4 k2 s2 f1 o1 r1\n\nInput : str = \"elephant\"\nOutput : e2 l1 p1 h1 a1 n1 t1" }, { "code": null, "e": 26423, "s": 26381, "text": "Source: SAP Interview Experience | Set 26" }, { "code": null, "e": 26784, "s": 26423, "text": "Approach: Create a count array to store the frequency of each character in the given string str. Traverse the string str again and check whether the frequency of that character is 0 or not. If not 0, then print the character along with its frequency and update its frequency to 0 in the hash table. This is done so that the same character is not printed again." }, { "code": null, "e": 26788, "s": 26784, "text": "C++" }, { "code": null, "e": 26793, "s": 26788, "text": "Java" }, { "code": null, "e": 26801, "s": 26793, "text": "Python3" }, { "code": null, "e": 26804, "s": 26801, "text": "C#" }, { "code": null, "e": 26808, "s": 26804, "text": "PHP" }, { "code": null, "e": 26819, "s": 26808, "text": "Javascript" }, { "code": "// C++ implementation to print the character and// its frequency in order of its occurrence#include <bits/stdc++.h>using namespace std; #define SIZE 26 // function to print the character and its frequency// in order of its occurrencevoid printCharWithFreq(string str){ // size of the string 'str' int n = str.size(); // 'freq[]' implemented as hash table int freq[SIZE]; // initialize all elements of freq[] to 0 memset(freq, 0, sizeof(freq)); // accumulate frequency of each character in 'str' for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if frequency of character str[i] is not // equal to 0 if (freq[str[i] - 'a'] != 0) { // print the character along with its // frequency cout << str[i] << freq[str[i] - 'a'] << \" \"; // update frequency of str[i] to 0 so // that the same character is not printed // again freq[str[i] - 'a'] = 0; } }} // Driver program to test aboveint main(){ string str = \"geeksforgeeks\"; printCharWithFreq(str); return 0;}", "e": 28002, "s": 26819, "text": null }, { "code": "// Java implementation to print the character and// its frequency in order of its occurrencepublic class Char_frequency { static final int SIZE = 26; // function to print the character and its // frequency in order of its occurrence static void printCharWithFreq(String str) { // size of the string 'str' int n = str.length(); // 'freq[]' implemented as hash table int[] freq = new int[SIZE]; // accumulate frequency of each character // in 'str' for (int i = 0; i < n; i++) freq[str.charAt(i) - 'a']++; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if frequency of character str.charAt(i) // is not equal to 0 if (freq[str.charAt(i) - 'a'] != 0) { // print the character along with its // frequency System.out.print(str.charAt(i)); System.out.print(freq[str.charAt(i) - 'a'] + \" \"); // update frequency of str.charAt(i) to // 0 so that the same character is not // printed again freq[str.charAt(i) - 'a'] = 0; } } } // Driver program to test above public static void main(String args[]) { String str = \"geeksforgeeks\"; printCharWithFreq(str); }}// This code is contributed by Sumit Ghosh", "e": 29428, "s": 28002, "text": null }, { "code": "# Python3 implementation to pr the character and# its frequency in order of its occurrence # import libraryimport numpy as np # Function to print the character and its# frequency in order of its occurrencedef prCharWithFreq(str) : # Size of the 'str' n = len(str) # Initialize all elements of freq[] to 0 freq = np.zeros(26, dtype = np.int) # Accumulate frequency of each # character in 'str' for i in range(0, n) : freq[ord(str[i]) - ord('a')] += 1 # Traverse 'str' from left to right for i in range(0, n) : # if frequency of character str[i] # is not equal to 0 if (freq[ord(str[i])- ord('a')] != 0) : # print the character along # with its frequency print (str[i], freq[ord(str[i]) - ord('a')], end = \" \") # Update frequency of str[i] to 0 so that # the same character is not printed again freq[ord(str[i]) - ord('a')] = 0 # Driver Codeif __name__ == \"__main__\" : str = \"geeksforgeeks\"; prCharWithFreq(str); # This code is contributed by 'Saloni1297'", "e": 30630, "s": 29428, "text": null }, { "code": "// C# implementation to print the// character and its frequency in// order of its occurrenceusing System; class GFG { static int SIZE = 26; // function to print the character and its // frequency in order of its occurrence static void printCharWithFreq(String str) { // size of the string 'str' int n = str.Length; // 'freq[]' implemented as hash table int[] freq = new int[SIZE]; // accumulate frequency of each character // in 'str' for (int i = 0; i < n; i++) freq[str[i] - 'a']++; // traverse 'str' from left to right for (int i = 0; i < n; i++) { // if frequency of character str.charAt(i) // is not equal to 0 if (freq[str[i] - 'a'] != 0) { // print the character along with its // frequency Console.Write(str[i]); Console.Write(freq[str[i] - 'a'] + \" \"); // update frequency of str.charAt(i) to // 0 so that the same character is not // printed again freq[str[i] - 'a'] = 0; } } } // Driver program to test above public static void Main() { String str = \"geeksforgeeks\"; printCharWithFreq(str); }} // This code is contributed by Sam007", "e": 31970, "s": 30630, "text": null }, { "code": "<?php// PHP implementation to print the// character and its frequency in// order of its occurrence$SIZE = 26; // function to print the character and// its frequency in order of its occurrencefunction printCharWithFreq($str){ global $SIZE; // size of the string 'str' $n = strlen($str); // 'freq[]' implemented as hash table $freq = array_fill(0, $SIZE, NULL); // accumulate frequency of each // character in 'str' for ($i = 0; $i < $n; $i++) $freq[ord($str[$i]) - ord('a')]++; // traverse 'str' from left to right for ($i = 0; $i < $n; $i++) { // if frequency of character str[i] // is not equal to 0 if ($freq[ord($str[$i]) - ord('a')] != 0) { // print the character along with // its frequency echo $str[$i] . $freq[ord($str[$i]) - ord('a')] . \" \"; // update frequency of str[i] to 0 // so that the same character is // not printed again $freq[ord($str[$i]) - ord('a')] = 0; } }} // Driver Code$str = \"geeksforgeeks\";printCharWithFreq($str); // This code is contributed by ita_c?>", "e": 33152, "s": 31970, "text": null }, { "code": "<script>// Javascript implementation to print the character and// its frequency in order of its occurrence let SIZE = 26; // function to print the character and its // frequency in order of its occurrence function printCharWithFreq(str) { // size of the string 'str' let n = str.length; // 'freq[]' implemented as hash table let freq = new Array(SIZE); for(let i = 0; i < freq.length; i++) { freq[i] = 0; } // accumulate frequency of each character // in 'str' for (let i = 0; i < n; i++) freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // traverse 'str' from left to right for (let i = 0; i < n; i++) { // if frequency of character str.charAt(i) // is not equal to 0 if (freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] != 0) { // print the character along with its // frequency document.write(str[i]); document.write(freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] + \" \"); // update frequency of str.charAt(i) to // 0 so that the same character is not // printed again freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 0; } } } // Driver program to test above let str = \"geeksforgeeks\"; printCharWithFreq(str); // This code is contributed by rag2127. </script>", "e": 34661, "s": 33152, "text": null }, { "code": null, "e": 34683, "s": 34661, "text": "g2 e4 k2 s2 f1 o1 r1 " }, { "code": null, "e": 34817, "s": 34683, "text": "Time Complexity: O(n), where n is the number of characters in the string. Auxiliary Space: O(1), as there are only lowercase letters." }, { "code": null, "e": 34897, "s": 34817, "text": "Alternate Solution (Use Hashing) We can also use hashing to solve the problem. " }, { "code": null, "e": 34901, "s": 34897, "text": "C++" }, { "code": null, "e": 34906, "s": 34901, "text": "Java" }, { "code": null, "e": 34914, "s": 34906, "text": "Python3" }, { "code": null, "e": 34917, "s": 34914, "text": "C#" }, { "code": null, "e": 34928, "s": 34917, "text": "Javascript" }, { "code": "// C++ implementation to//print the characters and// frequencies in order// of its occurrence#include <bits/stdc++.h>using namespace std; void prCharWithFreq(string s){ // Store all characters and // their frequencies in dictionary unordered_map<char, int> d; for(char i : s) { d[i]++; } // Print characters and their // frequencies in same order // of their appearance for(char i : s) { // Print only if this // character is not printed // before if(d[i] != 0) { cout << i << d[i] << \" \"; d[i] = 0; } }} // Driver Codeint main(){ string s=\"geeksforgeeks\"; prCharWithFreq(s);} // This code is contributed by rutvik_56", "e": 35594, "s": 34928, "text": null }, { "code": "// Java implementation to// print the characters and// frequencies in order// of its occurrenceimport java.util.*;class Gfg{ public static void prCharWithFreq(String s) { // Store all characters and // their frequencies in dictionary Map<Character, Integer> d = new HashMap<Character, Integer>(); for(int i = 0; i < s.length(); i++) { if(d.containsKey(s.charAt(i))) { d.put(s.charAt(i), d.get(s.charAt(i)) + 1); } else { d.put(s.charAt(i), 1); } } // Print characters and their // frequencies in same order // of their appearance for(int i = 0; i < s.length(); i++) { // Print only if this // character is not printed // before if(d.get(s.charAt(i)) != 0) { System.out.print(s.charAt(i)); System.out.print(d.get(s.charAt(i)) + \" \"); d.put(s.charAt(i), 0); } } } // Driver code public static void main(String []args) { String S = \"geeksforgeeks\"; prCharWithFreq(S); }} // This code is contributed by avanitrachhadiya2155", "e": 36900, "s": 35594, "text": null }, { "code": "# Python3 implementation to print the characters and# frequencies in order of its occurrence def prCharWithFreq(str): # Store all characters and their frequencies # in dictionary d = {} for i in str: if i in d: d[i] += 1 else: d[i] = 1 # Print characters and their frequencies in # same order of their appearance for i in str: # Print only if this character is not printed # before. if d[i] != 0: print(\"{}{}\".format(i,d[i]), end =\" \") d[i] = 0 # Driver Codeif __name__ == \"__main__\" : str = \"geeksforgeeks\"; prCharWithFreq(str); # This code is contributed by 'Ankur Tripathi'", "e": 37610, "s": 36900, "text": null }, { "code": "// C# implementation to// print the characters and// frequencies in order// of its occurrence using System;using System.Collections;using System.Collections.Generic; class GFG{ public static void prCharWithFreq(string s){ // Store all characters and // their frequencies in dictionary Dictionary<char,int> d = new Dictionary<char,int>(); foreach(char i in s) { if(d.ContainsKey(i)) { d[i]++; } else { d[i]=1; } } // Print characters and their // frequencies in same order // of their appearance foreach(char i in s) { // Print only if this // character is not printed // before if(d[i] != 0) { Console.Write(i+d[i].ToString() + \" \"); d[i] = 0; } }} // Driver Codepublic static void Main(string []args){ string s=\"geeksforgeeks\"; prCharWithFreq(s);}} // This code is contributed by pratham76", "e": 38505, "s": 37610, "text": null }, { "code": "<script>// Javascript implementation to//print the characters and// frequencies in order// of its occurrence function prCharWithFreq(s){ // Store all characters and // their frequencies in dictionary var d = new Map(); s.split('').forEach(element => { if(d.has(element)) { d.set(element, d.get(element)+1); } else d.set(element, 1); }); // Print characters and their // frequencies in same order // of their appearance s.split('').forEach(element => { // Print only if this // character is not printed // before if(d.has(element) && d.get(element)!=0) { document.write( element + d.get(element) + \" \"); d.set(element, 0); } });} // Driver Codevar s=\"geeksforgeeks\";prCharWithFreq(s); </script>", "e": 39296, "s": 38505, "text": null }, { "code": null, "e": 39318, "s": 39296, "text": "g2 e4 k2 s2 f1 o1 r1 " }, { "code": null, "e": 39416, "s": 39318, "text": "We can solve this problem quickly using the python Counter() method. The approach is very simple." }, { "code": null, "e": 39526, "s": 39416, "text": "1) First create a dictionary using the Counter method having strings as keys and their frequencies as values." }, { "code": null, "e": 39591, "s": 39526, "text": "2)Traverse in this dictionary print keys along with their values" }, { "code": null, "e": 39599, "s": 39591, "text": "Python3" }, { "code": "# Python3 implementation to print the characters and# frequencies in order of its occurrencefrom collections import Counter def prCharWithFreq(string): # Store all characters and their # frequencies using Counter function d = Counter(string) # Print characters and their frequencies in # same order of their appearance for i in d: print(i+str(d[i]), end=\" \") string = \"geeksforgeeks\"prCharWithFreq(string) # This code is contributed by vikkycirus", "e": 40074, "s": 39599, "text": null }, { "code": null, "e": 40096, "s": 40074, "text": "g2 e4 k2 s2 f1 o1 r1 " }, { "code": null, "e": 40517, "s": 40096, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 40523, "s": 40517, "text": "ukasp" }, { "code": null, "e": 40537, "s": 40523, "text": "ManasChhabra2" }, { "code": null, "e": 40551, "s": 40537, "text": "ankurtripathi" }, { "code": null, "e": 40561, "s": 40551, "text": "rutvik_56" }, { "code": null, "e": 40571, "s": 40561, "text": "pratham76" }, { "code": null, "e": 40592, "s": 40571, "text": "avanitrachhadiya2155" }, { "code": null, "e": 40603, "s": 40592, "text": "vikkycirus" }, { "code": null, "e": 40611, "s": 40603, "text": "rag2127" }, { "code": null, "e": 40620, "s": 40611, "text": "famously" }, { "code": null, "e": 40634, "s": 40620, "text": "avtarkumar719" }, { "code": null, "e": 40649, "s": 40634, "text": "varshagumber28" }, { "code": null, "e": 40658, "s": 40649, "text": "SAP Labs" }, { "code": null, "e": 40666, "s": 40658, "text": "Strings" }, { "code": null, "e": 40675, "s": 40666, "text": "SAP Labs" }, { "code": null, "e": 40683, "s": 40675, "text": "Strings" }, { "code": null, "e": 40781, "s": 40683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40856, "s": 40781, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 40913, "s": 40856, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 40949, "s": 40913, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 40996, "s": 40949, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 41049, "s": 40996, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 41085, "s": 41049, "text": "Convert string to char array in C++" }, { "code": null, "e": 41123, "s": 41085, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 41153, "s": 41123, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 41205, "s": 41153, "text": "Check whether two strings are anagram of each other" } ]
Count words that appear exactly two times in an array of words - GeeksforGeeks
07 Aug, 2021 Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There are two words "Om" and "Jerry" that appear twice. Source: Amazon Interview Below is the implementation: C++ Java Python3 C# Javascript // C++ program to count all words with count// exactly 2.#include <bits/stdc++.h>using namespace std; // Returns count of words with frequency// exactly 2.int countWords(string str[], int n){ unordered_map<string, int> m; for (int i = 0; i < n; i++) m[str[i]] += 1; int res = 0; for (auto it = m.begin(); it != m.end(); it++) if ((it->second == 2)) res++; return res;} // Driver codeint main(){ string s[] = { "hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace" }; int n = sizeof(s) / sizeof(s[0]); cout << countWords(s, n); return 0;} // Java program to count all words with count// exactly 2.import java.util.HashMap;import java.util.Map;public class GFG { // Returns count of words with frequency // exactly 2. static int countWords(String str[], int n) { // map to store count of each word HashMap<String, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++){ if(m.containsKey(str[i])){ int get = m.get(str[i]); m.put(str[i], get + 1); } else{ m.put(str[i], 1); } } int res = 0; for (Map.Entry<String, Integer> it: m.entrySet()){ if(it.getValue() == 2) res++; } return res; } // Driver code public static void main(String args[]) { String s[] = { "hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace" }; int n = s.length; System.out.println( countWords(s, n)); }}// This code is contributed by Sumit Ghosh # Python program to count all# words with count# exactly 2. # Returns count of words with frequency# exactly 2.def countWords(stri, n): m = dict() for i in range(n): m[stri[i]] = m.get(stri[i],0) + 1 res = 0 for i in m.values(): if i == 2: res += 1 return res # Driver codes = [ "hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace" ]n = len(s)print(countWords(s, n)) # This code is contributed# by Shubham Rana // C# program to count all words with count// exactly 2.using System;using System.Collections.Generic; class GFG{ // Returns count of words with frequency // exactly 2. static int countWords(String []str, int n) { // map to store count of each word Dictionary<String,int> m = new Dictionary<String,int>(); for (int i = 0; i < n; i++) { if(m.ContainsKey(str[i])) { int get = m[str[i]]; m.Remove(str[i]); m.Add(str[i], get + 1); } else { m.Add(str[i], 1); } } int res = 0; foreach(KeyValuePair<String, int> it in m) { if(it.Value == 2) res++; } return res; } // Driver code public static void Main(String []args) { String []a = { "hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace" }; int n = a.Length; Console.WriteLine( countWords(a, n)); }} // This code is contributed by Rajput-Ji <script> // Javascript program to count all words with count// exactly 2. // Returns count of words with frequency// exactly 2.function countWords(str, n){ var m = new Map(); for (var i = 0; i < n; i++) { if(m.has(str[i])) m.set(str[i], m.get(str[i])+1) else m.set(str[i], 1) } var res = 0; m.forEach((value, key) => { if ((value == 2)) res++; }); return res;} // Driver codevar s = ["hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace" ];var n = s.length;document.write( countWords(s, n)); </script> 1 Count the frequencies of every word using the Counter function Traverse in frequency dictionary Check which word has frequency 2. If so, increase the count Print Count Below is the implementation: Python # importing Counter from collectionsfrom collections import Counter # Python program to count all words with count exactly 2.# Returns count of words with frequency exactly 2.def countWords(stri, n): # Calculating frequency using Counter m = Counter(stri) count = 0 # Traversing in freq dictionary for i in m: if m[i] == 2: count += 1 return count # Driver codes = ["hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"]n = len(s)print(countWords(s, n)) # This code is contributed by vikkycirus 1 YouTubeGeeksforGeeks502K subscribersCount words that appear exactly two times in an array of words | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ast7ctj1pqA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Saumya Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji vikkycirus noob2000 bunnyram19 simranarora5sos Amazon cpp-unordered_map STL Strings Amazon Strings STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Array of Strings in C++ (5 Different Ways to Create) Caesar Cipher in Cryptography Check whether two strings are anagram of each other Reverse words in a given string Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 25024, "s": 24996, "text": "\n07 Aug, 2021" }, { "code": null, "e": 25112, "s": 25024, "text": "Given an array of n words. Some words are repeated twice, we need to count such words. " }, { "code": null, "e": 25123, "s": 25112, "text": "Examples: " }, { "code": null, "e": 25476, "s": 25123, "text": "Input : s[] = {\"hate\", \"love\", \"peace\", \"love\", \n \"peace\", \"hate\", \"love\", \"peace\", \n \"love\", \"peace\"};\nOutput : 1\nThere is only one word \"hate\" that appears twice\n\nInput : s[] = {\"Om\", \"Om\", \"Shankar\", \"Tripathi\", \n \"Tom\", \"Jerry\", \"Jerry\"};\nOutput : 2\nThere are two words \"Om\" and \"Jerry\" that appear\ntwice." }, { "code": null, "e": 25501, "s": 25476, "text": "Source: Amazon Interview" }, { "code": null, "e": 25531, "s": 25501, "text": "Below is the implementation: " }, { "code": null, "e": 25535, "s": 25531, "text": "C++" }, { "code": null, "e": 25540, "s": 25535, "text": "Java" }, { "code": null, "e": 25548, "s": 25540, "text": "Python3" }, { "code": null, "e": 25551, "s": 25548, "text": "C#" }, { "code": null, "e": 25562, "s": 25551, "text": "Javascript" }, { "code": "// C++ program to count all words with count// exactly 2.#include <bits/stdc++.h>using namespace std; // Returns count of words with frequency// exactly 2.int countWords(string str[], int n){ unordered_map<string, int> m; for (int i = 0; i < n; i++) m[str[i]] += 1; int res = 0; for (auto it = m.begin(); it != m.end(); it++) if ((it->second == 2)) res++; return res;} // Driver codeint main(){ string s[] = { \"hate\", \"love\", \"peace\", \"love\", \"peace\", \"hate\", \"love\", \"peace\", \"love\", \"peace\" }; int n = sizeof(s) / sizeof(s[0]); cout << countWords(s, n); return 0;}", "e": 26219, "s": 25562, "text": null }, { "code": "// Java program to count all words with count// exactly 2.import java.util.HashMap;import java.util.Map;public class GFG { // Returns count of words with frequency // exactly 2. static int countWords(String str[], int n) { // map to store count of each word HashMap<String, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++){ if(m.containsKey(str[i])){ int get = m.get(str[i]); m.put(str[i], get + 1); } else{ m.put(str[i], 1); } } int res = 0; for (Map.Entry<String, Integer> it: m.entrySet()){ if(it.getValue() == 2) res++; } return res; } // Driver code public static void main(String args[]) { String s[] = { \"hate\", \"love\", \"peace\", \"love\", \"peace\", \"hate\", \"love\", \"peace\", \"love\", \"peace\" }; int n = s.length; System.out.println( countWords(s, n)); }}// This code is contributed by Sumit Ghosh", "e": 27341, "s": 26219, "text": null }, { "code": "# Python program to count all# words with count# exactly 2. # Returns count of words with frequency# exactly 2.def countWords(stri, n): m = dict() for i in range(n): m[stri[i]] = m.get(stri[i],0) + 1 res = 0 for i in m.values(): if i == 2: res += 1 return res # Driver codes = [ \"hate\", \"love\", \"peace\", \"love\", \"peace\", \"hate\", \"love\", \"peace\", \"love\", \"peace\" ]n = len(s)print(countWords(s, n)) # This code is contributed# by Shubham Rana", "e": 27848, "s": 27341, "text": null }, { "code": "// C# program to count all words with count// exactly 2.using System;using System.Collections.Generic; class GFG{ // Returns count of words with frequency // exactly 2. static int countWords(String []str, int n) { // map to store count of each word Dictionary<String,int> m = new Dictionary<String,int>(); for (int i = 0; i < n; i++) { if(m.ContainsKey(str[i])) { int get = m[str[i]]; m.Remove(str[i]); m.Add(str[i], get + 1); } else { m.Add(str[i], 1); } } int res = 0; foreach(KeyValuePair<String, int> it in m) { if(it.Value == 2) res++; } return res; } // Driver code public static void Main(String []args) { String []a = { \"hate\", \"love\", \"peace\", \"love\", \"peace\", \"hate\", \"love\", \"peace\", \"love\", \"peace\" }; int n = a.Length; Console.WriteLine( countWords(a, n)); }} // This code is contributed by Rajput-Ji", "e": 29019, "s": 27848, "text": null }, { "code": "<script> // Javascript program to count all words with count// exactly 2. // Returns count of words with frequency// exactly 2.function countWords(str, n){ var m = new Map(); for (var i = 0; i < n; i++) { if(m.has(str[i])) m.set(str[i], m.get(str[i])+1) else m.set(str[i], 1) } var res = 0; m.forEach((value, key) => { if ((value == 2)) res++; }); return res;} // Driver codevar s = [\"hate\", \"love\", \"peace\", \"love\", \"peace\", \"hate\", \"love\", \"peace\", \"love\", \"peace\" ];var n = s.length;document.write( countWords(s, n)); </script>", "e": 29667, "s": 29019, "text": null }, { "code": null, "e": 29669, "s": 29667, "text": "1" }, { "code": null, "e": 29732, "s": 29669, "text": "Count the frequencies of every word using the Counter function" }, { "code": null, "e": 29765, "s": 29732, "text": "Traverse in frequency dictionary" }, { "code": null, "e": 29825, "s": 29765, "text": "Check which word has frequency 2. If so, increase the count" }, { "code": null, "e": 29837, "s": 29825, "text": "Print Count" }, { "code": null, "e": 29866, "s": 29837, "text": "Below is the implementation:" }, { "code": null, "e": 29873, "s": 29866, "text": "Python" }, { "code": "# importing Counter from collectionsfrom collections import Counter # Python program to count all words with count exactly 2.# Returns count of words with frequency exactly 2.def countWords(stri, n): # Calculating frequency using Counter m = Counter(stri) count = 0 # Traversing in freq dictionary for i in m: if m[i] == 2: count += 1 return count # Driver codes = [\"hate\", \"love\", \"peace\", \"love\", \"peace\", \"hate\", \"love\", \"peace\", \"love\", \"peace\"]n = len(s)print(countWords(s, n)) # This code is contributed by vikkycirus", "e": 30446, "s": 29873, "text": null }, { "code": null, "e": 30448, "s": 30446, "text": "1" }, { "code": null, "e": 31309, "s": 30448, "text": "YouTubeGeeksforGeeks502K subscribersCount words that appear exactly two times in an array of words | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:46•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Ast7ctj1pqA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 31730, "s": 31309, "text": "This article is contributed by Saumya Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31740, "s": 31730, "text": "Rajput-Ji" }, { "code": null, "e": 31751, "s": 31740, "text": "vikkycirus" }, { "code": null, "e": 31760, "s": 31751, "text": "noob2000" }, { "code": null, "e": 31771, "s": 31760, "text": "bunnyram19" }, { "code": null, "e": 31787, "s": 31771, "text": "simranarora5sos" }, { "code": null, "e": 31794, "s": 31787, "text": "Amazon" }, { "code": null, "e": 31812, "s": 31794, "text": "cpp-unordered_map" }, { "code": null, "e": 31816, "s": 31812, "text": "STL" }, { "code": null, "e": 31824, "s": 31816, "text": "Strings" }, { "code": null, "e": 31831, "s": 31824, "text": "Amazon" }, { "code": null, "e": 31839, "s": 31831, "text": "Strings" }, { "code": null, "e": 31843, "s": 31839, "text": "STL" }, { "code": null, "e": 31941, "s": 31843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31998, "s": 31941, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 32034, "s": 31998, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 32081, "s": 32034, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32117, "s": 32081, "text": "Convert string to char array in C++" }, { "code": null, "e": 32155, "s": 32117, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32208, "s": 32155, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 32238, "s": 32208, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32290, "s": 32238, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 32322, "s": 32290, "text": "Reverse words in a given string" } ]
C++ Map Library - find() Function
The C++ function std::map::find() finds an element associated with key k. If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end(). Following is the declaration for std::map::find() function form std::map header. iterator find (const key_type& k); const_iterator find (const key_type& k) const; k − Key to be searched. If object is constant qualified then method returns a constant iterator otherwise non-constant iterator. This member function doesn't throw any exception. Logarithmic i.e. O(log n) The following example shows the usage of std::map::find() function. #include <iostream> #include <map> using namespace std; int main(void) { map<char, int> m = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}, }; auto it = m.find('c'); cout << "Iterator points to " << it->first << " = " << it->second << endl; return 0; } Let us compile and run the above program, this will produce the following result − Iterator points to c = 3 Print Add Notes Bookmark this page
[ { "code": null, "e": 2677, "s": 2603, "text": "The C++ function std::map::find() finds an element associated with key k." }, { "code": null, "e": 2811, "s": 2677, "text": "If operation succeeds then methods returns iterator pointing to the element otherwise it returns an iterator pointing the map::end()." }, { "code": null, "e": 2892, "s": 2811, "text": "Following is the declaration for std::map::find() function form std::map header." }, { "code": null, "e": 2975, "s": 2892, "text": "iterator find (const key_type& k);\nconst_iterator find (const key_type& k) const;\n" }, { "code": null, "e": 2999, "s": 2975, "text": "k − Key to be searched." }, { "code": null, "e": 3104, "s": 2999, "text": "If object is constant qualified then method returns a constant iterator otherwise non-constant iterator." }, { "code": null, "e": 3154, "s": 3104, "text": "This member function doesn't throw any exception." }, { "code": null, "e": 3180, "s": 3154, "text": "Logarithmic i.e. O(log n)" }, { "code": null, "e": 3248, "s": 3180, "text": "The following example shows the usage of std::map::find() function." }, { "code": null, "e": 3601, "s": 3248, "text": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main(void) {\n map<char, int> m = {\n {'a', 1},\n {'b', 2},\n {'c', 3},\n {'d', 4},\n {'e', 5},\n };\n\n auto it = m.find('c');\n\n cout << \"Iterator points to \" << it->first << \n \" = \" << it->second << endl;\n\n return 0;\n}" }, { "code": null, "e": 3684, "s": 3601, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3710, "s": 3684, "text": "Iterator points to c = 3\n" }, { "code": null, "e": 3717, "s": 3710, "text": " Print" }, { "code": null, "e": 3728, "s": 3717, "text": " Add Notes" } ]
Machine Learning With Spark. A distributed Machine Learning... | by MA Raza, Ph.D. | Towards Data Science
This is a comprehensive tutorial on using the Spark distributed machine learning framework to build a scalable ML data pipeline. I will cover the basic machine learning algorithms implemented in Spark MLlib library and through this tutorial, I will use the PySpark in python environment. Machine learning is getting popular in solving real-world problems in almost every business domain. It helps solve the problems using the data which is often unstructured, noisy, and in huge size. With the increase in data sizes and various sources of data, solving machine learning problems using standard techniques pose a big challenge. Spark is a distributed processing engine using the MapReduce framework to solve problems related to big data and processing of it. Spark framework has its own machine learning module called MLlib. In this article, I will use pyspark and spark MLlib to demonstrate the use of machine learning using distributed processing. Readers will be able to learn the below concept with real examples. Setting up Spark in the Google Colaboratory Machine Learning Basic Concepts Preprocessing and Data Transformation using Spark Spark Clustering with pyspark Classification with pyspark Regression methods with pyspark A working google colab notebook will be provided to reproduce the results. Since this article is a hands-on tutorial covering the transformations, classification, clustering, and regression using pyspark in one session, the length of the article is longer than my previous articles. One benefit is that you can go through the basic concepts and implementation in one go. According to Apache Spark and Delta Lake Under the Hood Apache Spark is a unified computing engine and a set of libraries for parallel data processing on computer clusters. As of the time this writing, Spark is the most actively developed open source engine for this task; making it the de facto tool for any developer or data scientist interested in big data. Spark supports multiple widely used programming languages (Python, Java, Scala and R), includes libraries for diverse tasks ranging from SQL to streaming and machine learning, and runs anywhere from a laptop to a cluster of thousands of servers. This makes it an easy system to start with and scale up to big data processing or incredibly large scale. As a first step, I configure the google colab runtime with spark installation. For details, readers may read my article Getting Started Spark 3.0.0 in Google Colab om medium. We will install the below programs Java 8 spark-3.0.1 Hadoop3.2 Findspark you can install the LATEST version of Spark using the below set of commands. # Run below commands!apt-get install openjdk-8-jdk-headless -qq > /dev/null!wget -q http://apache.osuosl.org/spark/spark-3.0.1/spark-3.0.1-bin-hadoop3.2.tgz!tar xf spark-3.0.1-bin-hadoop3.2.tgz!pip install -q findspark After installing the spark and Java, set the environment variables where Spark and Java are installed. import osos.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"os.environ["SPARK_HOME"] = "/content/spark-3.0.1-bin-hadoop3.2" Let us test the installation of spark in our google colab environment. import findsparkfindspark.init()from pyspark.sql import SparkSessionspark = SparkSession.builder.master("local[*]").getOrCreate()# Test the spark df = spark.createDataFrame([{"hello": "world"} for x in range(1000)])df.show(3, False)/content/spark-3.0.1-bin-hadoop3.2/python/pyspark/sql/session.py:381: UserWarning: inferring schema from dict is deprecated,please use pyspark.sql.Row instead warnings.warn("inferring schema from dict is deprecated,"+-----+|hello|+-----+|world||world||world|+-----+only showing top 3 rows# make sure the version of pysparkimport pysparkprint(pyspark.__version__)3.0.1 Once, we have set up the spark in google colab and made sure it is running with the correct version i.e. 3.0.1 in this case, we can start exploring the machine learning API developed on top of Spark. PySpark is a higher level Python API to use spark with python. For this tutorial, I assume the readers have a basic understanding of Machine Learning and SK-Learn for model building and training. Spark MLlib used the same fit and predict structure as in SK-Learn. In order to reproduce the results, I have uploaded the data to my GitHub and can be accessed easily. Learn by Doing: Use the colab notebook to run it yourself This section covers the basic steps involved in transformations of input feature data into the format Machine Learning algorithms accept. We will be covering the transformations coming with the SparkML library. To understand or read more about the available spark transformations in 3.0.3, follow the below link. spark.apache.org MinMaxScaler is one of the favorite classes shipped with most machine learning libraries. It scaled the data between 0 and 1. from pyspark.ml.feature import MinMaxScalerfrom pyspark.ml.linalg import Vectors# Create some dummy feature datafeatures_df = spark.createDataFrame([ (1, Vectors.dense([10.0,10000.0,1.0]),), (2, Vectors.dense([20.0,30000.0,2.0]),), (3, Vectors.dense([30.0,40000.0,3.0]),), ],["id", "features"] )features_df.show()+---+------------------+| id| features|+---+------------------+| 1|[10.0,10000.0,1.0]|| 2|[20.0,30000.0,2.0]|| 3|[30.0,40000.0,3.0]|+---+------------------+# Apply MinMaxScaler transformationfeatures_scaler = MinMaxScaler(inputCol = "features", outputCol = "sfeatures")smodel = features_scaler.fit(features_df)sfeatures_df = smodel.transform(features_df)sfeatures_df.show()+---+------------------+--------------------+| id| features| sfeatures|+---+------------------+--------------------+| 1|[10.0,10000.0,1.0]| (3,[],[])|| 2|[20.0,30000.0,2.0]|[0.5,0.6666666666...|| 3|[30.0,40000.0,3.0]| [1.0,1.0,1.0]|+---+------------------+--------------------+ StandardScaler is another well-known class written with machine learning libraries. It normalizes the data between -1 and 1 and converts the data into bell-shaped data. You can demean the data and scale to some variance. from pyspark.ml.feature import StandardScalerfrom pyspark.ml.linalg import Vectors# Create the dummy datafeatures_df = spark.createDataFrame([ (1, Vectors.dense([10.0,10000.0,1.0]),), (2, Vectors.dense([20.0,30000.0,2.0]),), (3, Vectors.dense([30.0,40000.0,3.0]),), ],["id", "features"] )# Apply the StandardScaler modelfeatures_stand_scaler = StandardScaler(inputCol = "features", outputCol = "sfeatures", withStd=True, withMean=True)stmodel = features_stand_scaler.fit(features_df)stand_sfeatures_df = stmodel.transform(features_df)stand_sfeatures_df.show()+---+------------------+--------------------+| id| features| sfeatures|+---+------------------+--------------------+| 1|[10.0,10000.0,1.0]|[-1.0,-1.09108945...|| 2|[20.0,30000.0,2.0]|[0.0,0.2182178902...|| 3|[30.0,40000.0,3.0]|[1.0,0.8728715609...|+---+------------------+--------------------+ The real data sets come with various ranges and sometimes it is advisable to transform the data into well-defined buckets before plugging into machine learning algorithms. Bucketizer class is handy to transform the data into various buckets. from pyspark.ml.feature import Bucketizerfrom pyspark.ml.linalg import Vectors# Define the splits for bucketssplits = [-float("inf"), -10, 0.0, 10, float("inf")]b_data = [(-800.0,), (-10.5,), (-1.7,), (0.0,), (8.2,), (90.1,)]b_df = spark.createDataFrame(b_data, ["features"])b_df.show()+--------+|features|+--------+| -800.0|| -10.5|| -1.7|| 0.0|| 8.2|| 90.1|+--------+# Transforming data into bucketsbucketizer = Bucketizer(splits=splits, inputCol= "features", outputCol="bfeatures")bucketed_df = bucketizer.transform(b_df)bucketed_df.show()+--------+---------+|features|bfeatures|+--------+---------+| -800.0| 0.0|| -10.5| 0.0|| -1.7| 1.0|| 0.0| 2.0|| 8.2| 2.0|| 90.1| 3.0|+--------+---------+ Natural Language Processing is one of the main applications of Machine learning. One of the first steps for NLP is tokenizing the text into words or token. We can utilize the Tokenizer class with SparkML to perform this task. from pyspark.ml.feature import Tokenizersentences_df = spark.createDataFrame([ (1, "This is an introduction to sparkMlib"), (2, "Mlib incluse libraries fro classfication and regression"), (3, "It also incluses support for data piple lines"), ], ["id", "sentences"])sentences_df.show()+---+--------------------+| id| sentences|+---+--------------------+| 1|This is an introd...|| 2|Mlib incluse libr...|| 3|It also incluses ...|+---+--------------------+sent_token = Tokenizer(inputCol = "sentences", outputCol = "words")sent_tokenized_df = sent_token.transform(sentences_df)sent_tokenized_df.take(10)[Row(id=1, sentences='This is an introduction to sparkMlib', words=['this', 'is', 'an', 'introduction', 'to', 'sparkmlib']), Row(id=2, sentences='Mlib incluse libraries fro classfication and regression', words=['mlib', 'incluse', 'libraries', 'fro', 'classfication', 'and', 'regression']), Row(id=3, sentences='It also incluses support for data piple lines', words=['it', 'also', 'incluses', 'support', 'for', 'data', 'piple', 'lines'])] Term frequency-inverse document frequency (TF-IDF) is a feature vectorization method widely used in text mining to reflect the importance of a term to a document in the corpus. Using the above-tokenized data, Let us apply the TF-IDF from pyspark.ml.feature import HashingTF, IDFhashingTF = HashingTF(inputCol = "words", outputCol = "rawfeatures", numFeatures = 20)sent_fhTF_df = hashingTF.transform(sent_tokenized_df)sent_fhTF_df.take(1)[Row(id=1, sentences='This is an introduction to sparkMlib', words=['this', 'is', 'an', 'introduction', 'to', 'sparkmlib'], rawfeatures=SparseVector(20, {6: 2.0, 8: 1.0, 9: 1.0, 10: 1.0, 13: 1.0}))]idf = IDF(inputCol = "rawfeatures", outputCol = "idffeatures")idfModel = idf.fit(sent_fhTF_df)tfidf_df = idfModel.transform(sent_fhTF_df)tfidf_df.take(1)[Row(id=1, sentences='This is an introduction to sparkMlib', words=['this', 'is', 'an', 'introduction', 'to', 'sparkmlib'], rawfeatures=SparseVector(20, {6: 2.0, 8: 1.0, 9: 1.0, 10: 1.0, 13: 1.0}), idffeatures=SparseVector(20, {6: 0.5754, 8: 0.6931, 9: 0.0, 10: 0.6931, 13: 0.2877}))] User can play with various transformations depending on the requirements of the problem in-hand. Clustering is a machine learning technique where the data is grouped into a reasonable number of classes using the input features. In this section, we study the basic application of clustering techniques using the spark ML framework. from pyspark.ml.linalg import Vectorsfrom pyspark.ml.feature import VectorAssemblerfrom pyspark.ml.clustering import KMeans, BisectingKMeansimport glob# Downloading the clustering dataset!wget -q 'https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/clustering_dataset.csv' Load the clustering data stored in csv format using spark # Read the data.clustering_file_name ='clustering_dataset.csv'import pandas as pd# df = pd.read_csv(clustering_file_name)cluster_df = spark.read.csv(clustering_file_name, header=True,inferSchema=True) Convert the tabular data into vectorized format using VectorAssembler # Coverting the input data into features columnvectorAssembler = VectorAssembler(inputCols = ['col1', 'col2', 'col3'], outputCol = "features")vcluster_df = vectorAssembler.transform(cluster_df)vcluster_df.show(10)+----+----+----+--------------+|col1|col2|col3| features|+----+----+----+--------------+| 7| 4| 1| [7.0,4.0,1.0]|| 7| 7| 9| [7.0,7.0,9.0]|| 7| 9| 6| [7.0,9.0,6.0]|| 1| 6| 5| [1.0,6.0,5.0]|| 6| 7| 7| [6.0,7.0,7.0]|| 7| 9| 4| [7.0,9.0,4.0]|| 7| 10| 6|[7.0,10.0,6.0]|| 7| 8| 2| [7.0,8.0,2.0]|| 8| 3| 8| [8.0,3.0,8.0]|| 4| 10| 5|[4.0,10.0,5.0]|+----+----+----+--------------+only showing top 10 rows Once the data is prepared into the format MLlib can use for models, now we can define and train the clustering algorithm such as K-Means. We can define the number of clusters and initialize the seed as done below. # Applying the k-means algorithmkmeans = KMeans().setK(3)kmeans = kmeans.setSeed(1)kmodel = kmeans.fit(vcluster_df) After training has been finished, let us print the centers. centers = kmodel.clusterCenters()print("The location of centers: {}".format(centers))The location of centers: [array([35.88461538, 31.46153846, 34.42307692]), array([80. , 79.20833333, 78.29166667]), array([5.12, 5.84, 4.84])] There are various kinds of clustering algorithms implemented in MLlib. Bisecting K-Means Clustering is another popular method. # Applying Hierarchical Clusteringbkmeans = BisectingKMeans().setK(3)bkmeans = bkmeans.setSeed(1)bkmodel = bkmeans.fit(vcluster_df)bkcneters = bkmodel.clusterCenters()bkcneters[array([5.12, 5.84, 4.84]), array([35.88461538, 31.46153846, 34.42307692]), array([80. , 79.20833333, 78.29166667])] To read more about the clustering methods implemented in MLlib, follow the below link. spark.apache.org Classification is one of the widely used Machine algorithms and almost every data engineer and data scientist must know about these algorithms. Once the data is loaded and prepared, I will demonstrate three classification algorithms. NaiveBayes ClassificationMulti-Layer Perceptron ClassificationDecision Trees Classification NaiveBayes Classification Multi-Layer Perceptron Classification Decision Trees Classification We explore the supervised classification algorithms using IRIS data. I have uploaded the data into my GitHub to reproduce the results. Users can download the data using the below command. # Downloading the clustering data!wget -q "https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/iris.csv"df = pd.read_csv("https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/iris.csv", header=None)df.head() spark.createDataFrame(df, columns)DataFrame[c_0: double, c_1: double, c_2: double, c_3: double, c4 : string] In this section, we will be using the IRIS data to understand the classification. To perform ML models, we apply the preprocessing step on our input data. from pyspark.sql.functions import *from pyspark.ml.feature import VectorAssemblerfrom pyspark.ml.feature import StringIndexer# Read the iris datadf_iris = pd.read_csv("https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/iris.csv", header=None)iris_df = spark.createDataFrame(df_iris)iris_df.show(5, False)+------------+-----------+------------+-----------+-----------+|sepal_length|sepal_width|petal_length|petal_width|species |+------------+-----------+------------+-----------+-----------+|5.1 |3.5 |1.4 |0.2 |Iris-setosa||4.9 |3.0 |1.4 |0.2 |Iris-setosa||4.7 |3.2 |1.3 |0.2 |Iris-setosa||4.6 |3.1 |1.5 |0.2 |Iris-setosa||5.0 |3.6 |1.4 |0.2 |Iris-setosa|+------------+-----------+------------+-----------+-----------+only showing top 5 rows# Rename the columnsiris_df = iris_df.select(col("0").alias("sepal_length"), col("1").alias("sepal_width"), col("2").alias("petal_length"), col("3").alias("petal_width"), col("4").alias("species"), )# Converting the columns into featuresvectorAssembler = VectorAssembler(inputCols = ["sepal_length", "sepal_width", "petal_length", "petal_width"], outputCol = "features")viris_df = vectorAssembler.transform(iris_df)viris_df.show(5, False)+------------+-----------+------------+-----------+-----------+-----------------+|sepal_length|sepal_width|petal_length|petal_width|species |features |+------------+-----------+------------+-----------+-----------+-----------------+|5.1 |3.5 |1.4 |0.2 |Iris-setosa|[5.1,3.5,1.4,0.2]||4.9 |3.0 |1.4 |0.2 |Iris-setosa|[4.9,3.0,1.4,0.2]||4.7 |3.2 |1.3 |0.2 |Iris-setosa|[4.7,3.2,1.3,0.2]||4.6 |3.1 |1.5 |0.2 |Iris-setosa|[4.6,3.1,1.5,0.2]||5.0 |3.6 |1.4 |0.2 |Iris-setosa|[5.0,3.6,1.4,0.2]|+------------+-----------+------------+-----------+-----------+-----------------+only showing top 5 rowsindexer = StringIndexer(inputCol="species", outputCol = "label")iviris_df = indexer.fit(viris_df).transform(viris_df)iviris_df.show(2, False)+------------+-----------+------------+-----------+-----------+-----------------+-----+|sepal_length|sepal_width|petal_length|petal_width|species |features |label|+------------+-----------+------------+-----------+-----------+-----------------+-----+|5.1 |3.5 |1.4 |0.2 |Iris-setosa|[5.1,3.5,1.4,0.2]|0.0 ||4.9 |3.0 |1.4 |0.2 |Iris-setosa|[4.9,3.0,1.4,0.2]|0.0 |+------------+-----------+------------+-----------+-----------+-----------------+-----+only showing top 2 rows Once the data is prepared, we are ready to apply the first classification algorithm. from pyspark.ml.classification import NaiveBayesfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator# Create the traing and test splitssplits = iviris_df.randomSplit([0.6,0.4], 1)train_df = splits[0]test_df = splits[1]# Apply the Naive bayes classifiernb = NaiveBayes(modelType="multinomial")nbmodel = nb.fit(train_df)predictions_df = nbmodel.transform(test_df)predictions_df.show(1, False)+------------+-----------+------------+-----------+-----------+-----------------+-----+------------------------------------------------------------+------------------------------------------------------------+----------+|sepal_length|sepal_width|petal_length|petal_width|species |features |label|rawPrediction |probability |prediction|+------------+-----------+------------+-----------+-----------+-----------------+-----+------------------------------------------------------------+------------------------------------------------------------+----------+|4.3 |3.0 |1.1 |0.1 |Iris-setosa|[4.3,3.0,1.1,0.1]|0.0 |[-9.966434726497221,-11.294595492758821,-11.956012812323921]|[0.7134106367667451,0.18902823898426235,0.09756112424899269]|0.0 |+------------+-----------+------------+-----------+-----------+-----------------+-----+------------------------------------------------------------+------------------------------------------------------------+----------+only showing top 1 row Let us Evaluate the trained classifier evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")nbaccuracy = evaluator.evaluate(predictions_df)nbaccuracy0.8275862068965517 The second classifier we will be investigating is a Multi-layer perceptron. In this tutorial, I am not going into details of the optimal MLP network for this problem however in practice, you research the optimal network suitable to the problem in hand. from pyspark.ml.classification import MultilayerPerceptronClassifier# Define the MLP Classifierlayers = [4,5,5,3]mlp = MultilayerPerceptronClassifier(layers = layers, seed=1)mlp_model = mlp.fit(train_df)mlp_predictions = mlp_model.transform(test_df)# Evaluate the MLP classifiermlp_evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")mlp_accuracy = mlp_evaluator.evaluate(mlp_predictions)mlp_accuracy0.9827586206896551 Another common classifier in the ML family is the Decision Tree Classifier, in this section, we explore this classifier. from pyspark.ml.classification import DecisionTreeClassifier# Define the DT Classifier dt = DecisionTreeClassifier(labelCol="label", featuresCol="features")dt_model = dt.fit(train_df)dt_predictions = dt_model.transform(test_df)# Evaluate the DT Classifierdt_evaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")dt_accuracy = dt_evaluator.evaluate(dt_predictions)dt_accuracy0.9827586206896551 Apart from the above three demonstrated classification algorithms, Spark MLlib has also many other implementations of classification algorithms. Details of the implemented classification algorithms can be found at below link spark.apache.org It is highly recommended to try some of the classification algorithms to get hands-on. In this section, we explore the Machine learning models for regression problems using pyspark. Regression models are helpful in predicting future values using past data. We will use the Combined Cycle Power Plant data set to predict the net hourly electrical output (EP). I have uploaded the data to my GitHub so that users can reproduce the results. from pyspark.ml.regression import LinearRegressionfrom pyspark.ml.feature import VectorAssembler# Read the iris datadf_ccpp = pd.read_csv("https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/ccpp.csv")pp_df = spark.createDataFrame(df_ccpp)pp_df.show(2, False)+-----+-----+-------+-----+------+|AT |V |AP |RH |PE |+-----+-----+-------+-----+------+|14.96|41.76|1024.07|73.17|463.26||25.18|62.96|1020.04|59.08|444.37|+-----+-----+-------+-----+------+only showing top 2 rows# Create the feature column using VectorAssembler classvectorAssembler = VectorAssembler(inputCols =["AT", "V", "AP", "RH"], outputCol = "features")vpp_df = vectorAssembler.transform(pp_df)vpp_df.show(2, False)+-----+-----+-------+-----+------+---------------------------+|AT |V |AP |RH |PE |features |+-----+-----+-------+-----+------+---------------------------+|14.96|41.76|1024.07|73.17|463.26|[14.96,41.76,1024.07,73.17]||25.18|62.96|1020.04|59.08|444.37|[25.18,62.96,1020.04,59.08]|+-----+-----+-------+-----+------+---------------------------+only showing top 2 rows We start with the simplest regression technique i.e. Linear Regression. # Define and fit Linear Regressionlr = LinearRegression(featuresCol="features", labelCol="PE")lr_model = lr.fit(vpp_df)# Print and save the Model outputlr_model.coefficientslr_model.interceptlr_model.summary.rootMeanSquaredError4.557126016749486#lr_model.save() In this section, we explore the Decision Tree Regression commonly used in Machine learning. from pyspark.ml.regression import DecisionTreeRegressorfrom pyspark.ml.evaluation import RegressionEvaluatorvpp_df.show(2, False)+-----+-----+-------+-----+------+---------------------------+|AT |V |AP |RH |PE |features |+-----+-----+-------+-----+------+---------------------------+|14.96|41.76|1024.07|73.17|463.26|[14.96,41.76,1024.07,73.17]||25.18|62.96|1020.04|59.08|444.37|[25.18,62.96,1020.04,59.08]|+-----+-----+-------+-----+------+---------------------------+only showing top 2 rows# Define train and test data splitsplits = vpp_df.randomSplit([0.7,0.3])train_df = splits[0]test_df = splits[1]# Define the Decision Tree Model dt = DecisionTreeRegressor(featuresCol="features", labelCol="PE")dt_model = dt.fit(train_df)dt_predictions = dt_model.transform(test_df)dt_predictions.show(1, False)+----+-----+-------+-----+------+--------------------------+-----------------+|AT |V |AP |RH |PE |features |prediction |+----+-----+-------+-----+------+--------------------------+-----------------+|3.31|39.42|1024.05|84.31|487.19|[3.31,39.42,1024.05,84.31]|486.1117703349283|+----+-----+-------+-----+------+--------------------------+-----------------+only showing top 1 row# Evaluate the Modeldt_evaluator = RegressionEvaluator(labelCol="PE", predictionCol="prediction", metricName="rmse")dt_rmse = dt_evaluator.evaluate(dt_predictions)print("The RMSE of Decision Tree regression Model is {}".format(dt_rmse))The RMSE of Decision Tree regression Model is 4.451790078736588 Gradient Boosting is another common choice among ML professionals. Let us try the GBM in this section. from pyspark.ml.regression import GBTRegressor# Define the GBT Modelgbt = GBTRegressor(featuresCol="features", labelCol="PE")gbt_model = gbt.fit(train_df)gbt_predictions = gbt_model.transform(test_df)# Evaluate the GBT Modelgbt_evaluator = RegressionEvaluator(labelCol="PE", predictionCol="prediction", metricName="rmse")gbt_rmse = gbt_evaluator.evaluate(gbt_predictions)print("The RMSE of GBT Tree regression Model is {}".format(gbt_rmse))The RMSE of GBT Tree regression Model is 4.035802933864555 Apart from the above-demonstrated regression algorithms, Spark MLlib has also many other implementations of regression algorithms. Details of the implemented regression algorithms can be found at the below link. spark.apache.org It is highly recommended to try some of the regression algorithms to get hands-on and play with the parameters. In this tutorial, I have tried to give the readers an opportunity to learn and implement basic Machine Learning algorithms using PySpark. Spark not only provide the benefit of distributed processing but also can handle a large amount of data to be processing. To summarise, we have covered below topics/algorithms Setting up the Spark 3.0.1 in Google Colab Overview of Data Transformations using PySpark Clustering algorithms using PySpark Classification problems using PySpark Regression Problems using PySpark
[ { "code": null, "e": 460, "s": 172, "text": "This is a comprehensive tutorial on using the Spark distributed machine learning framework to build a scalable ML data pipeline. I will cover the basic machine learning algorithms implemented in Spark MLlib library and through this tutorial, I will use the PySpark in python environment." }, { "code": null, "e": 931, "s": 460, "text": "Machine learning is getting popular in solving real-world problems in almost every business domain. It helps solve the problems using the data which is often unstructured, noisy, and in huge size. With the increase in data sizes and various sources of data, solving machine learning problems using standard techniques pose a big challenge. Spark is a distributed processing engine using the MapReduce framework to solve problems related to big data and processing of it." }, { "code": null, "e": 1190, "s": 931, "text": "Spark framework has its own machine learning module called MLlib. In this article, I will use pyspark and spark MLlib to demonstrate the use of machine learning using distributed processing. Readers will be able to learn the below concept with real examples." }, { "code": null, "e": 1234, "s": 1190, "text": "Setting up Spark in the Google Colaboratory" }, { "code": null, "e": 1266, "s": 1234, "text": "Machine Learning Basic Concepts" }, { "code": null, "e": 1316, "s": 1266, "text": "Preprocessing and Data Transformation using Spark" }, { "code": null, "e": 1346, "s": 1316, "text": "Spark Clustering with pyspark" }, { "code": null, "e": 1374, "s": 1346, "text": "Classification with pyspark" }, { "code": null, "e": 1406, "s": 1374, "text": "Regression methods with pyspark" }, { "code": null, "e": 1481, "s": 1406, "text": "A working google colab notebook will be provided to reproduce the results." }, { "code": null, "e": 1777, "s": 1481, "text": "Since this article is a hands-on tutorial covering the transformations, classification, clustering, and regression using pyspark in one session, the length of the article is longer than my previous articles. One benefit is that you can go through the basic concepts and implementation in one go." }, { "code": null, "e": 1833, "s": 1777, "text": "According to Apache Spark and Delta Lake Under the Hood" }, { "code": null, "e": 2490, "s": 1833, "text": "Apache Spark is a unified computing engine and a set of libraries for parallel data processing on computer clusters. As of the time this writing, Spark is the most actively developed open source engine for this task; making it the de facto tool for any developer or data scientist interested in big data. Spark supports multiple widely used programming languages (Python, Java, Scala and R), includes libraries for diverse tasks ranging from SQL to streaming and machine learning, and runs anywhere from a laptop to a cluster of thousands of servers. This makes it an easy system to start with and scale up to big data processing or incredibly large scale." }, { "code": null, "e": 2665, "s": 2490, "text": "As a first step, I configure the google colab runtime with spark installation. For details, readers may read my article Getting Started Spark 3.0.0 in Google Colab om medium." }, { "code": null, "e": 2700, "s": 2665, "text": "We will install the below programs" }, { "code": null, "e": 2707, "s": 2700, "text": "Java 8" }, { "code": null, "e": 2719, "s": 2707, "text": "spark-3.0.1" }, { "code": null, "e": 2729, "s": 2719, "text": "Hadoop3.2" }, { "code": null, "e": 2739, "s": 2729, "text": "Findspark" }, { "code": null, "e": 2816, "s": 2739, "text": "you can install the LATEST version of Spark using the below set of commands." }, { "code": null, "e": 3035, "s": 2816, "text": "# Run below commands!apt-get install openjdk-8-jdk-headless -qq > /dev/null!wget -q http://apache.osuosl.org/spark/spark-3.0.1/spark-3.0.1-bin-hadoop3.2.tgz!tar xf spark-3.0.1-bin-hadoop3.2.tgz!pip install -q findspark" }, { "code": null, "e": 3138, "s": 3035, "text": "After installing the spark and Java, set the environment variables where Spark and Java are installed." }, { "code": null, "e": 3272, "s": 3138, "text": "import osos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"os.environ[\"SPARK_HOME\"] = \"/content/spark-3.0.1-bin-hadoop3.2\"" }, { "code": null, "e": 3343, "s": 3272, "text": "Let us test the installation of spark in our google colab environment." }, { "code": null, "e": 3944, "s": 3343, "text": "import findsparkfindspark.init()from pyspark.sql import SparkSessionspark = SparkSession.builder.master(\"local[*]\").getOrCreate()# Test the spark df = spark.createDataFrame([{\"hello\": \"world\"} for x in range(1000)])df.show(3, False)/content/spark-3.0.1-bin-hadoop3.2/python/pyspark/sql/session.py:381: UserWarning: inferring schema from dict is deprecated,please use pyspark.sql.Row instead warnings.warn(\"inferring schema from dict is deprecated,\"+-----+|hello|+-----+|world||world||world|+-----+only showing top 3 rows# make sure the version of pysparkimport pysparkprint(pyspark.__version__)3.0.1" }, { "code": null, "e": 4408, "s": 3944, "text": "Once, we have set up the spark in google colab and made sure it is running with the correct version i.e. 3.0.1 in this case, we can start exploring the machine learning API developed on top of Spark. PySpark is a higher level Python API to use spark with python. For this tutorial, I assume the readers have a basic understanding of Machine Learning and SK-Learn for model building and training. Spark MLlib used the same fit and predict structure as in SK-Learn." }, { "code": null, "e": 4509, "s": 4408, "text": "In order to reproduce the results, I have uploaded the data to my GitHub and can be accessed easily." }, { "code": null, "e": 4567, "s": 4509, "text": "Learn by Doing: Use the colab notebook to run it yourself" }, { "code": null, "e": 4880, "s": 4567, "text": "This section covers the basic steps involved in transformations of input feature data into the format Machine Learning algorithms accept. We will be covering the transformations coming with the SparkML library. To understand or read more about the available spark transformations in 3.0.3, follow the below link." }, { "code": null, "e": 4897, "s": 4880, "text": "spark.apache.org" }, { "code": null, "e": 5023, "s": 4897, "text": "MinMaxScaler is one of the favorite classes shipped with most machine learning libraries. It scaled the data between 0 and 1." }, { "code": null, "e": 6049, "s": 5023, "text": "from pyspark.ml.feature import MinMaxScalerfrom pyspark.ml.linalg import Vectors# Create some dummy feature datafeatures_df = spark.createDataFrame([ (1, Vectors.dense([10.0,10000.0,1.0]),), (2, Vectors.dense([20.0,30000.0,2.0]),), (3, Vectors.dense([30.0,40000.0,3.0]),), ],[\"id\", \"features\"] )features_df.show()+---+------------------+| id| features|+---+------------------+| 1|[10.0,10000.0,1.0]|| 2|[20.0,30000.0,2.0]|| 3|[30.0,40000.0,3.0]|+---+------------------+# Apply MinMaxScaler transformationfeatures_scaler = MinMaxScaler(inputCol = \"features\", outputCol = \"sfeatures\")smodel = features_scaler.fit(features_df)sfeatures_df = smodel.transform(features_df)sfeatures_df.show()+---+------------------+--------------------+| id| features| sfeatures|+---+------------------+--------------------+| 1|[10.0,10000.0,1.0]| (3,[],[])|| 2|[20.0,30000.0,2.0]|[0.5,0.6666666666...|| 3|[30.0,40000.0,3.0]| [1.0,1.0,1.0]|+---+------------------+--------------------+" }, { "code": null, "e": 6270, "s": 6049, "text": "StandardScaler is another well-known class written with machine learning libraries. It normalizes the data between -1 and 1 and converts the data into bell-shaped data. You can demean the data and scale to some variance." }, { "code": null, "e": 7158, "s": 6270, "text": "from pyspark.ml.feature import StandardScalerfrom pyspark.ml.linalg import Vectors# Create the dummy datafeatures_df = spark.createDataFrame([ (1, Vectors.dense([10.0,10000.0,1.0]),), (2, Vectors.dense([20.0,30000.0,2.0]),), (3, Vectors.dense([30.0,40000.0,3.0]),), ],[\"id\", \"features\"] )# Apply the StandardScaler modelfeatures_stand_scaler = StandardScaler(inputCol = \"features\", outputCol = \"sfeatures\", withStd=True, withMean=True)stmodel = features_stand_scaler.fit(features_df)stand_sfeatures_df = stmodel.transform(features_df)stand_sfeatures_df.show()+---+------------------+--------------------+| id| features| sfeatures|+---+------------------+--------------------+| 1|[10.0,10000.0,1.0]|[-1.0,-1.09108945...|| 2|[20.0,30000.0,2.0]|[0.0,0.2182178902...|| 3|[30.0,40000.0,3.0]|[1.0,0.8728715609...|+---+------------------+--------------------+" }, { "code": null, "e": 7330, "s": 7158, "text": "The real data sets come with various ranges and sometimes it is advisable to transform the data into well-defined buckets before plugging into machine learning algorithms." }, { "code": null, "e": 7400, "s": 7330, "text": "Bucketizer class is handy to transform the data into various buckets." }, { "code": null, "e": 8161, "s": 7400, "text": "from pyspark.ml.feature import Bucketizerfrom pyspark.ml.linalg import Vectors# Define the splits for bucketssplits = [-float(\"inf\"), -10, 0.0, 10, float(\"inf\")]b_data = [(-800.0,), (-10.5,), (-1.7,), (0.0,), (8.2,), (90.1,)]b_df = spark.createDataFrame(b_data, [\"features\"])b_df.show()+--------+|features|+--------+| -800.0|| -10.5|| -1.7|| 0.0|| 8.2|| 90.1|+--------+# Transforming data into bucketsbucketizer = Bucketizer(splits=splits, inputCol= \"features\", outputCol=\"bfeatures\")bucketed_df = bucketizer.transform(b_df)bucketed_df.show()+--------+---------+|features|bfeatures|+--------+---------+| -800.0| 0.0|| -10.5| 0.0|| -1.7| 1.0|| 0.0| 2.0|| 8.2| 2.0|| 90.1| 3.0|+--------+---------+" }, { "code": null, "e": 8387, "s": 8161, "text": "Natural Language Processing is one of the main applications of Machine learning. One of the first steps for NLP is tokenizing the text into words or token. We can utilize the Tokenizer class with SparkML to perform this task." }, { "code": null, "e": 9451, "s": 8387, "text": "from pyspark.ml.feature import Tokenizersentences_df = spark.createDataFrame([ (1, \"This is an introduction to sparkMlib\"), (2, \"Mlib incluse libraries fro classfication and regression\"), (3, \"It also incluses support for data piple lines\"), ], [\"id\", \"sentences\"])sentences_df.show()+---+--------------------+| id| sentences|+---+--------------------+| 1|This is an introd...|| 2|Mlib incluse libr...|| 3|It also incluses ...|+---+--------------------+sent_token = Tokenizer(inputCol = \"sentences\", outputCol = \"words\")sent_tokenized_df = sent_token.transform(sentences_df)sent_tokenized_df.take(10)[Row(id=1, sentences='This is an introduction to sparkMlib', words=['this', 'is', 'an', 'introduction', 'to', 'sparkmlib']), Row(id=2, sentences='Mlib incluse libraries fro classfication and regression', words=['mlib', 'incluse', 'libraries', 'fro', 'classfication', 'and', 'regression']), Row(id=3, sentences='It also incluses support for data piple lines', words=['it', 'also', 'incluses', 'support', 'for', 'data', 'piple', 'lines'])]" }, { "code": null, "e": 9684, "s": 9451, "text": "Term frequency-inverse document frequency (TF-IDF) is a feature vectorization method widely used in text mining to reflect the importance of a term to a document in the corpus. Using the above-tokenized data, Let us apply the TF-IDF" }, { "code": null, "e": 10524, "s": 9684, "text": "from pyspark.ml.feature import HashingTF, IDFhashingTF = HashingTF(inputCol = \"words\", outputCol = \"rawfeatures\", numFeatures = 20)sent_fhTF_df = hashingTF.transform(sent_tokenized_df)sent_fhTF_df.take(1)[Row(id=1, sentences='This is an introduction to sparkMlib', words=['this', 'is', 'an', 'introduction', 'to', 'sparkmlib'], rawfeatures=SparseVector(20, {6: 2.0, 8: 1.0, 9: 1.0, 10: 1.0, 13: 1.0}))]idf = IDF(inputCol = \"rawfeatures\", outputCol = \"idffeatures\")idfModel = idf.fit(sent_fhTF_df)tfidf_df = idfModel.transform(sent_fhTF_df)tfidf_df.take(1)[Row(id=1, sentences='This is an introduction to sparkMlib', words=['this', 'is', 'an', 'introduction', 'to', 'sparkmlib'], rawfeatures=SparseVector(20, {6: 2.0, 8: 1.0, 9: 1.0, 10: 1.0, 13: 1.0}), idffeatures=SparseVector(20, {6: 0.5754, 8: 0.6931, 9: 0.0, 10: 0.6931, 13: 0.2877}))]" }, { "code": null, "e": 10621, "s": 10524, "text": "User can play with various transformations depending on the requirements of the problem in-hand." }, { "code": null, "e": 10855, "s": 10621, "text": "Clustering is a machine learning technique where the data is grouped into a reasonable number of classes using the input features. In this section, we study the basic application of clustering techniques using the spark ML framework." }, { "code": null, "e": 11147, "s": 10855, "text": "from pyspark.ml.linalg import Vectorsfrom pyspark.ml.feature import VectorAssemblerfrom pyspark.ml.clustering import KMeans, BisectingKMeansimport glob# Downloading the clustering dataset!wget -q 'https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/clustering_dataset.csv'" }, { "code": null, "e": 11205, "s": 11147, "text": "Load the clustering data stored in csv format using spark" }, { "code": null, "e": 11406, "s": 11205, "text": "# Read the data.clustering_file_name ='clustering_dataset.csv'import pandas as pd# df = pd.read_csv(clustering_file_name)cluster_df = spark.read.csv(clustering_file_name, header=True,inferSchema=True)" }, { "code": null, "e": 11476, "s": 11406, "text": "Convert the tabular data into vectorized format using VectorAssembler" }, { "code": null, "e": 12148, "s": 11476, "text": "# Coverting the input data into features columnvectorAssembler = VectorAssembler(inputCols = ['col1', 'col2', 'col3'], outputCol = \"features\")vcluster_df = vectorAssembler.transform(cluster_df)vcluster_df.show(10)+----+----+----+--------------+|col1|col2|col3| features|+----+----+----+--------------+| 7| 4| 1| [7.0,4.0,1.0]|| 7| 7| 9| [7.0,7.0,9.0]|| 7| 9| 6| [7.0,9.0,6.0]|| 1| 6| 5| [1.0,6.0,5.0]|| 6| 7| 7| [6.0,7.0,7.0]|| 7| 9| 4| [7.0,9.0,4.0]|| 7| 10| 6|[7.0,10.0,6.0]|| 7| 8| 2| [7.0,8.0,2.0]|| 8| 3| 8| [8.0,3.0,8.0]|| 4| 10| 5|[4.0,10.0,5.0]|+----+----+----+--------------+only showing top 10 rows" }, { "code": null, "e": 12362, "s": 12148, "text": "Once the data is prepared into the format MLlib can use for models, now we can define and train the clustering algorithm such as K-Means. We can define the number of clusters and initialize the seed as done below." }, { "code": null, "e": 12478, "s": 12362, "text": "# Applying the k-means algorithmkmeans = KMeans().setK(3)kmeans = kmeans.setSeed(1)kmodel = kmeans.fit(vcluster_df)" }, { "code": null, "e": 12538, "s": 12478, "text": "After training has been finished, let us print the centers." }, { "code": null, "e": 12772, "s": 12538, "text": "centers = kmodel.clusterCenters()print(\"The location of centers: {}\".format(centers))The location of centers: [array([35.88461538, 31.46153846, 34.42307692]), array([80. , 79.20833333, 78.29166667]), array([5.12, 5.84, 4.84])]" }, { "code": null, "e": 12899, "s": 12772, "text": "There are various kinds of clustering algorithms implemented in MLlib. Bisecting K-Means Clustering is another popular method." }, { "code": null, "e": 13199, "s": 12899, "text": "# Applying Hierarchical Clusteringbkmeans = BisectingKMeans().setK(3)bkmeans = bkmeans.setSeed(1)bkmodel = bkmeans.fit(vcluster_df)bkcneters = bkmodel.clusterCenters()bkcneters[array([5.12, 5.84, 4.84]), array([35.88461538, 31.46153846, 34.42307692]), array([80. , 79.20833333, 78.29166667])]" }, { "code": null, "e": 13286, "s": 13199, "text": "To read more about the clustering methods implemented in MLlib, follow the below link." }, { "code": null, "e": 13303, "s": 13286, "text": "spark.apache.org" }, { "code": null, "e": 13537, "s": 13303, "text": "Classification is one of the widely used Machine algorithms and almost every data engineer and data scientist must know about these algorithms. Once the data is loaded and prepared, I will demonstrate three classification algorithms." }, { "code": null, "e": 13629, "s": 13537, "text": "NaiveBayes ClassificationMulti-Layer Perceptron ClassificationDecision Trees Classification" }, { "code": null, "e": 13655, "s": 13629, "text": "NaiveBayes Classification" }, { "code": null, "e": 13693, "s": 13655, "text": "Multi-Layer Perceptron Classification" }, { "code": null, "e": 13723, "s": 13693, "text": "Decision Trees Classification" }, { "code": null, "e": 13911, "s": 13723, "text": "We explore the supervised classification algorithms using IRIS data. I have uploaded the data into my GitHub to reproduce the results. Users can download the data using the below command." }, { "code": null, "e": 14156, "s": 13911, "text": "# Downloading the clustering data!wget -q \"https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/iris.csv\"df = pd.read_csv(\"https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/iris.csv\", header=None)df.head()" }, { "code": null, "e": 14265, "s": 14156, "text": "spark.createDataFrame(df, columns)DataFrame[c_0: double, c_1: double, c_2: double, c_3: double, c4 : string]" }, { "code": null, "e": 14420, "s": 14265, "text": "In this section, we will be using the IRIS data to understand the classification. To perform ML models, we apply the preprocessing step on our input data." }, { "code": null, "e": 17364, "s": 14420, "text": "from pyspark.sql.functions import *from pyspark.ml.feature import VectorAssemblerfrom pyspark.ml.feature import StringIndexer# Read the iris datadf_iris = pd.read_csv(\"https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/iris.csv\", header=None)iris_df = spark.createDataFrame(df_iris)iris_df.show(5, False)+------------+-----------+------------+-----------+-----------+|sepal_length|sepal_width|petal_length|petal_width|species |+------------+-----------+------------+-----------+-----------+|5.1 |3.5 |1.4 |0.2 |Iris-setosa||4.9 |3.0 |1.4 |0.2 |Iris-setosa||4.7 |3.2 |1.3 |0.2 |Iris-setosa||4.6 |3.1 |1.5 |0.2 |Iris-setosa||5.0 |3.6 |1.4 |0.2 |Iris-setosa|+------------+-----------+------------+-----------+-----------+only showing top 5 rows# Rename the columnsiris_df = iris_df.select(col(\"0\").alias(\"sepal_length\"), col(\"1\").alias(\"sepal_width\"), col(\"2\").alias(\"petal_length\"), col(\"3\").alias(\"petal_width\"), col(\"4\").alias(\"species\"), )# Converting the columns into featuresvectorAssembler = VectorAssembler(inputCols = [\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"], outputCol = \"features\")viris_df = vectorAssembler.transform(iris_df)viris_df.show(5, False)+------------+-----------+------------+-----------+-----------+-----------------+|sepal_length|sepal_width|petal_length|petal_width|species |features |+------------+-----------+------------+-----------+-----------+-----------------+|5.1 |3.5 |1.4 |0.2 |Iris-setosa|[5.1,3.5,1.4,0.2]||4.9 |3.0 |1.4 |0.2 |Iris-setosa|[4.9,3.0,1.4,0.2]||4.7 |3.2 |1.3 |0.2 |Iris-setosa|[4.7,3.2,1.3,0.2]||4.6 |3.1 |1.5 |0.2 |Iris-setosa|[4.6,3.1,1.5,0.2]||5.0 |3.6 |1.4 |0.2 |Iris-setosa|[5.0,3.6,1.4,0.2]|+------------+-----------+------------+-----------+-----------+-----------------+only showing top 5 rowsindexer = StringIndexer(inputCol=\"species\", outputCol = \"label\")iviris_df = indexer.fit(viris_df).transform(viris_df)iviris_df.show(2, False)+------------+-----------+------------+-----------+-----------+-----------------+-----+|sepal_length|sepal_width|petal_length|petal_width|species |features |label|+------------+-----------+------------+-----------+-----------+-----------------+-----+|5.1 |3.5 |1.4 |0.2 |Iris-setosa|[5.1,3.5,1.4,0.2]|0.0 ||4.9 |3.0 |1.4 |0.2 |Iris-setosa|[4.9,3.0,1.4,0.2]|0.0 |+------------+-----------+------------+-----------+-----------+-----------------+-----+only showing top 2 rows" }, { "code": null, "e": 17449, "s": 17364, "text": "Once the data is prepared, we are ready to apply the first classification algorithm." }, { "code": null, "e": 18977, "s": 17449, "text": "from pyspark.ml.classification import NaiveBayesfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator# Create the traing and test splitssplits = iviris_df.randomSplit([0.6,0.4], 1)train_df = splits[0]test_df = splits[1]# Apply the Naive bayes classifiernb = NaiveBayes(modelType=\"multinomial\")nbmodel = nb.fit(train_df)predictions_df = nbmodel.transform(test_df)predictions_df.show(1, False)+------------+-----------+------------+-----------+-----------+-----------------+-----+------------------------------------------------------------+------------------------------------------------------------+----------+|sepal_length|sepal_width|petal_length|petal_width|species |features |label|rawPrediction |probability |prediction|+------------+-----------+------------+-----------+-----------+-----------------+-----+------------------------------------------------------------+------------------------------------------------------------+----------+|4.3 |3.0 |1.1 |0.1 |Iris-setosa|[4.3,3.0,1.1,0.1]|0.0 |[-9.966434726497221,-11.294595492758821,-11.956012812323921]|[0.7134106367667451,0.18902823898426235,0.09756112424899269]|0.0 |+------------+-----------+------------+-----------+-----------+-----------------+-----+------------------------------------------------------------+------------------------------------------------------------+----------+only showing top 1 row" }, { "code": null, "e": 19016, "s": 18977, "text": "Let us Evaluate the trained classifier" }, { "code": null, "e": 19206, "s": 19016, "text": "evaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")nbaccuracy = evaluator.evaluate(predictions_df)nbaccuracy0.8275862068965517" }, { "code": null, "e": 19459, "s": 19206, "text": "The second classifier we will be investigating is a Multi-layer perceptron. In this tutorial, I am not going into details of the optimal MLP network for this problem however in practice, you research the optimal network suitable to the problem in hand." }, { "code": null, "e": 19940, "s": 19459, "text": "from pyspark.ml.classification import MultilayerPerceptronClassifier# Define the MLP Classifierlayers = [4,5,5,3]mlp = MultilayerPerceptronClassifier(layers = layers, seed=1)mlp_model = mlp.fit(train_df)mlp_predictions = mlp_model.transform(test_df)# Evaluate the MLP classifiermlp_evaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")mlp_accuracy = mlp_evaluator.evaluate(mlp_predictions)mlp_accuracy0.9827586206896551" }, { "code": null, "e": 20061, "s": 19940, "text": "Another common classifier in the ML family is the Decision Tree Classifier, in this section, we explore this classifier." }, { "code": null, "e": 20514, "s": 20061, "text": "from pyspark.ml.classification import DecisionTreeClassifier# Define the DT Classifier dt = DecisionTreeClassifier(labelCol=\"label\", featuresCol=\"features\")dt_model = dt.fit(train_df)dt_predictions = dt_model.transform(test_df)# Evaluate the DT Classifierdt_evaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")dt_accuracy = dt_evaluator.evaluate(dt_predictions)dt_accuracy0.9827586206896551" }, { "code": null, "e": 20739, "s": 20514, "text": "Apart from the above three demonstrated classification algorithms, Spark MLlib has also many other implementations of classification algorithms. Details of the implemented classification algorithms can be found at below link" }, { "code": null, "e": 20756, "s": 20739, "text": "spark.apache.org" }, { "code": null, "e": 20843, "s": 20756, "text": "It is highly recommended to try some of the classification algorithms to get hands-on." }, { "code": null, "e": 21013, "s": 20843, "text": "In this section, we explore the Machine learning models for regression problems using pyspark. Regression models are helpful in predicting future values using past data." }, { "code": null, "e": 21194, "s": 21013, "text": "We will use the Combined Cycle Power Plant data set to predict the net hourly electrical output (EP). I have uploaded the data to my GitHub so that users can reproduce the results." }, { "code": null, "e": 22305, "s": 21194, "text": "from pyspark.ml.regression import LinearRegressionfrom pyspark.ml.feature import VectorAssembler# Read the iris datadf_ccpp = pd.read_csv(\"https://raw.githubusercontent.com/amjadraza/blogs-data/master/spark_ml/ccpp.csv\")pp_df = spark.createDataFrame(df_ccpp)pp_df.show(2, False)+-----+-----+-------+-----+------+|AT |V |AP |RH |PE |+-----+-----+-------+-----+------+|14.96|41.76|1024.07|73.17|463.26||25.18|62.96|1020.04|59.08|444.37|+-----+-----+-------+-----+------+only showing top 2 rows# Create the feature column using VectorAssembler classvectorAssembler = VectorAssembler(inputCols =[\"AT\", \"V\", \"AP\", \"RH\"], outputCol = \"features\")vpp_df = vectorAssembler.transform(pp_df)vpp_df.show(2, False)+-----+-----+-------+-----+------+---------------------------+|AT |V |AP |RH |PE |features |+-----+-----+-------+-----+------+---------------------------+|14.96|41.76|1024.07|73.17|463.26|[14.96,41.76,1024.07,73.17]||25.18|62.96|1020.04|59.08|444.37|[25.18,62.96,1020.04,59.08]|+-----+-----+-------+-----+------+---------------------------+only showing top 2 rows" }, { "code": null, "e": 22377, "s": 22305, "text": "We start with the simplest regression technique i.e. Linear Regression." }, { "code": null, "e": 22639, "s": 22377, "text": "# Define and fit Linear Regressionlr = LinearRegression(featuresCol=\"features\", labelCol=\"PE\")lr_model = lr.fit(vpp_df)# Print and save the Model outputlr_model.coefficientslr_model.interceptlr_model.summary.rootMeanSquaredError4.557126016749486#lr_model.save()" }, { "code": null, "e": 22731, "s": 22639, "text": "In this section, we explore the Decision Tree Regression commonly used in Machine learning." }, { "code": null, "e": 24276, "s": 22731, "text": "from pyspark.ml.regression import DecisionTreeRegressorfrom pyspark.ml.evaluation import RegressionEvaluatorvpp_df.show(2, False)+-----+-----+-------+-----+------+---------------------------+|AT |V |AP |RH |PE |features |+-----+-----+-------+-----+------+---------------------------+|14.96|41.76|1024.07|73.17|463.26|[14.96,41.76,1024.07,73.17]||25.18|62.96|1020.04|59.08|444.37|[25.18,62.96,1020.04,59.08]|+-----+-----+-------+-----+------+---------------------------+only showing top 2 rows# Define train and test data splitsplits = vpp_df.randomSplit([0.7,0.3])train_df = splits[0]test_df = splits[1]# Define the Decision Tree Model dt = DecisionTreeRegressor(featuresCol=\"features\", labelCol=\"PE\")dt_model = dt.fit(train_df)dt_predictions = dt_model.transform(test_df)dt_predictions.show(1, False)+----+-----+-------+-----+------+--------------------------+-----------------+|AT |V |AP |RH |PE |features |prediction |+----+-----+-------+-----+------+--------------------------+-----------------+|3.31|39.42|1024.05|84.31|487.19|[3.31,39.42,1024.05,84.31]|486.1117703349283|+----+-----+-------+-----+------+--------------------------+-----------------+only showing top 1 row# Evaluate the Modeldt_evaluator = RegressionEvaluator(labelCol=\"PE\", predictionCol=\"prediction\", metricName=\"rmse\")dt_rmse = dt_evaluator.evaluate(dt_predictions)print(\"The RMSE of Decision Tree regression Model is {}\".format(dt_rmse))The RMSE of Decision Tree regression Model is 4.451790078736588" }, { "code": null, "e": 24379, "s": 24276, "text": "Gradient Boosting is another common choice among ML professionals. Let us try the GBM in this section." }, { "code": null, "e": 24878, "s": 24379, "text": "from pyspark.ml.regression import GBTRegressor# Define the GBT Modelgbt = GBTRegressor(featuresCol=\"features\", labelCol=\"PE\")gbt_model = gbt.fit(train_df)gbt_predictions = gbt_model.transform(test_df)# Evaluate the GBT Modelgbt_evaluator = RegressionEvaluator(labelCol=\"PE\", predictionCol=\"prediction\", metricName=\"rmse\")gbt_rmse = gbt_evaluator.evaluate(gbt_predictions)print(\"The RMSE of GBT Tree regression Model is {}\".format(gbt_rmse))The RMSE of GBT Tree regression Model is 4.035802933864555" }, { "code": null, "e": 25090, "s": 24878, "text": "Apart from the above-demonstrated regression algorithms, Spark MLlib has also many other implementations of regression algorithms. Details of the implemented regression algorithms can be found at the below link." }, { "code": null, "e": 25107, "s": 25090, "text": "spark.apache.org" }, { "code": null, "e": 25219, "s": 25107, "text": "It is highly recommended to try some of the regression algorithms to get hands-on and play with the parameters." }, { "code": null, "e": 25533, "s": 25219, "text": "In this tutorial, I have tried to give the readers an opportunity to learn and implement basic Machine Learning algorithms using PySpark. Spark not only provide the benefit of distributed processing but also can handle a large amount of data to be processing. To summarise, we have covered below topics/algorithms" }, { "code": null, "e": 25576, "s": 25533, "text": "Setting up the Spark 3.0.1 in Google Colab" }, { "code": null, "e": 25623, "s": 25576, "text": "Overview of Data Transformations using PySpark" }, { "code": null, "e": 25659, "s": 25623, "text": "Clustering algorithms using PySpark" }, { "code": null, "e": 25697, "s": 25659, "text": "Classification problems using PySpark" } ]
cfdisk command in Linux with examples - GeeksforGeeks
15 May, 2019 cfdisk command is used to create, delete, and modify partitions on a disk device. It displays or manipulates the disk partition table by providing a text-based “graphical” interface. cfdisk /dev/sda Example: After running you get a prompt like this: Choose gpt from the list. Now you will see a partition table like this: Creating Partitions Using cfdisk: See the available free space. Here we have 20 GB. Select NEW and create a new partition. Use up-down arrow keys to navigate and enter to select. You can do many things with the free space, if you are installing a new system with a command line interface, you can see an option of using the selected space as primary partition.Example: Select the size 2GB. Enter -> and select primary. Similarly we can do a logical partition also. Example: Select the size 2GB. Enter -> and select primary. Similarly we can do a logical partition also. After sizing the partition, select what type do you want, in my case, I am choosing Linux Swap. After selecting the size and type write to the disk:You will see a prompt like this: You will see a prompt like this: Options: -h, –help: It displays help text and exit. -L, –color[=when]: Colorize the output. The optional argument when can be auto, never or always. If the when argument is omitted, it defaults to auto. The colors can be disabled, for the current built-in default see –help output. See also the COLORS section. -V, –version: Display version information and exit. -z, –zero: Start with an in-memory zeroed partition table. This option does not zero the partition table on the disk; rather, it simply starts the program without reading the existing partition table. This option allows you to create a new partition table from scratch or from a sfdisk-compatible script. Other command line commands: While using cfdisk you can use simple commands just like we use in vi editor for saving, inserting etc. The list of commands are as follows: b: Toggle bootable flag of the current partition. It allows the user to select which partition is primary in the bootable drive. Just press b to see the results, no need of using ctrl. d: It will will delete the current marked partition, making a free space for new partition. h: Will print the help screen, showing commands used . n: Will create a new partition of the marked free space . q: Will quit the program without writing partitions to the table. s: Will fix the partitions order if they are now in proper array. t: Will allow you to change the partition type, allowing you to select from the list. u: Will dump the disk layout in a specified script file name W: Will allow the user to write the data to the disk. The user will be asked if he or she wants to write or not by simply taking input “yes” or “no”. x: Will allow the user to hide or display all extra information of the partition. Up-Arrow: Will allow the user to move the cursor to the previous partition, like moving up in the given table list. Down-Arrow: This option allows the user to move the cursor to the next partition, next partition because every new partition is placed after the previous partition. Left-Arrow: This option allows the user to enter previous menu item. Right-Arrow: This option allows the user to enter to the next menu item. Example: Sample output when we use “?” or “h” linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n15 May, 2019" }, { "code": null, "e": 24589, "s": 24406, "text": "cfdisk command is used to create, delete, and modify partitions on a disk device. It displays or manipulates the disk partition table by providing a text-based “graphical” interface." }, { "code": null, "e": 24605, "s": 24589, "text": "cfdisk /dev/sda" }, { "code": null, "e": 24614, "s": 24605, "text": "Example:" }, { "code": null, "e": 24656, "s": 24614, "text": "After running you get a prompt like this:" }, { "code": null, "e": 24728, "s": 24656, "text": "Choose gpt from the list. Now you will see a partition table like this:" }, { "code": null, "e": 24762, "s": 24728, "text": "Creating Partitions Using cfdisk:" }, { "code": null, "e": 24907, "s": 24762, "text": "See the available free space. Here we have 20 GB. Select NEW and create a new partition. Use up-down arrow keys to navigate and enter to select." }, { "code": null, "e": 25193, "s": 24907, "text": "You can do many things with the free space, if you are installing a new system with a command line interface, you can see an option of using the selected space as primary partition.Example: Select the size 2GB. Enter -> and select primary. Similarly we can do a logical partition also." }, { "code": null, "e": 25298, "s": 25193, "text": "Example: Select the size 2GB. Enter -> and select primary. Similarly we can do a logical partition also." }, { "code": null, "e": 25394, "s": 25298, "text": "After sizing the partition, select what type do you want, in my case, I am choosing Linux Swap." }, { "code": null, "e": 25479, "s": 25394, "text": "After selecting the size and type write to the disk:You will see a prompt like this:" }, { "code": null, "e": 25512, "s": 25479, "text": "You will see a prompt like this:" }, { "code": null, "e": 25521, "s": 25512, "text": "Options:" }, { "code": null, "e": 25564, "s": 25521, "text": "-h, –help: It displays help text and exit." }, { "code": null, "e": 25823, "s": 25564, "text": "-L, –color[=when]: Colorize the output. The optional argument when can be auto, never or always. If the when argument is omitted, it defaults to auto. The colors can be disabled, for the current built-in default see –help output. See also the COLORS section." }, { "code": null, "e": 25875, "s": 25823, "text": "-V, –version: Display version information and exit." }, { "code": null, "e": 26180, "s": 25875, "text": "-z, –zero: Start with an in-memory zeroed partition table. This option does not zero the partition table on the disk; rather, it simply starts the program without reading the existing partition table. This option allows you to create a new partition table from scratch or from a sfdisk-compatible script." }, { "code": null, "e": 26350, "s": 26180, "text": "Other command line commands: While using cfdisk you can use simple commands just like we use in vi editor for saving, inserting etc. The list of commands are as follows:" }, { "code": null, "e": 26535, "s": 26350, "text": "b: Toggle bootable flag of the current partition. It allows the user to select which partition is primary in the bootable drive. Just press b to see the results, no need of using ctrl." }, { "code": null, "e": 26627, "s": 26535, "text": "d: It will will delete the current marked partition, making a free space for new partition." }, { "code": null, "e": 26682, "s": 26627, "text": "h: Will print the help screen, showing commands used ." }, { "code": null, "e": 26740, "s": 26682, "text": "n: Will create a new partition of the marked free space ." }, { "code": null, "e": 26806, "s": 26740, "text": "q: Will quit the program without writing partitions to the table." }, { "code": null, "e": 26872, "s": 26806, "text": "s: Will fix the partitions order if they are now in proper array." }, { "code": null, "e": 26958, "s": 26872, "text": "t: Will allow you to change the partition type, allowing you to select from the list." }, { "code": null, "e": 27019, "s": 26958, "text": "u: Will dump the disk layout in a specified script file name" }, { "code": null, "e": 27169, "s": 27019, "text": "W: Will allow the user to write the data to the disk. The user will be asked if he or she wants to write or not by simply taking input “yes” or “no”." }, { "code": null, "e": 27251, "s": 27169, "text": "x: Will allow the user to hide or display all extra information of the partition." }, { "code": null, "e": 27367, "s": 27251, "text": "Up-Arrow: Will allow the user to move the cursor to the previous partition, like moving up in the given table list." }, { "code": null, "e": 27532, "s": 27367, "text": "Down-Arrow: This option allows the user to move the cursor to the next partition, next partition because every new partition is placed after the previous partition." }, { "code": null, "e": 27601, "s": 27532, "text": "Left-Arrow: This option allows the user to enter previous menu item." }, { "code": null, "e": 27674, "s": 27601, "text": "Right-Arrow: This option allows the user to enter to the next menu item." }, { "code": null, "e": 27720, "s": 27674, "text": "Example: Sample output when we use “?” or “h”" }, { "code": null, "e": 27734, "s": 27720, "text": "linux-command" }, { "code": null, "e": 27756, "s": 27734, "text": "Linux-system-commands" }, { "code": null, "e": 27763, "s": 27756, "text": "Picked" }, { "code": null, "e": 27774, "s": 27763, "text": "Linux-Unix" }, { "code": null, "e": 27872, "s": 27774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27909, "s": 27872, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27944, "s": 27909, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27970, "s": 27944, "text": "Thread functions in C/C++" }, { "code": null, "e": 28004, "s": 27970, "text": "mv command in Linux with examples" }, { "code": null, "e": 28041, "s": 28004, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28070, "s": 28041, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28096, "s": 28070, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28136, "s": 28096, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 28171, "s": 28136, "text": "Basic Operators in Shell Scripting" } ]
PHP | array_column() Function - GeeksforGeeks
29 Sep, 2021 The array_column() is an inbuilt function in PHP and is used to return the values from a single column in the input array. Syntax: array array_column($input_array, $column_number, $index_key); Parameters: Out of the three parameters, two are mandatory and one is optional. Let’s look at the parameters. $input_array (mandatory): This parameter refers to the original multi-dimensional array from which we want to extract all the values of a particular column.$column_number (mandatory): This parameter refers to the column of values that is needed to be returned. This value may be an integer key of the column, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects.$index_key (optional): This is an optional parameter and refers to the column to use as the index/keys for the returned array in output. This value may be the integer key of the column, or it may be the string key name. $input_array (mandatory): This parameter refers to the original multi-dimensional array from which we want to extract all the values of a particular column. $column_number (mandatory): This parameter refers to the column of values that is needed to be returned. This value may be an integer key of the column, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects. $index_key (optional): This is an optional parameter and refers to the column to use as the index/keys for the returned array in output. This value may be the integer key of the column, or it may be the string key name. Return Type: As shown in the syntax, the return type of array_column() function is array. That is, the function returns an array that contains values from a single column of the input array, identified by a column_number. Optionally, an index_key may also be provided to index the values in the returned array by the values from the index_key column of the input array. Examples: Input : array( array( 'roll' => 5, 'name' => 'Akash', 'hobby' => 'Cricket', ), array( 'roll' => 1, 'name' => 'Rishav', 'hobby' => 'Football', ), array( 'roll' => 3, 'name' => 'Anand', 'hobby' => 'Chess', ), ) $column_number = 'hobby' , $index_key = 'roll' Output : Array ( [5] => Cricket [1] => Football [3] => Chess [4] => Cards [2] => Basketball ) In the above example, the array_column() function is used to fetch the values of column with key as ‘name’ and these values in the output array are stored with keys which are taken from values of the key ‘roll’ in the original array. Below program illustrates the array_column() with all three parameters: C++ <?php// PHP code to illustrate the working of array_columnfunction Column($details){ $rec = array_column($details, 'name', 'roll'); return $rec;} // Driver Code$details = array( array( 'roll' => 5, 'name' => 'Akash', 'hobby' => 'Cricket', ), array( 'roll' => 1, 'name' => 'Rishav', 'hobby' => 'Football', ), array( 'roll' => 3, 'name' => 'Anand', 'hobby' => 'Chess', ), array( 'roll' => 4, 'name' => 'Gaurav', 'hobby' => 'Cards', ), array( 'roll' => 2, 'name' => 'Rahim', 'hobby' => 'Basketball', ),);print_r(Column($details));?> Output: Array ( [5] => Akash [1] => Rishav [3] => Anand [4] => Gaurav [2] => Rahim ) We can also ignore the third parameter that is index_key. Then, in this case, the column in output array will get indexed in a linear manner as given in the array. Below is the PHP program to illustrate this: C++ <?php// PHP code to illustrate the working of array_columnfunction Column($details){ $rec = array_column($details, 'hobby'); return $rec;} // Driver Code$details = array( array( 'roll' => 5, 'name' => 'Akash', 'hobby' => 'Cricket', ), array( 'roll' => 1, 'name' => 'Rishav', 'hobby' => 'Football', ), array( 'roll' => 3, 'name' => 'Anand', 'hobby' => 'Chess', ), array( 'roll' => 4, 'name' => 'Gaurav', 'hobby' => 'Cards', ), array( 'roll' => 2, 'name' => 'Rahim', 'hobby' => 'Basketball', ),);print_r(Column($details));?> Output: Array ( [0] => Cricket [1] => Football [2] => Chess [3] => Cards [4] => Basketball ) simranarora5sos PHP-array Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 40295, "s": 40267, "text": "\n29 Sep, 2021" }, { "code": null, "e": 40419, "s": 40295, "text": "The array_column() is an inbuilt function in PHP and is used to return the values from a single column in the input array. " }, { "code": null, "e": 40428, "s": 40419, "text": "Syntax: " }, { "code": null, "e": 40490, "s": 40428, "text": "array array_column($input_array, $column_number, $index_key);" }, { "code": null, "e": 40601, "s": 40490, "text": "Parameters: Out of the three parameters, two are mandatory and one is optional. Let’s look at the parameters. " }, { "code": null, "e": 41261, "s": 40601, "text": "$input_array (mandatory): This parameter refers to the original multi-dimensional array from which we want to extract all the values of a particular column.$column_number (mandatory): This parameter refers to the column of values that is needed to be returned. This value may be an integer key of the column, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects.$index_key (optional): This is an optional parameter and refers to the column to use as the index/keys for the returned array in output. This value may be the integer key of the column, or it may be the string key name." }, { "code": null, "e": 41418, "s": 41261, "text": "$input_array (mandatory): This parameter refers to the original multi-dimensional array from which we want to extract all the values of a particular column." }, { "code": null, "e": 41703, "s": 41418, "text": "$column_number (mandatory): This parameter refers to the column of values that is needed to be returned. This value may be an integer key of the column, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects." }, { "code": null, "e": 41923, "s": 41703, "text": "$index_key (optional): This is an optional parameter and refers to the column to use as the index/keys for the returned array in output. This value may be the integer key of the column, or it may be the string key name." }, { "code": null, "e": 42293, "s": 41923, "text": "Return Type: As shown in the syntax, the return type of array_column() function is array. That is, the function returns an array that contains values from a single column of the input array, identified by a column_number. Optionally, an index_key may also be provided to index the values in the returned array by the values from the index_key column of the input array." }, { "code": null, "e": 42304, "s": 42293, "text": "Examples: " }, { "code": null, "e": 42899, "s": 42304, "text": "Input : \n array(\n array(\n 'roll' => 5,\n 'name' => 'Akash',\n 'hobby' => 'Cricket',\n ),\n array(\n 'roll' => 1,\n 'name' => 'Rishav',\n 'hobby' => 'Football',\n ),\n array(\n 'roll' => 3,\n 'name' => 'Anand',\n 'hobby' => 'Chess',\n ),\n )\n \n $column_number = 'hobby' , $index_key = 'roll'\nOutput : \n Array\n (\n [5] => Cricket\n [1] => Football\n [3] => Chess\n [4] => Cards\n [2] => Basketball\n )" }, { "code": null, "e": 43133, "s": 42899, "text": "In the above example, the array_column() function is used to fetch the values of column with key as ‘name’ and these values in the output array are stored with keys which are taken from values of the key ‘roll’ in the original array." }, { "code": null, "e": 43207, "s": 43133, "text": "Below program illustrates the array_column() with all three parameters: " }, { "code": null, "e": 43211, "s": 43207, "text": "C++" }, { "code": "<?php// PHP code to illustrate the working of array_columnfunction Column($details){ $rec = array_column($details, 'name', 'roll'); return $rec;} // Driver Code$details = array( array( 'roll' => 5, 'name' => 'Akash', 'hobby' => 'Cricket', ), array( 'roll' => 1, 'name' => 'Rishav', 'hobby' => 'Football', ), array( 'roll' => 3, 'name' => 'Anand', 'hobby' => 'Chess', ), array( 'roll' => 4, 'name' => 'Gaurav', 'hobby' => 'Cards', ), array( 'roll' => 2, 'name' => 'Rahim', 'hobby' => 'Basketball', ),);print_r(Column($details));?>", "e": 43882, "s": 43211, "text": null }, { "code": null, "e": 43891, "s": 43882, "text": "Output: " }, { "code": null, "e": 43988, "s": 43891, "text": "Array\n(\n [5] => Akash\n [1] => Rishav\n [3] => Anand\n [4] => Gaurav\n [2] => Rahim\n)" }, { "code": null, "e": 44199, "s": 43988, "text": "We can also ignore the third parameter that is index_key. Then, in this case, the column in output array will get indexed in a linear manner as given in the array. Below is the PHP program to illustrate this: " }, { "code": null, "e": 44203, "s": 44199, "text": "C++" }, { "code": "<?php// PHP code to illustrate the working of array_columnfunction Column($details){ $rec = array_column($details, 'hobby'); return $rec;} // Driver Code$details = array( array( 'roll' => 5, 'name' => 'Akash', 'hobby' => 'Cricket', ), array( 'roll' => 1, 'name' => 'Rishav', 'hobby' => 'Football', ), array( 'roll' => 3, 'name' => 'Anand', 'hobby' => 'Chess', ), array( 'roll' => 4, 'name' => 'Gaurav', 'hobby' => 'Cards', ), array( 'roll' => 2, 'name' => 'Rahim', 'hobby' => 'Basketball', ),);print_r(Column($details));?>", "e": 44867, "s": 44203, "text": null }, { "code": null, "e": 44876, "s": 44867, "text": "Output: " }, { "code": null, "e": 44981, "s": 44876, "text": "Array\n(\n [0] => Cricket\n [1] => Football\n [2] => Chess\n [3] => Cards\n [4] => Basketball\n)" }, { "code": null, "e": 44999, "s": 44983, "text": "simranarora5sos" }, { "code": null, "e": 45009, "s": 44999, "text": "PHP-array" }, { "code": null, "e": 45026, "s": 45009, "text": "Web Technologies" }, { "code": null, "e": 45124, "s": 45026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45133, "s": 45124, "text": "Comments" }, { "code": null, "e": 45146, "s": 45133, "text": "Old Comments" }, { "code": null, "e": 45202, "s": 45146, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 45235, "s": 45202, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 45297, "s": 45235, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 45340, "s": 45297, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 45390, "s": 45340, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 45451, "s": 45390, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45496, "s": 45451, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45568, "s": 45496, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 45626, "s": 45568, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Python 3 Tutorial
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). Python is named after a TV Show called ëMonty Pythonís Flying Circusí and not after Python-the snake. Python 3.0 was released in 2008. Although this version is supposed to be backward incompatibles, later on many of its important features have been backported to be compatible with version 2.7.This tutorial gives enough understanding on Python 3 version programming language. Please refer to this link for our Python 2 tutorial. Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. Python is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Python: Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. Following are important characteristics of python − It supports functional and structured programming methods as well as OOP. It supports functional and structured programming methods as well as OOP. It can be used as a scripting language or can be compiled to byte-code for building large applications. It can be used as a scripting language or can be compiled to byte-code for building large applications. It provides very high-level dynamic data types and supports dynamic type checking. It provides very high-level dynamic data types and supports dynamic type checking. It supports automatic garbage collection. It supports automatic garbage collection. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. Just to give you a little excitement about Python, I'm going to give you a small conventional Python Hello World program, You can try it using Demo link. print "Hello, Python!" As mentioned before, Python is one of the most widely used language over the web. I'm going to list few of them here: Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Easy-to-read − Python code is more clearly defined and visible to the eyes. Easy-to-read − Python code is more clearly defined and visible to the eyes. Easy-to-maintain − Python's source code is fairly easy-to-maintain. Easy-to-maintain − Python's source code is fairly easy-to-maintain. A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code. Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code. Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases − Python provides interfaces to all major commercial databases. Databases − Python provides interfaces to all major commercial databases. GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable − Python provides a better structure and support for large programs than shell scripting. Scalable − Python provides a better structure and support for large programs than shell scripting. This tutorial is designed for software programmers who want to upgrade their Python skills to Python 3. This tutorial can also be used to learn Python programming language from scratch. You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2699, "s": 2340, "text": "Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). Python is named after a TV Show called ëMonty Pythonís Flying Circusí and not after Python-the snake." }, { "code": null, "e": 3028, "s": 2699, "text": " Python 3.0 was released in 2008. Although this version is supposed to be backward incompatibles, later on many of its important features have been backported to be compatible with version 2.7.This tutorial gives enough understanding on Python 3 version programming language. Please refer to this link for our Python 2 tutorial." }, { "code": null, "e": 3302, "s": 3028, "text": "Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages." }, { "code": null, "e": 3517, "s": 3302, "text": "Python is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Python:" }, { "code": null, "e": 3686, "s": 3517, "text": "Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP." }, { "code": null, "e": 3855, "s": 3686, "text": "Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP." }, { "code": null, "e": 3986, "s": 3855, "text": "Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs." }, { "code": null, "e": 4117, "s": 3986, "text": "Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs." }, { "code": null, "e": 4250, "s": 4117, "text": "Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects." }, { "code": null, "e": 4383, "s": 4250, "text": "Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects." }, { "code": null, "e": 4594, "s": 4383, "text": "Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games." }, { "code": null, "e": 4805, "s": 4594, "text": "Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games." }, { "code": null, "e": 4857, "s": 4805, "text": "Following are important characteristics of python −" }, { "code": null, "e": 4931, "s": 4857, "text": "It supports functional and structured programming methods as well as OOP." }, { "code": null, "e": 5005, "s": 4931, "text": "It supports functional and structured programming methods as well as OOP." }, { "code": null, "e": 5109, "s": 5005, "text": "It can be used as a scripting language or can be compiled to byte-code for building large applications." }, { "code": null, "e": 5213, "s": 5109, "text": "It can be used as a scripting language or can be compiled to byte-code for building large applications." }, { "code": null, "e": 5296, "s": 5213, "text": "It provides very high-level dynamic data types and supports dynamic type checking." }, { "code": null, "e": 5379, "s": 5296, "text": "It provides very high-level dynamic data types and supports dynamic type checking." }, { "code": null, "e": 5421, "s": 5379, "text": "It supports automatic garbage collection." }, { "code": null, "e": 5463, "s": 5421, "text": "It supports automatic garbage collection." }, { "code": null, "e": 5535, "s": 5463, "text": "It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java." }, { "code": null, "e": 5607, "s": 5535, "text": "It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java." }, { "code": null, "e": 5761, "s": 5607, "text": "Just to give you a little excitement about Python, I'm going to give you a small conventional Python Hello World program, You can try it using Demo link." }, { "code": null, "e": 5784, "s": 5761, "text": "print \"Hello, Python!\"" }, { "code": null, "e": 5902, "s": 5784, "text": "As mentioned before, Python is one of the most widely used language over the web. I'm going to list few of them here:" }, { "code": null, "e": 6048, "s": 5902, "text": "Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly." }, { "code": null, "e": 6194, "s": 6048, "text": "Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly." }, { "code": null, "e": 6270, "s": 6194, "text": "Easy-to-read − Python code is more clearly defined and visible to the eyes." }, { "code": null, "e": 6346, "s": 6270, "text": "Easy-to-read − Python code is more clearly defined and visible to the eyes." }, { "code": null, "e": 6414, "s": 6346, "text": "Easy-to-maintain − Python's source code is fairly easy-to-maintain." }, { "code": null, "e": 6482, "s": 6414, "text": "Easy-to-maintain − Python's source code is fairly easy-to-maintain." }, { "code": null, "e": 6618, "s": 6482, "text": "A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh." }, { "code": null, "e": 6754, "s": 6618, "text": "A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh." }, { "code": null, "e": 6884, "s": 6754, "text": "Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code." }, { "code": null, "e": 7014, "s": 6884, "text": "Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code." }, { "code": null, "e": 7125, "s": 7014, "text": "Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms." }, { "code": null, "e": 7236, "s": 7125, "text": "Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms." }, { "code": null, "e": 7396, "s": 7236, "text": "Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient." }, { "code": null, "e": 7556, "s": 7396, "text": "Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient." }, { "code": null, "e": 7630, "s": 7556, "text": "Databases − Python provides interfaces to all major commercial databases." }, { "code": null, "e": 7704, "s": 7630, "text": "Databases − Python provides interfaces to all major commercial databases." }, { "code": null, "e": 7904, "s": 7704, "text": "GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix." }, { "code": null, "e": 8104, "s": 7904, "text": "GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix." }, { "code": null, "e": 8203, "s": 8104, "text": "Scalable − Python provides a better structure and support for large programs than shell scripting." }, { "code": null, "e": 8302, "s": 8203, "text": "Scalable − Python provides a better structure and support for large programs than shell scripting." }, { "code": null, "e": 8488, "s": 8302, "text": "This tutorial is designed for software programmers who want to upgrade their Python skills to Python 3. This tutorial can also be used to learn Python programming language from scratch." }, { "code": null, "e": 8634, "s": 8488, "text": "You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus." }, { "code": null, "e": 8671, "s": 8634, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8687, "s": 8671, "text": " Malhar Lathkar" }, { "code": null, "e": 8720, "s": 8687, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 8739, "s": 8720, "text": " Arnab Chakraborty" }, { "code": null, "e": 8774, "s": 8739, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 8796, "s": 8774, "text": " In28Minutes Official" }, { "code": null, "e": 8830, "s": 8796, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 8858, "s": 8830, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8893, "s": 8858, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 8907, "s": 8893, "text": " Lets Kode It" }, { "code": null, "e": 8940, "s": 8907, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 8957, "s": 8940, "text": " Abhilash Nelson" }, { "code": null, "e": 8964, "s": 8957, "text": " Print" }, { "code": null, "e": 8975, "s": 8964, "text": " Add Notes" } ]
How to check if input is numeric in C++?
Here we will see how to check whether a given input is numeric string or a normal string. The numeric string will hold all characters that are in range 0 – 9. The solution is very simple, we will simply go through each characters one by one, and check whether it is numeric or not. If it is numeric, then point to the next, otherwise return false value. #include <iostream> using namespace std; bool isNumeric(string str) { for (int i = 0; i < str.length(); i++) if (isdigit(str[i]) == false) return false; //when one non numeric value is found, return false return true; } int main() { string str; cout << "Enter a string: "; cin >> str; if (isNumeric(str)) cout << "This is a Number" << endl; else cout << "This is not a number"; } Enter a string: 5687 This is a Number Enter a string: 584asS This is not a number
[ { "code": null, "e": 1416, "s": 1062, "text": "Here we will see how to check whether a given input is numeric string or a normal string. The numeric string will hold all characters that are in range 0 – 9. The solution is very simple, we will simply go through each characters one by one, and check whether it is numeric or not. If it is numeric, then point to the next, otherwise return false value." }, { "code": null, "e": 1847, "s": 1416, "text": "#include <iostream>\nusing namespace std;\nbool isNumeric(string str) {\n for (int i = 0; i < str.length(); i++)\n if (isdigit(str[i]) == false)\n return false; //when one non numeric value is found, return false\n return true;\n}\nint main() {\n string str;\n cout << \"Enter a string: \";\n cin >> str;\n if (isNumeric(str))\n cout << \"This is a Number\" << endl;\n else\n cout << \"This is not a number\";\n}" }, { "code": null, "e": 1885, "s": 1847, "text": "Enter a string: 5687\nThis is a Number" }, { "code": null, "e": 1929, "s": 1885, "text": "Enter a string: 584asS\nThis is not a number" } ]
Find letter's position in Alphabet using Bit operation in C++
In this problem, we are given a string str consisting of english alphabets. Our task is to find the letter's position in the Alphabet using the Bit operation. Problem Description: Here, we will return the position of each character of the string as it is in english alphabets. The characters of the string are case-insensitive i.e. “t” and “T” are treated the same. Let’s take an example to understand the problem, Input: str = “Tutorialspoint” Output: 20 21 20 15 18 9 1 12 19 16 15 9 14 20 A simple solution to find a character's position is by finding its logical AND operation with 31. Live Demo #include <iostream> using namespace std; void findLetterPosition(string str, int n) { for (int i = 0; i < n; i++) { cout<<(str[i] & 31) << " "; } } int main() { string str = "TutorialsPoint"; int n = str.length(); cout<<"The letters position in string "<<str<<" is \n"; findLetterPosition(str, n); return 0; } The letters position in string TutorialsPoint is 20 21 20 15 18 9 1 12 19 16 15 9 14 20
[ { "code": null, "e": 1222, "s": 1062, "text": "In this problem, we are given a string str consisting of english alphabets. Our task is to find the letter's position in the Alphabet using the Bit operation. " }, { "code": null, "e": 1340, "s": 1222, "text": "Problem Description: Here, we will return the position of each character of the string as it is in english alphabets." }, { "code": null, "e": 1429, "s": 1340, "text": "The characters of the string are case-insensitive i.e. “t” and “T” are treated the same." }, { "code": null, "e": 1479, "s": 1429, "text": "Let’s take an example to understand the problem, " }, { "code": null, "e": 1509, "s": 1479, "text": "Input: str = “Tutorialspoint”" }, { "code": null, "e": 1557, "s": 1509, "text": "Output: 20 21 20 15 18 9 1 12 19 16 15 9 14 20 " }, { "code": null, "e": 1655, "s": 1557, "text": "A simple solution to find a character's position is by finding its logical AND operation with 31." }, { "code": null, "e": 1665, "s": 1655, "text": "Live Demo" }, { "code": null, "e": 2013, "s": 1665, "text": "#include <iostream>\nusing namespace std;\n\nvoid findLetterPosition(string str, int n) {\n \n for (int i = 0; i < n; i++) {\n cout<<(str[i] & 31) << \" \";\n }\n}\n\nint main() {\n \n string str = \"TutorialsPoint\";\n int n = str.length();\n cout<<\"The letters position in string \"<<str<<\" is \\n\";\n findLetterPosition(str, n);\n\n return 0;\n}" }, { "code": null, "e": 2101, "s": 2013, "text": "The letters position in string TutorialsPoint is\n20 21 20 15 18 9 1 12 19 16 15 9 14 20" } ]
How to Scrape Youtube Comments with Python | by François St-Amant | Towards Data Science
The first part of any Natural Language Processing project is to get a database. Indeed, having the whole dataset cleaned and labeled only applies on Kaggle, not in real life. When it comes to sentiment analysis projects, I feel like Youtube comments represent a great and underused source of data. You easily have access to the opinion of all viewers on a very specific subject, i.e. the video. Knowing all this, here is how to scrape the comments from a Youtube video, step by step. Here is the video from which I will be scraping the comments: https://www.youtube.com/watch?v=kuhhT_cBtFU&t=2s It’s a video posted by CNN showing the arrest and shooting of Rayshard Brooks in Atlanta that took place on June 12th. So first, don’t forget to install a ChromeDriver from right here. You should also have Google Chrome installed. Now that this is done, let’s import the libraries we will need: import timefrom selenium.webdriver import Chromefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC Selenium is needed here because Youtube is JavaScript rendered, which BeautifulSoup cannot deal with. All the other modules are needed because Youtube comments are dynamically loaded, which means that they are only visible when you scroll down the page. So we want a loop that will: Scroll down Wait for comments to appear Scrape the comments Repeat for whatever range we want. Here is the loop that does just that. So here is how it works: Access the URL you want with the driver.get function.Scroll down and wait until everything is visible with wait.until and EC.visibility_of_element_located.Scrape the comments by finding all the #content-text elements (which is what we want, as you can see below) in the current viewed page. Access the URL you want with the driver.get function. Scroll down and wait until everything is visible with wait.until and EC.visibility_of_element_located. Scrape the comments by finding all the #content-text elements (which is what we want, as you can see below) in the current viewed page. 4. Append the comments to the data list. To scrape comments from another video, all you need to do is change the URL! It’s that easy. Here, I repeat the loop 200 times, which scrapes about 1,400 comments. Here is what the data looks like: import pandas as pd df = pd.DataFrame(data, columns=['comment'])df.head() There you have it. Now, you would be able to use that data to start your NLP project. Thanks for reading, I hope this helped! To become a member: https://francoisstamant.medium.com/membership
[ { "code": null, "e": 347, "s": 172, "text": "The first part of any Natural Language Processing project is to get a database. Indeed, having the whole dataset cleaned and labeled only applies on Kaggle, not in real life." }, { "code": null, "e": 567, "s": 347, "text": "When it comes to sentiment analysis projects, I feel like Youtube comments represent a great and underused source of data. You easily have access to the opinion of all viewers on a very specific subject, i.e. the video." }, { "code": null, "e": 656, "s": 567, "text": "Knowing all this, here is how to scrape the comments from a Youtube video, step by step." }, { "code": null, "e": 767, "s": 656, "text": "Here is the video from which I will be scraping the comments: https://www.youtube.com/watch?v=kuhhT_cBtFU&t=2s" }, { "code": null, "e": 886, "s": 767, "text": "It’s a video posted by CNN showing the arrest and shooting of Rayshard Brooks in Atlanta that took place on June 12th." }, { "code": null, "e": 1062, "s": 886, "text": "So first, don’t forget to install a ChromeDriver from right here. You should also have Google Chrome installed. Now that this is done, let’s import the libraries we will need:" }, { "code": null, "e": 1320, "s": 1062, "text": "import timefrom selenium.webdriver import Chromefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC" }, { "code": null, "e": 1422, "s": 1320, "text": "Selenium is needed here because Youtube is JavaScript rendered, which BeautifulSoup cannot deal with." }, { "code": null, "e": 1603, "s": 1422, "text": "All the other modules are needed because Youtube comments are dynamically loaded, which means that they are only visible when you scroll down the page. So we want a loop that will:" }, { "code": null, "e": 1615, "s": 1603, "text": "Scroll down" }, { "code": null, "e": 1643, "s": 1615, "text": "Wait for comments to appear" }, { "code": null, "e": 1663, "s": 1643, "text": "Scrape the comments" }, { "code": null, "e": 1698, "s": 1663, "text": "Repeat for whatever range we want." }, { "code": null, "e": 1736, "s": 1698, "text": "Here is the loop that does just that." }, { "code": null, "e": 1761, "s": 1736, "text": "So here is how it works:" }, { "code": null, "e": 2052, "s": 1761, "text": "Access the URL you want with the driver.get function.Scroll down and wait until everything is visible with wait.until and EC.visibility_of_element_located.Scrape the comments by finding all the #content-text elements (which is what we want, as you can see below) in the current viewed page." }, { "code": null, "e": 2106, "s": 2052, "text": "Access the URL you want with the driver.get function." }, { "code": null, "e": 2209, "s": 2106, "text": "Scroll down and wait until everything is visible with wait.until and EC.visibility_of_element_located." }, { "code": null, "e": 2345, "s": 2209, "text": "Scrape the comments by finding all the #content-text elements (which is what we want, as you can see below) in the current viewed page." }, { "code": null, "e": 2386, "s": 2345, "text": "4. Append the comments to the data list." }, { "code": null, "e": 2479, "s": 2386, "text": "To scrape comments from another video, all you need to do is change the URL! It’s that easy." }, { "code": null, "e": 2584, "s": 2479, "text": "Here, I repeat the loop 200 times, which scrapes about 1,400 comments. Here is what the data looks like:" }, { "code": null, "e": 2660, "s": 2584, "text": "import pandas as pd df = pd.DataFrame(data, columns=['comment'])df.head()" }, { "code": null, "e": 2746, "s": 2660, "text": "There you have it. Now, you would be able to use that data to start your NLP project." }, { "code": null, "e": 2786, "s": 2746, "text": "Thanks for reading, I hope this helped!" } ]
How to convert UTC date time into local date time using JavaScript ?
14 Apr, 2022 Given an UTC date and the task is to convert UTC date time into local date-time using JavaScript toLocaleString() function. Syntax: var theDate = new Date(Date.parse('06/14/2020 4:41:48 PM UTC')) theDate.toLocaleString() JavaScript code: javascript // Function to convert UTC date-time// to Local date-timefunction myFunction() { var theDate = new Date(Date.parse( '06/14/2020 4:41:48 PM UTC')); document.write("Local date Time: ", theDate.toLocaleString());} Example: This example converting UTC date time into local date time using JavaScript. html <!DOCTYPE html><html> <head> <title> How to convert UTC date time into local date time? </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeekforGeeks</h1> <p> Click the button to convert UTC date and time to local date and time </p> <p> UTC date and time: 06/14/2020 4:41:48 PM </p> <button onclick="myGeeks()"> Try it </button> <p id="demo"></p> <script> function myGeeks() { var theDate = new Date(Date.parse( '06/14/2020 4:41:48 PM UTC')); document.getElementById("demo") .innerHTML = "Local date Time: " + theDate.toLocaleString(); } </script></body> </html> Output: Before Clicking the Button: After Clicking the Button: sweetyty javascript-date Picked CSS HTML JavaScript HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Apr, 2022" }, { "code": null, "e": 152, "s": 28, "text": "Given an UTC date and the task is to convert UTC date time into local date-time using JavaScript toLocaleString() function." }, { "code": null, "e": 160, "s": 152, "text": "Syntax:" }, { "code": null, "e": 249, "s": 160, "text": "var theDate = new Date(Date.parse('06/14/2020 4:41:48 PM UTC'))\ntheDate.toLocaleString()" }, { "code": null, "e": 267, "s": 249, "text": "JavaScript code: " }, { "code": null, "e": 278, "s": 267, "text": "javascript" }, { "code": "// Function to convert UTC date-time// to Local date-timefunction myFunction() { var theDate = new Date(Date.parse( '06/14/2020 4:41:48 PM UTC')); document.write(\"Local date Time: \", theDate.toLocaleString());}", "e": 518, "s": 278, "text": null }, { "code": null, "e": 605, "s": 518, "text": "Example: This example converting UTC date time into local date time using JavaScript. " }, { "code": null, "e": 610, "s": 605, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to convert UTC date time into local date time? </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeekforGeeks</h1> <p> Click the button to convert UTC date and time to local date and time </p> <p> UTC date and time: 06/14/2020 4:41:48 PM </p> <button onclick=\"myGeeks()\"> Try it </button> <p id=\"demo\"></p> <script> function myGeeks() { var theDate = new Date(Date.parse( '06/14/2020 4:41:48 PM UTC')); document.getElementById(\"demo\") .innerHTML = \"Local date Time: \" + theDate.toLocaleString(); } </script></body> </html>", "e": 1455, "s": 610, "text": null }, { "code": null, "e": 1463, "s": 1455, "text": "Output:" }, { "code": null, "e": 1492, "s": 1463, "text": "Before Clicking the Button: " }, { "code": null, "e": 1520, "s": 1492, "text": "After Clicking the Button: " }, { "code": null, "e": 1529, "s": 1520, "text": "sweetyty" }, { "code": null, "e": 1545, "s": 1529, "text": "javascript-date" }, { "code": null, "e": 1552, "s": 1545, "text": "Picked" }, { "code": null, "e": 1556, "s": 1552, "text": "CSS" }, { "code": null, "e": 1561, "s": 1556, "text": "HTML" }, { "code": null, "e": 1572, "s": 1561, "text": "JavaScript" }, { "code": null, "e": 1577, "s": 1572, "text": "HTML" } ]
usermod command in Linux with Examples
16 Feb, 2022 usermod command or modify user is a command in Linux that is used to change the properties of a user in Linux through the command line. After creating a user we have to sometimes change their attributes like password or login directory etc. so in order to do that we use the Usermod command. The information of a user is stored in the following files: /etc/passwd /etc/group /etc/shadow /etc/login.defs /etc/gshadow /etc/login.defs When we execute usermod command in terminal the command make the changes in these files itself. Note: usermod command needs to be executed only as a root user. 1. To add a comment for a user sudo usermod -c "This is test user" test_user This will add a comment about the user or a short description related to the user. 2. To change the home directory of a user sudo usermod -d /home/manav test_user This will change the home directory of the user to /home/manav. 3. To change the expiry date of a user sudo usermod -e 2020-05-29 test_user This will change the expiration date of account “test_user” 4. To change the group of a user sudo usermod -g manav test_user This command will now change the group of test user from test_user to manav 5. To change user login name sudo usermod -l test_account test_user This will now change the login name of the user “test_user”. 6. To lock a user sudo usermod -L test_user This will lock the “test_user” account and will display a! sign in shadow file before the username 7. To unlock a user sudo usermod -U test_user This will unlock the “test_user” which was locked by the previous command 8. To set an unencrypted password for the user sudo usermod -p test_password test_user This will set the password “test_password” in the unencrypted form for the user “test_user” 9. To create a shell for the user sudo usermod -s /bin/sh test_user This command will now create a shell for the user “test_user” from /bin/sh 10. To change the user id of a user sudo usermod -u 1234 test_user This command will change the user id of “test_user” to 1234 gulshankumarar231 sumitgumber28 linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples Docker - COPY Instruction UDP Server-Client implementation in C scp command in Linux with Examples echo command in Linux with Examples Cat command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Feb, 2022" }, { "code": null, "e": 406, "s": 53, "text": "usermod command or modify user is a command in Linux that is used to change the properties of a user in Linux through the command line. After creating a user we have to sometimes change their attributes like password or login directory etc. so in order to do that we use the Usermod command. The information of a user is stored in the following files: " }, { "code": null, "e": 420, "s": 408, "text": "/etc/passwd" }, { "code": null, "e": 431, "s": 420, "text": "/etc/group" }, { "code": null, "e": 443, "s": 431, "text": "/etc/shadow" }, { "code": null, "e": 459, "s": 443, "text": "/etc/login.defs" }, { "code": null, "e": 472, "s": 459, "text": "/etc/gshadow" }, { "code": null, "e": 488, "s": 472, "text": "/etc/login.defs" }, { "code": null, "e": 585, "s": 488, "text": "When we execute usermod command in terminal the command make the changes in these files itself. " }, { "code": null, "e": 650, "s": 585, "text": "Note: usermod command needs to be executed only as a root user. " }, { "code": null, "e": 684, "s": 652, "text": "1. To add a comment for a user " }, { "code": null, "e": 732, "s": 686, "text": "sudo usermod -c \"This is test user\" test_user" }, { "code": null, "e": 818, "s": 734, "text": "This will add a comment about the user or a short description related to the user. " }, { "code": null, "e": 861, "s": 818, "text": "2. To change the home directory of a user " }, { "code": null, "e": 901, "s": 863, "text": "sudo usermod -d /home/manav test_user" }, { "code": null, "e": 968, "s": 903, "text": "This will change the home directory of the user to /home/manav. " }, { "code": null, "e": 1008, "s": 968, "text": "3. To change the expiry date of a user " }, { "code": null, "e": 1047, "s": 1010, "text": "sudo usermod -e 2020-05-29 test_user" }, { "code": null, "e": 1110, "s": 1049, "text": "This will change the expiration date of account “test_user” " }, { "code": null, "e": 1144, "s": 1110, "text": "4. To change the group of a user " }, { "code": null, "e": 1178, "s": 1146, "text": "sudo usermod -g manav test_user" }, { "code": null, "e": 1257, "s": 1180, "text": "This command will now change the group of test user from test_user to manav " }, { "code": null, "e": 1287, "s": 1257, "text": "5. To change user login name " }, { "code": null, "e": 1328, "s": 1289, "text": "sudo usermod -l test_account test_user" }, { "code": null, "e": 1392, "s": 1330, "text": "This will now change the login name of the user “test_user”. " }, { "code": null, "e": 1411, "s": 1392, "text": "6. To lock a user " }, { "code": null, "e": 1439, "s": 1413, "text": "sudo usermod -L test_user" }, { "code": null, "e": 1541, "s": 1441, "text": "This will lock the “test_user” account and will display a! sign in shadow file before the username " }, { "code": null, "e": 1562, "s": 1541, "text": "7. To unlock a user " }, { "code": null, "e": 1590, "s": 1564, "text": "sudo usermod -U test_user" }, { "code": null, "e": 1667, "s": 1592, "text": "This will unlock the “test_user” which was locked by the previous command " }, { "code": null, "e": 1715, "s": 1667, "text": "8. To set an unencrypted password for the user " }, { "code": null, "e": 1757, "s": 1717, "text": "sudo usermod -p test_password test_user" }, { "code": null, "e": 1852, "s": 1759, "text": "This will set the password “test_password” in the unencrypted form for the user “test_user” " }, { "code": null, "e": 1887, "s": 1852, "text": "9. To create a shell for the user " }, { "code": null, "e": 1923, "s": 1889, "text": "sudo usermod -s /bin/sh test_user" }, { "code": null, "e": 2001, "s": 1925, "text": "This command will now create a shell for the user “test_user” from /bin/sh " }, { "code": null, "e": 2038, "s": 2001, "text": "10. To change the user id of a user " }, { "code": null, "e": 2071, "s": 2040, "text": "sudo usermod -u 1234 test_user" }, { "code": null, "e": 2134, "s": 2073, "text": "This command will change the user id of “test_user” to 1234 " }, { "code": null, "e": 2152, "s": 2134, "text": "gulshankumarar231" }, { "code": null, "e": 2166, "s": 2152, "text": "sumitgumber28" }, { "code": null, "e": 2180, "s": 2166, "text": "linux-command" }, { "code": null, "e": 2202, "s": 2180, "text": "Linux-system-commands" }, { "code": null, "e": 2213, "s": 2202, "text": "Linux-Unix" }, { "code": null, "e": 2311, "s": 2213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2346, "s": 2311, "text": "tar command in Linux with examples" }, { "code": null, "e": 2379, "s": 2346, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2417, "s": 2379, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2453, "s": 2417, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2479, "s": 2453, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2517, "s": 2479, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2552, "s": 2517, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2588, "s": 2552, "text": "echo command in Linux with Examples" }, { "code": null, "e": 2623, "s": 2588, "text": "Cat command in Linux with examples" } ]
D3.js scaleLinear() method
19 Aug, 2020 The d3.scaleLinear() method is used to create a visual scale point. This method is used to transform data values into visual variables. Syntax: d3.scaleLinear(); Parameters: This method takes no parameters. Return Value: This method returns a Linear scale function. Example 1: Plotting scale points. <!DOCTYPE html><html><meta charset="utf-8"><head> <title>Line in D3.js</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <center> <svg width="700" height="40"> <g class="scal" transform="translate(40, 30)"> </g> </svg></center> <script>var points = [ 0, 2, 4, 6, 7.72, 9.11, 9.99 ]; var ScaleGener = d3.scaleLinear() .domain([0, 10]) .range([0, 600]); d3.select('svg .scal') .selectAll('circle') .data(points) .enter() .append('circle') .attr('r', 3) .attr('fill', "green") .attr('cx', function(d) { return ScaleGener(d); });</script></body></html> Output: Example 2: Setting text for each point. <!DOCTYPE html><html><meta charset="utf-8"><head> <title>Line in D3.js</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <center> <svg width="700" height="40"> <g class="scal" transform="translate(40, 30)"> </g> </svg></center> <script>var points = [ 0, 2, 4, 6, 7.72, 9.11, 9.99 ]; var ScaleGener = d3.scaleLinear() .domain([0, 10]) .range([0, 600]); d3.select('svg .scal') .selectAll('circle') .data(points) .enter() .append('circle') .attr('r', 3) .attr('fill', "green") .attr('cx', function(d) { return ScaleGener(d); }); d3.select('svg .scal') .selectAll('text') .data(points) .enter() .append('text') .attr('x', function(d) { return ScaleGener(d); }) .attr('y', -10) .text(function(d) { return d; }); </script></body></html> Output: D3.js HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? How to Insert Form Data into Database using PHP ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js How to calculate the number of days between two dates in javascript? Node.js | fs.writeFileSync() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Aug, 2020" }, { "code": null, "e": 164, "s": 28, "text": "The d3.scaleLinear() method is used to create a visual scale point. This method is used to transform data values into visual variables." }, { "code": null, "e": 172, "s": 164, "text": "Syntax:" }, { "code": null, "e": 190, "s": 172, "text": "d3.scaleLinear();" }, { "code": null, "e": 235, "s": 190, "text": "Parameters: This method takes no parameters." }, { "code": null, "e": 294, "s": 235, "text": "Return Value: This method returns a Linear scale function." }, { "code": null, "e": 328, "s": 294, "text": "Example 1: Plotting scale points." }, { "code": "<!DOCTYPE html><html><meta charset=\"utf-8\"><head> <title>Line in D3.js</title></head><script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"></script> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <center> <svg width=\"700\" height=\"40\"> <g class=\"scal\" transform=\"translate(40, 30)\"> </g> </svg></center> <script>var points = [ 0, 2, 4, 6, 7.72, 9.11, 9.99 ]; var ScaleGener = d3.scaleLinear() .domain([0, 10]) .range([0, 600]); d3.select('svg .scal') .selectAll('circle') .data(points) .enter() .append('circle') .attr('r', 3) .attr('fill', \"green\") .attr('cx', function(d) { return ScaleGener(d); });</script></body></html>", "e": 1074, "s": 328, "text": null }, { "code": null, "e": 1082, "s": 1074, "text": "Output:" }, { "code": null, "e": 1122, "s": 1082, "text": "Example 2: Setting text for each point." }, { "code": "<!DOCTYPE html><html><meta charset=\"utf-8\"><head> <title>Line in D3.js</title></head><script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"></script> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <center> <svg width=\"700\" height=\"40\"> <g class=\"scal\" transform=\"translate(40, 30)\"> </g> </svg></center> <script>var points = [ 0, 2, 4, 6, 7.72, 9.11, 9.99 ]; var ScaleGener = d3.scaleLinear() .domain([0, 10]) .range([0, 600]); d3.select('svg .scal') .selectAll('circle') .data(points) .enter() .append('circle') .attr('r', 3) .attr('fill', \"green\") .attr('cx', function(d) { return ScaleGener(d); }); d3.select('svg .scal') .selectAll('text') .data(points) .enter() .append('text') .attr('x', function(d) { return ScaleGener(d); }) .attr('y', -10) .text(function(d) { return d; }); </script></body></html>", "e": 2093, "s": 1122, "text": null }, { "code": null, "e": 2101, "s": 2093, "text": "Output:" }, { "code": null, "e": 2107, "s": 2101, "text": "D3.js" }, { "code": null, "e": 2112, "s": 2107, "text": "HTML" }, { "code": null, "e": 2123, "s": 2112, "text": "JavaScript" }, { "code": null, "e": 2140, "s": 2123, "text": "Web Technologies" }, { "code": null, "e": 2145, "s": 2140, "text": "HTML" }, { "code": null, "e": 2243, "s": 2145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2291, "s": 2243, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2328, "s": 2291, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2392, "s": 2328, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 2453, "s": 2392, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2503, "s": 2453, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2564, "s": 2503, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2636, "s": 2564, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2663, "s": 2636, "text": "File uploading in React.js" }, { "code": null, "e": 2732, "s": 2663, "text": "How to calculate the number of days between two dates in javascript?" } ]
How to skip blank and null values in MySQL?
To skip blank and null in MySQL, use the following syntax: select *from yourTableName where yourColumnName IS NOT NULL AND yourColumnName <> ''; Let us first create a table: mysql> create table DemoTable (Id int, FirstName varchar(20)); Query OK, 0 rows affected (0.66 sec) Following is the query to insert records in the table using insert command: mysql> insert into DemoTable values(100,'Larry'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(101,''); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(102,'Chris'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(103,null); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(104,' '); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(105,'Robert'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(106,null); Query OK, 1 row affected (0.13 sec) Following is the query to display records from the table using select command: mysql> select *from DemoTable; This will produce the following output with blank values and NULL: +------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Larry | | 101 | | | 102 | Chris | | 103 | NULL | | 104 | | | 105 | Robert | | 106 | NULL | +------+-----------+ 7 rows in set (0.00 sec) Following is the query to skip blank values as well as null in MySQL: mysql> select *from DemoTable where FirstName IS NOT NULL AND FirstName <> ''; This will produce the following output +------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Larry | | 102 | Chris | | 105 | Robert | +------+-----------+ 3 rows in set (0.03 sec)
[ { "code": null, "e": 1246, "s": 1187, "text": "To skip blank and null in MySQL, use the following syntax:" }, { "code": null, "e": 1332, "s": 1246, "text": "select *from yourTableName where yourColumnName IS NOT NULL AND yourColumnName <> '';" }, { "code": null, "e": 1361, "s": 1332, "text": "Let us first create a table:" }, { "code": null, "e": 1461, "s": 1361, "text": "mysql> create table DemoTable (Id int, FirstName varchar(20));\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1537, "s": 1461, "text": "Following is the query to insert records in the table using insert command:" }, { "code": null, "e": 2125, "s": 1537, "text": "mysql> insert into DemoTable values(100,'Larry');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(101,'');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(102,'Chris');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(103,null);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values(104,' ');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values(105,'Robert');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values(106,null);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2204, "s": 2125, "text": "Following is the query to display records from the table using select command:" }, { "code": null, "e": 2235, "s": 2204, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2302, "s": 2235, "text": "This will produce the following output with blank values and NULL:" }, { "code": null, "e": 2558, "s": 2302, "text": "+------+-----------+\n| Id | FirstName |\n+------+-----------+\n| 100 | Larry |\n| 101 | |\n| 102 | Chris |\n| 103 | NULL |\n| 104 | |\n| 105 | Robert |\n| 106 | NULL |\n+------+-----------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2628, "s": 2558, "text": "Following is the query to skip blank values as well as null in MySQL:" }, { "code": null, "e": 2707, "s": 2628, "text": "mysql> select *from DemoTable where FirstName IS NOT NULL AND FirstName <> '';" }, { "code": null, "e": 2746, "s": 2707, "text": "This will produce the following output" }, { "code": null, "e": 2918, "s": 2746, "text": "+------+-----------+\n| Id | FirstName |\n+------+-----------+\n| 100 | Larry |\n| 102 | Chris |\n| 105 | Robert |\n+------+-----------+\n3 rows in set (0.03 sec)" } ]
How to make bootstrap button transparent ?
22 Apr, 2020 Buttons can be made transparent in Bootstrap by using the built-in class property: Syntax: <button class="btn bg-transparent"> Transparent button </button> Description: The <button> tag is used to specify the button element in HTML, which gets executed on pressed. Generally, the properties of bootstrap must be mentioned in class. Example: class=” “ Inside the class=” ”btn – On mentioning the btn property, specifies that its a bootstrap button.bg – Specifies the background color of the button.transparent – Makes the button transparent. How to use it:Make sure, you have included the bootstrap code (Starter Template) in your code. Example: <!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Hello, world!</title></head> <body> <button class="btn bg-transparent"> Transparent button </button> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script></body> </html> Output:Before Pressing:After pressing: The documentation of Bootstrap is well-structured and easy to understand.Reference: Official Documentation Bootstrap-Misc Picked Bootstrap HTML Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 111, "s": 28, "text": "Buttons can be made transparent in Bootstrap by using the built-in class property:" }, { "code": null, "e": 119, "s": 111, "text": "Syntax:" }, { "code": null, "e": 188, "s": 119, "text": "<button class=\"btn bg-transparent\">\n Transparent button\n</button>" }, { "code": null, "e": 201, "s": 188, "text": "Description:" }, { "code": null, "e": 297, "s": 201, "text": "The <button> tag is used to specify the button element in HTML, which gets executed on pressed." }, { "code": null, "e": 383, "s": 297, "text": "Generally, the properties of bootstrap must be mentioned in class. Example: class=” “" }, { "code": null, "e": 573, "s": 383, "text": "Inside the class=” ”btn – On mentioning the btn property, specifies that its a bootstrap button.bg – Specifies the background color of the button.transparent – Makes the button transparent." }, { "code": null, "e": 668, "s": 573, "text": "How to use it:Make sure, you have included the bootstrap code (Starter Template) in your code." }, { "code": null, "e": 677, "s": 668, "text": "Example:" }, { "code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\"> <title>Hello, world!</title></head> <body> <button class=\"btn bg-transparent\"> Transparent button </button> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.4.1.slim.min.js\" integrity=\"sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n\" crossorigin=\"anonymous\"></script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\" integrity=\"sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6\" crossorigin=\"anonymous\"></script></body> </html>", "e": 2089, "s": 677, "text": null }, { "code": null, "e": 2128, "s": 2089, "text": "Output:Before Pressing:After pressing:" }, { "code": null, "e": 2235, "s": 2128, "text": "The documentation of Bootstrap is well-structured and easy to understand.Reference: Official Documentation" }, { "code": null, "e": 2250, "s": 2235, "text": "Bootstrap-Misc" }, { "code": null, "e": 2257, "s": 2250, "text": "Picked" }, { "code": null, "e": 2267, "s": 2257, "text": "Bootstrap" }, { "code": null, "e": 2272, "s": 2267, "text": "HTML" }, { "code": null, "e": 2289, "s": 2272, "text": "Web Technologies" }, { "code": null, "e": 2316, "s": 2289, "text": "Web technologies Questions" }, { "code": null, "e": 2332, "s": 2316, "text": "Write From Home" }, { "code": null, "e": 2337, "s": 2332, "text": "HTML" } ]
Get the YouTube video ID from a URL using JavaScript
31 May, 2019 Given a Youtube Video URL, The job is to get the Video ID from the URL using JavaScript. Here are few methods discussed. split() method:This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit) Parameters:separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value:Returns a new Array, having the splitted items. string.split(separator, limit) Parameters: separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item) limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array. Return value:Returns a new Array, having the splitted items. JavaScript String substring() Method:This method gets the characters from a string, between two defined indices, and returns the new substring.This method gets the characters in a string between “start” and “end”, excluding “end” itself.Syntax:string.substring(start, end) Parameters:start: This parameter is required. It specifies the position from where to start the extraction. Index of first character starts from 0.end: This parameter is optional. It specifies the position (including) where to stop the extraction. If not used, it extracts the whole string.Return value:it returns a new string containing the extracted characters. string.substring(start, end) Parameters: start: This parameter is required. It specifies the position from where to start the extraction. Index of first character starts from 0. end: This parameter is optional. It specifies the position (including) where to stop the extraction. If not used, it extracts the whole string. Return value:it returns a new string containing the extracted characters. Example 1: This example gets the Video ID by RegExp. <!DOCTYPE HTML><html> <head> <title> JavaScript | Get the YouTube video ID from a URL. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var url = 'https://youtu.be/BnJWi0E3Mv0'; up.innerHTML = "URL = " + url; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { VID_REGEX =/(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/; down.innerHTML = "ID = " + url.match(VID_REGEX)[1]; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example first splits the URL and then take a portion of the string by using split() and substring() method. <!DOCTYPE HTML><html> <head> <title> JavaScript | Get the YouTube video ID from a URL. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var url = 'https://www.youtube.com/watch?v=da9gTKWIivA'; up.innerHTML = "URL = " + url; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = "ID = " + url.split("v=")[1].substring(0, 11); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2019" }, { "code": null, "e": 149, "s": 28, "text": "Given a Youtube Video URL, The job is to get the Video ID from the URL using JavaScript. Here are few methods discussed." }, { "code": null, "e": 728, "s": 149, "text": "split() method:This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)\nParameters:separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value:Returns a new Array, having the splitted items." }, { "code": null, "e": 760, "s": 728, "text": "string.split(separator, limit)\n" }, { "code": null, "e": 772, "s": 760, "text": "Parameters:" }, { "code": null, "e": 976, "s": 772, "text": "separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)" }, { "code": null, "e": 1135, "s": 976, "text": "limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array." }, { "code": null, "e": 1196, "s": 1135, "text": "Return value:Returns a new Array, having the splitted items." }, { "code": null, "e": 1833, "s": 1196, "text": "JavaScript String substring() Method:This method gets the characters from a string, between two defined indices, and returns the new substring.This method gets the characters in a string between “start” and “end”, excluding “end” itself.Syntax:string.substring(start, end)\nParameters:start: This parameter is required. It specifies the position from where to start the extraction. Index of first character starts from 0.end: This parameter is optional. It specifies the position (including) where to stop the extraction. If not used, it extracts the whole string.Return value:it returns a new string containing the extracted characters." }, { "code": null, "e": 1863, "s": 1833, "text": "string.substring(start, end)\n" }, { "code": null, "e": 1875, "s": 1863, "text": "Parameters:" }, { "code": null, "e": 2012, "s": 1875, "text": "start: This parameter is required. It specifies the position from where to start the extraction. Index of first character starts from 0." }, { "code": null, "e": 2156, "s": 2012, "text": "end: This parameter is optional. It specifies the position (including) where to stop the extraction. If not used, it extracts the whole string." }, { "code": null, "e": 2230, "s": 2156, "text": "Return value:it returns a new string containing the extracted characters." }, { "code": null, "e": 2283, "s": 2230, "text": "Example 1: This example gets the Video ID by RegExp." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Get the YouTube video ID from a URL. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var url = 'https://youtu.be/BnJWi0E3Mv0'; up.innerHTML = \"URL = \" + url; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { VID_REGEX =/(?:youtube(?:-nocookie)?\\.com\\/(?:[^\\/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})/; down.innerHTML = \"ID = \" + url.match(VID_REGEX)[1]; } </script></body> </html>", "e": 3289, "s": 2283, "text": null }, { "code": null, "e": 3297, "s": 3289, "text": "Output:" }, { "code": null, "e": 3328, "s": 3297, "text": "Before clicking on the button:" }, { "code": null, "e": 3358, "s": 3328, "text": "After clicking on the button:" }, { "code": null, "e": 3482, "s": 3358, "text": "Example 2: This example first splits the URL and then take a portion of the string by using split() and substring() method." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Get the YouTube video ID from a URL. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var url = 'https://www.youtube.com/watch?v=da9gTKWIivA'; up.innerHTML = \"URL = \" + url; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { down.innerHTML = \"ID = \" + url.split(\"v=\")[1].substring(0, 11); } </script></body> </html>", "e": 4374, "s": 3482, "text": null }, { "code": null, "e": 4382, "s": 4374, "text": "Output:" }, { "code": null, "e": 4413, "s": 4382, "text": "Before clicking on the button:" }, { "code": null, "e": 4443, "s": 4413, "text": "After clicking on the button:" }, { "code": null, "e": 4459, "s": 4443, "text": "JavaScript-Misc" }, { "code": null, "e": 4470, "s": 4459, "text": "JavaScript" }, { "code": null, "e": 4487, "s": 4470, "text": "Web Technologies" }, { "code": null, "e": 4585, "s": 4487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4646, "s": 4585, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4718, "s": 4646, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4758, "s": 4718, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4800, "s": 4758, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4841, "s": 4800, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4874, "s": 4841, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4936, "s": 4874, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4997, "s": 4936, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5047, "s": 4997, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Convert list of string to list of list
25 Jun, 2022 Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to list to perform tasks is quite common in web development. Let’s discuss certain ways in which this can be performed. Method #1 : Using strip() + split() A combination of strip and split function can perform a particular task. The strip function can be used to get rid of the brackets and split function can make the data list comma-separated. Python3 # Python3 code to demonstrate# to convert list of string to list of list# using strip() + split() # initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint (& quot The original list is : & quot + str(test_list)) # using strip() + split()# to convert list of string to list of listres = [i.strip(& quot [] & quot ).split(" , & quot ) for i in test_list] # printing resultprint (& quot The list after conversion is : & quot + str(res)) Output : The original list is : ['[1, 4, 5]', '[4, 6, 8]'] The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']] Method #2 : Using list slicing and split() The task performed in the above method can also be performed using the list slicing in which we slice all the elements from second to second last element hence omitting the last brackets. Python3 # Python3 code to demonstrate# to convert the list of string to list of list# using list slicing + split() # initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint (& quot The original list is : & quot + str(test_list)) # using list slicing + split()# to convert list of string to list of listres = [i[1: -1].split(', ') for i in test_list] # printing resultprint (& quot The list after conversion is : & quot + str(res)) Output : The original list is : ['[1, 4, 5]', '[4, 6, 8]'] The list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']] Method#3 : Using re.findall and list comprehension This task can be performed using list comprehension for iterating over the list and re.findall function to make list with all element that matches pattern. Python3 # Python3 code to demonstrate# to convert list of string to list of list# using list comprehension + re.findallimport re# initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint("The original list is : " + str(test_list)) # using list comprehension + re.findall# to convert list of string to list of listres = [re.findall('[0-9]', i) for i in test_list] # printing resultprint("The list after conversion is : " + str(res)) Output: The original list is : ['[1, 4, 5]', '[4, 6, 8]'] The list after conversion is : [['1', '4', '5'], ['4', '6', '8']] Method#4: Using loop + eval() method This task can be performed with the help of this functions. Loop is used to iterate over the list and eval is used to parse the expression present in the string. Python3 # Python3 code to demonstrate# to convert list of string to list of list# using loop + eval functionsimport re# initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint("The original list is : " + str(test_list)) # using loop + eval functions# to convert list of string to list of listfor i in range(len(test_list)): test_list[i] = eval(test_list[i]) # printing resultprint("The list after conversion is : " + str(test_list)) Output: The original list is : ['[1, 4, 5]', '[4, 6, 8]'] The list after conversion is : [[1, 4, 5], [4, 6, 8]] nidhi_biet satyam00so Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jun, 2022" }, { "code": null, "e": 421, "s": 54, "text": "Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to list to perform tasks is quite common in web development. Let’s discuss certain ways in which this can be performed. " }, { "code": null, "e": 648, "s": 421, "text": "Method #1 : Using strip() + split() A combination of strip and split function can perform a particular task. The strip function can be used to get rid of the brackets and split function can make the data list comma-separated. " }, { "code": null, "e": 656, "s": 648, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to convert list of string to list of list# using strip() + split() # initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint (& quot The original list is : & quot + str(test_list)) # using strip() + split()# to convert list of string to list of listres = [i.strip(& quot [] & quot ).split(\" , & quot ) for i in test_list] # printing resultprint (& quot The list after conversion is : & quot + str(res))", "e": 1222, "s": 656, "text": null }, { "code": null, "e": 1231, "s": 1222, "text": "Output :" }, { "code": null, "e": 1351, "s": 1231, "text": "The original list is : ['[1, 4, 5]', '[4, 6, 8]']\nThe list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]" }, { "code": null, "e": 1584, "s": 1351, "text": "Method #2 : Using list slicing and split() The task performed in the above method can also be performed using the list slicing in which we slice all the elements from second to second last element hence omitting the last brackets. " }, { "code": null, "e": 1592, "s": 1584, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to convert the list of string to list of list# using list slicing + split() # initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint (& quot The original list is : & quot + str(test_list)) # using list slicing + split()# to convert list of string to list of listres = [i[1: -1].split(', ') for i in test_list] # printing resultprint (& quot The list after conversion is : & quot + str(res))", "e": 2073, "s": 1592, "text": null }, { "code": null, "e": 2082, "s": 2073, "text": "Output :" }, { "code": null, "e": 2202, "s": 2082, "text": "The original list is : ['[1, 4, 5]', '[4, 6, 8]']\nThe list after conversion is : [['1', ' 4', ' 5'], ['4', ' 6', ' 8']]" }, { "code": null, "e": 2410, "s": 2202, "text": "Method#3 : Using re.findall and list comprehension This task can be performed using list comprehension for iterating over the list and re.findall function to make list with all element that matches pattern. " }, { "code": null, "e": 2418, "s": 2410, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to convert list of string to list of list# using list comprehension + re.findallimport re# initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint(\"The original list is : \" + str(test_list)) # using list comprehension + re.findall# to convert list of string to list of listres = [re.findall('[0-9]', i) for i in test_list] # printing resultprint(\"The list after conversion is : \" + str(res))", "e": 2871, "s": 2418, "text": null }, { "code": null, "e": 2879, "s": 2871, "text": "Output:" }, { "code": null, "e": 2995, "s": 2879, "text": "The original list is : ['[1, 4, 5]', '[4, 6, 8]']\nThe list after conversion is : [['1', '4', '5'], ['4', '6', '8']]" }, { "code": null, "e": 3195, "s": 2995, "text": "Method#4: Using loop + eval() method This task can be performed with the help of this functions. Loop is used to iterate over the list and eval is used to parse the expression present in the string. " }, { "code": null, "e": 3203, "s": 3195, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to convert list of string to list of list# using loop + eval functionsimport re# initializing listtest_list = ['[1, 4, 5]', '[4, 6, 8]'] # printing original listprint(\"The original list is : \" + str(test_list)) # using loop + eval functions# to convert list of string to list of listfor i in range(len(test_list)): test_list[i] = eval(test_list[i]) # printing resultprint(\"The list after conversion is : \" + str(test_list))", "e": 3661, "s": 3203, "text": null }, { "code": null, "e": 3669, "s": 3661, "text": "Output:" }, { "code": null, "e": 3773, "s": 3669, "text": "The original list is : ['[1, 4, 5]', '[4, 6, 8]']\nThe list after conversion is : [[1, 4, 5], [4, 6, 8]]" }, { "code": null, "e": 3784, "s": 3773, "text": "nidhi_biet" }, { "code": null, "e": 3795, "s": 3784, "text": "satyam00so" }, { "code": null, "e": 3816, "s": 3795, "text": "Python list-programs" }, { "code": null, "e": 3828, "s": 3816, "text": "python-list" }, { "code": null, "e": 3835, "s": 3828, "text": "Python" }, { "code": null, "e": 3847, "s": 3835, "text": "python-list" }, { "code": null, "e": 3945, "s": 3847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3963, "s": 3945, "text": "Python Dictionary" }, { "code": null, "e": 4005, "s": 3963, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4027, "s": 4005, "text": "Enumerate() in Python" }, { "code": null, "e": 4053, "s": 4027, "text": "Python String | replace()" }, { "code": null, "e": 4085, "s": 4053, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4114, "s": 4085, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4141, "s": 4114, "text": "Python Classes and Objects" }, { "code": null, "e": 4162, "s": 4141, "text": "Python OOPs Concepts" }, { "code": null, "e": 4185, "s": 4162, "text": "Introduction To PYTHON" } ]
Schedule a Python Script on PythonAnywhere
23 Jan, 2020 Keeping the computer on 24/7 is not practical, so if you want to execute a Python script at a particular time every day, you probably need a computer that is ON all the time. To make this possible, a website PythonAnywhere gives you access to such a 24/7 computer. You can upload a Python script and schedule it to run at a certain time every day. This availability can be useful, for example, when you want to extract some values (e.g., weather data) from a website and generate a text file with the value or other reports every day. To schedule, a Python script for execution on PythonAnywhere, follow these simple steps: Sign up on here the account for Beginners is free with some T&C. Go to your Dashboard, Files, Upload a File and upload the Python file you want to schedule for execution. Go to Tasks and set the time of the day you want your script to be executed and type in the name of the Python file you uploaded (e.g., myfirstpyscript.py).Note: The time entered should be in UTC. Click “create” and you are done. The Python file will now be executed every day at your specified time. Example: Below is a very simple Python script you can use to schedule for execution. from datetime import datetime # Saves a .txt file with file name# as 2020-01-11-10-20-23.txtwith open(datetime.now().strftime("%Y-%m-%d-%H-%M-%S"), "w")as myfile: # Content of the file myfile.write("Hello World !") The above code creates a text file and writes the string “Hello World!” in that text file. The name of the text file will be the current date and time. For example one file name example would be 2020-01-11-10-20-23.txt. That name is generated by datetime.now() indicating the date and time the script was executed. Every time the script is executed, the script generates a new text file with a different name. You will have a new text file created every day. Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jan, 2020" }, { "code": null, "e": 587, "s": 52, "text": "Keeping the computer on 24/7 is not practical, so if you want to execute a Python script at a particular time every day, you probably need a computer that is ON all the time. To make this possible, a website PythonAnywhere gives you access to such a 24/7 computer. You can upload a Python script and schedule it to run at a certain time every day. This availability can be useful, for example, when you want to extract some values (e.g., weather data) from a website and generate a text file with the value or other reports every day." }, { "code": null, "e": 676, "s": 587, "text": "To schedule, a Python script for execution on PythonAnywhere, follow these simple steps:" }, { "code": null, "e": 741, "s": 676, "text": "Sign up on here the account for Beginners is free with some T&C." }, { "code": null, "e": 847, "s": 741, "text": "Go to your Dashboard, Files, Upload a File and upload the Python file you want to schedule for execution." }, { "code": null, "e": 1044, "s": 847, "text": "Go to Tasks and set the time of the day you want your script to be executed and type in the name of the Python file you uploaded (e.g., myfirstpyscript.py).Note: The time entered should be in UTC." }, { "code": null, "e": 1077, "s": 1044, "text": "Click “create” and you are done." }, { "code": null, "e": 1148, "s": 1077, "text": "The Python file will now be executed every day at your specified time." }, { "code": null, "e": 1233, "s": 1148, "text": "Example: Below is a very simple Python script you can use to schedule for execution." }, { "code": "from datetime import datetime # Saves a .txt file with file name# as 2020-01-11-10-20-23.txtwith open(datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"), \"w\")as myfile: # Content of the file myfile.write(\"Hello World !\")", "e": 1463, "s": 1233, "text": null }, { "code": null, "e": 1683, "s": 1463, "text": "The above code creates a text file and writes the string “Hello World!” in that text file. The name of the text file will be the current date and time. For example one file name example would be 2020-01-11-10-20-23.txt." }, { "code": null, "e": 1922, "s": 1683, "text": "That name is generated by datetime.now() indicating the date and time the script was executed. Every time the script is executed, the script generates a new text file with a different name. You will have a new text file created every day." }, { "code": null, "e": 1943, "s": 1922, "text": "Python-Miscellaneous" }, { "code": null, "e": 1950, "s": 1943, "text": "Python" } ]
Center any element in Bootstrap
Use the .center-block class in Bootstrap to center an element. You can try to run the following code to implement the .center-block class: Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h1>Heading One</h1> <div class = "center-block" style = "background-color:green;color: white; width:200px;">Text will be in center.</div> </div> </body> </html>
[ { "code": null, "e": 1250, "s": 1187, "text": "Use the .center-block class in Bootstrap to center an element." }, { "code": null, "e": 1326, "s": 1250, "text": "You can try to run the following code to implement the .center-block class:" }, { "code": null, "e": 1336, "s": 1326, "text": "Live Demo" }, { "code": null, "e": 1842, "s": 1336, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h1>Heading One</h1>\n <div class = \"center-block\" style = \"background-color:green;color: white; width:200px;\">Text will be in center.</div>\n </div>\n </body>\n</html>" } ]
How to get properties of Python cv2.VideoCapture object ? - GeeksforGeeks
25 Nov, 2021 Let us see how we can get the properties from the cv2.VideoCapture objects and understand how they work. cv2.VideoCapture is a function of openCV library(used for computer vision, machine learning, and image processing) which allows working with video either by capturing via live webcam or by a video file. To know more about this function, refer to this link. Before we start, make sure to install the OpenCV library on Python 3.X. You can install these using the pip command: pip install opencv-python By knowing the properties of the cv2.VideoCapture object facilitates to do Video Processing ultimately by doing processing on the frames. 1) Width: This property is used to get the width of the frames in the video stream. The measuring unit is in pixels. Syntax: cv2.CAP_PROP_FRAME_WIDTH 2) Height: This property is used to get the height of the frames in the video stream. The measuring unit is in pixels. Syntax: cv2.CAP_PROP_FRAME_HEIGHT 3) Fps: FPS stands for frames per second. This property is used to get the frame rate of the video. Syntax: cv2.CAP_PROP_FPS 4) Current Position: This property is used to find what is the current position of the video, its measuring unit is milliseconds. Syntax: cv2.CAP_PROP_POS_MSEC 5) Total number of frame: This property is used to calculate the total number of frames in the video file. Syntax: cv2.CAP_PROP_FRAME_COUNT 6) Brightness: This property is not for video files. It only works with a camera or webcam. Used to find out the brightness. Syntax: cv2.CAP_PROP_BRIGHTNESS 7) Contrast: This property also works with the camera or webcam only. Used to find out the contrast on images captured. Syntax: cv2.CAP_PROP_CONTRAST 8) Saturation Value: This is used to get the saturation of live frames capturing via cameras. This also doesn’t work on the video file. Syntax: cv2.CAP_PROP_SATURATION 9) HUE Value: This is for knowing the HUE value of the image. Only for cameras. Syntax: cv2.CAP_PROP_HUE 10) GAIN: This property is used to get the gain of the image. Wouldn’t work with the video file, simply return “0” if applied on a video file. Syntax: cv2.CAP_PROP_GAIN 11) Need to convert into RGB: This property returns a Boolean value which indicates whether the images should be converted to RGB colorspace or not. Syntax: cv2.CAP_PROP_CONVERT_RGB These properties will be much clear on using these directly on the code. Here’s its implementation: Python3 # importing cv2import cv2 #For Video File#capture=cv2.VideoCapture("sample.webm") #For webcamcapture=cv2.VideoCapture(0) # showing values of the propertiesprint("CV_CAP_PROP_FRAME_WIDTH: '{}'".format(capture.get(cv2.CAP_PROP_FRAME_WIDTH)))print("CV_CAP_PROP_FRAME_HEIGHT : '{}'".format(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))print("CAP_PROP_FPS : '{}'".format(capture.get(cv2.CAP_PROP_FPS)))print("CAP_PROP_POS_MSEC : '{}'".format(capture.get(cv2.CAP_PROP_POS_MSEC)))print("CAP_PROP_FRAME_COUNT : '{}'".format(capture.get(cv2.CAP_PROP_FRAME_COUNT)))print("CAP_PROP_BRIGHTNESS : '{}'".format(capture.get(cv2.CAP_PROP_BRIGHTNESS)))print("CAP_PROP_CONTRAST : '{}'".format(capture.get(cv2.CAP_PROP_CONTRAST)))print("CAP_PROP_SATURATION : '{}'".format(capture.get(cv2.CAP_PROP_SATURATION)))print("CAP_PROP_HUE : '{}'".format(capture.get(cv2.CAP_PROP_HUE)))print("CAP_PROP_GAIN : '{}'".format(capture.get(cv2.CAP_PROP_GAIN)))print("CAP_PROP_CONVERT_RGB : '{}'".format(capture.get(cv2.CAP_PROP_CONVERT_RGB))) # release windowcapture.release()cv2.destroyAllWindows() Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n25 Nov, 2021" }, { "code": null, "e": 24265, "s": 23901, "text": "Let us see how we can get the properties from the cv2.VideoCapture objects and understand how they work. cv2.VideoCapture is a function of openCV library(used for computer vision, machine learning, and image processing) which allows working with video either by capturing via live webcam or by a video file. To know more about this function, refer to this link. " }, { "code": null, "e": 24382, "s": 24265, "text": "Before we start, make sure to install the OpenCV library on Python 3.X. You can install these using the pip command:" }, { "code": null, "e": 24408, "s": 24382, "text": "pip install opencv-python" }, { "code": null, "e": 24547, "s": 24408, "text": "By knowing the properties of the cv2.VideoCapture object facilitates to do Video Processing ultimately by doing processing on the frames. " }, { "code": null, "e": 24666, "s": 24547, "text": "1) Width: This property is used to get the width of the frames in the video stream. The measuring unit is in pixels. " }, { "code": null, "e": 24699, "s": 24666, "text": "Syntax: cv2.CAP_PROP_FRAME_WIDTH" }, { "code": null, "e": 24818, "s": 24699, "text": "2) Height: This property is used to get the height of the frames in the video stream. The measuring unit is in pixels." }, { "code": null, "e": 24853, "s": 24818, "text": "Syntax: cv2.CAP_PROP_FRAME_HEIGHT " }, { "code": null, "e": 24953, "s": 24853, "text": "3) Fps: FPS stands for frames per second. This property is used to get the frame rate of the video." }, { "code": null, "e": 24978, "s": 24953, "text": "Syntax: cv2.CAP_PROP_FPS" }, { "code": null, "e": 25108, "s": 24978, "text": "4) Current Position: This property is used to find what is the current position of the video, its measuring unit is milliseconds." }, { "code": null, "e": 25138, "s": 25108, "text": "Syntax: cv2.CAP_PROP_POS_MSEC" }, { "code": null, "e": 25245, "s": 25138, "text": "5) Total number of frame: This property is used to calculate the total number of frames in the video file." }, { "code": null, "e": 25280, "s": 25245, "text": " Syntax: cv2.CAP_PROP_FRAME_COUNT" }, { "code": null, "e": 25405, "s": 25280, "text": "6) Brightness: This property is not for video files. It only works with a camera or webcam. Used to find out the brightness." }, { "code": null, "e": 25437, "s": 25405, "text": "Syntax: cv2.CAP_PROP_BRIGHTNESS" }, { "code": null, "e": 25557, "s": 25437, "text": "7) Contrast: This property also works with the camera or webcam only. Used to find out the contrast on images captured." }, { "code": null, "e": 25587, "s": 25557, "text": "Syntax: cv2.CAP_PROP_CONTRAST" }, { "code": null, "e": 25723, "s": 25587, "text": "8) Saturation Value: This is used to get the saturation of live frames capturing via cameras. This also doesn’t work on the video file." }, { "code": null, "e": 25755, "s": 25723, "text": "Syntax: cv2.CAP_PROP_SATURATION" }, { "code": null, "e": 25835, "s": 25755, "text": "9) HUE Value: This is for knowing the HUE value of the image. Only for cameras." }, { "code": null, "e": 25860, "s": 25835, "text": "Syntax: cv2.CAP_PROP_HUE" }, { "code": null, "e": 26004, "s": 25860, "text": "10) GAIN: This property is used to get the gain of the image. Wouldn’t work with the video file, simply return “0” if applied on a video file." }, { "code": null, "e": 26030, "s": 26004, "text": "Syntax: cv2.CAP_PROP_GAIN" }, { "code": null, "e": 26179, "s": 26030, "text": "11) Need to convert into RGB: This property returns a Boolean value which indicates whether the images should be converted to RGB colorspace or not." }, { "code": null, "e": 26212, "s": 26179, "text": "Syntax: cv2.CAP_PROP_CONVERT_RGB" }, { "code": null, "e": 26312, "s": 26212, "text": "These properties will be much clear on using these directly on the code. Here’s its implementation:" }, { "code": null, "e": 26320, "s": 26312, "text": "Python3" }, { "code": "# importing cv2import cv2 #For Video File#capture=cv2.VideoCapture(\"sample.webm\") #For webcamcapture=cv2.VideoCapture(0) # showing values of the propertiesprint(\"CV_CAP_PROP_FRAME_WIDTH: '{}'\".format(capture.get(cv2.CAP_PROP_FRAME_WIDTH)))print(\"CV_CAP_PROP_FRAME_HEIGHT : '{}'\".format(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))print(\"CAP_PROP_FPS : '{}'\".format(capture.get(cv2.CAP_PROP_FPS)))print(\"CAP_PROP_POS_MSEC : '{}'\".format(capture.get(cv2.CAP_PROP_POS_MSEC)))print(\"CAP_PROP_FRAME_COUNT : '{}'\".format(capture.get(cv2.CAP_PROP_FRAME_COUNT)))print(\"CAP_PROP_BRIGHTNESS : '{}'\".format(capture.get(cv2.CAP_PROP_BRIGHTNESS)))print(\"CAP_PROP_CONTRAST : '{}'\".format(capture.get(cv2.CAP_PROP_CONTRAST)))print(\"CAP_PROP_SATURATION : '{}'\".format(capture.get(cv2.CAP_PROP_SATURATION)))print(\"CAP_PROP_HUE : '{}'\".format(capture.get(cv2.CAP_PROP_HUE)))print(\"CAP_PROP_GAIN : '{}'\".format(capture.get(cv2.CAP_PROP_GAIN)))print(\"CAP_PROP_CONVERT_RGB : '{}'\".format(capture.get(cv2.CAP_PROP_CONVERT_RGB))) # release windowcapture.release()cv2.destroyAllWindows()", "e": 27386, "s": 26320, "text": null }, { "code": null, "e": 27400, "s": 27386, "text": "Python-OpenCV" }, { "code": null, "e": 27407, "s": 27400, "text": "Python" }, { "code": null, "e": 27505, "s": 27407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27514, "s": 27505, "text": "Comments" }, { "code": null, "e": 27527, "s": 27514, "text": "Old Comments" }, { "code": null, "e": 27559, "s": 27527, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27615, "s": 27559, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27657, "s": 27615, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27699, "s": 27657, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27735, "s": 27699, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27757, "s": 27735, "text": "Defaultdict in Python" }, { "code": null, "e": 27796, "s": 27757, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27823, "s": 27796, "text": "Python Classes and Objects" }, { "code": null, "e": 27854, "s": 27823, "text": "Python | os.path.join() method" } ]
Is it possible to resume java execution after exception occurs?
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. There are two types of exceptions in Java. Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions. When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program. import java.io.File; import java.io.FileInputStream; public class Test { public static void main(String args[]){ System.out.println("Hello"); try{ File file =new File("my_file"); FileInputStream fis = new FileInputStream(file); }catch(Exception e){ System.out.println("Given file path is not found"); } } } Given file path is not found When a run time exception occurs You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code. public class ExceptionExample { public static void main(String[] args) { //Creating an integer array with size 5 int inpuArray[] = new int[5]; //Populating the array inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //Accessing index greater than the size of the array System.out.println( inpuArray[3]); } } 26
[ { "code": null, "e": 1290, "s": 1062, "text": "An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed." }, { "code": null, "e": 1333, "s": 1290, "text": "There are two types of exceptions in Java." }, { "code": null, "e": 1612, "s": 1333, "text": "Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation." }, { "code": null, "e": 1890, "s": 1612, "text": "Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions." }, { "code": null, "e": 2120, "s": 1890, "text": "When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program." }, { "code": null, "e": 2484, "s": 2120, "text": "import java.io.File;\nimport java.io.FileInputStream;\npublic class Test {\n public static void main(String args[]){\n System.out.println(\"Hello\");\n try{\n File file =new File(\"my_file\");\n FileInputStream fis = new FileInputStream(file);\n }catch(Exception e){\n System.out.println(\"Given file path is not found\");\n }\n }\n}" }, { "code": null, "e": 2513, "s": 2484, "text": "Given file path is not found" }, { "code": null, "e": 2735, "s": 2513, "text": "When a run time exception occurs You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code." }, { "code": null, "e": 3154, "s": 2735, "text": "public class ExceptionExample {\n public static void main(String[] args) {\n //Creating an integer array with size 5\n int inpuArray[] = new int[5];\n //Populating the array\n inpuArray[0] = 41;\n inpuArray[1] = 98;\n inpuArray[2] = 43;\n inpuArray[3] = 26;\n inpuArray[4] = 79;\n //Accessing index greater than the size of the array\n System.out.println( inpuArray[3]);\n }\n}" }, { "code": null, "e": 3157, "s": 3154, "text": "26" } ]
Count number of equal pairs in a string - GeeksforGeeks
31 Dec, 2019 Given a string s, find the number of pairs of characters that are same. Pairs (s[i], s[j]), (s[j], s[i]), (s[i], s[i]), (s[j], s[j]) should be considered different. Examples : Input: air Output: 3 Explanation : 3 pairs that are equal are (a, a), (i, i) and (r, r) Input : geeksforgeeks Output : 31 The naive approach will be you to run two nested for loops and find out all pairs and keep a count of all pairs. But this is not efficient enough for longer length of strings. For an efficient approach, we need to count the number of equal pairs in linear time. Since pairs (x, y) and pairs (y, x) are considered different. We need to use a hash table to store the count of all occurrences of a character.So we know if a character occurs twice, then it will have 4 pairs – (i, i), (j, j), (i, j), (j, i). So using a hash function, store the occurrence of each character, then for each character the number of pairs will be occurrence^2. Hash table will be 256 in length as we have 256 characters. Below is the implementation of the above approach : C++ Java Python 3 C# // CPP program to count the number of pairs#include <bits/stdc++.h>using namespace std;#define MAX 256 // Function to count the number of equal pairsint countPairs(string s){ // Hash table int cnt[MAX] = { 0 }; // Traverse the string and count occurrence for (int i = 0; i < s.length(); i++) cnt[s[i]]++; // Stores the answer int ans = 0; // Traverse and check the occurrence of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans;} // Driver Codeint main(){ string s = "geeksforgeeks"; cout << countPairs(s); return 0;} // Java program to count the number of pairsimport java.io.*; class GFG { static int MAX = 256; // Function to count the number of equal pairs static int countPairs(String s) { // Hash table int cnt[] = new int[MAX]; // Traverse the string and count occurrence for (int i = 0; i < s.length(); i++) cnt[s.charAt(i)]++; // Stores the answer int ans = 0; // Traverse and check the occurrence // of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans; } // Driver Code public static void main (String[] args) { String s = "geeksforgeeks"; System.out.println(countPairs(s)); }} // This code is contributed by vt_m # Python3 program to count the # number of pairs MAX = 256 # Function to count the number # of equal pairsdef countPairs(s): # Hash table cnt = [0 for i in range(0, MAX)] # Traverse the string and count # occurrence for i in range(len(s)): cnt[ord(s[i]) - 97] += 1 # Stores the answer ans = 0 # Traverse and check the occurrence # of every character for i in range(0, MAX): ans += cnt[i] * cnt[i] return ans # Driver code if __name__=="__main__": s = "geeksforgeeks" print(countPairs(s)) # This code is contributed # by Sairahul099 // C# program to count the number of pairsusing System; class GFG { static int MAX = 256; // Function to count the number of equal pairs static int countPairs(string s) { // Hash table int []cnt = new int[MAX]; // Traverse the string and count occurrence for (int i = 0; i < s.Length; i++) cnt[s[i]]++; // Stores the answer int ans = 0; // Traverse and check the occurrence // of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans; } // Driver Code public static void Main () { string s = "geeksforgeeks"; Console.WriteLine(countPairs(s)); }} // This code is contributed by vt_m 31 Sairahul Jella nidhi_biet frequency-counting Combinatorial Strings Strings Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Print all subsets of given size of a set Make all combinations of size k Python program to get all subsets of given size of a set Count Derangements (Permutation such that no element appears in its original position) Combinations with repetitions Reverse a string in Java Write a program to reverse an array or string C++ Data Types Longest Common Subsequence | DP-4 Different methods to reverse a string in C/C++
[ { "code": null, "e": 25255, "s": 25227, "text": "\n31 Dec, 2019" }, { "code": null, "e": 25420, "s": 25255, "text": "Given a string s, find the number of pairs of characters that are same. Pairs (s[i], s[j]), (s[j], s[i]), (s[i], s[i]), (s[j], s[j]) should be considered different." }, { "code": null, "e": 25431, "s": 25420, "text": "Examples :" }, { "code": null, "e": 25555, "s": 25431, "text": "Input: air\nOutput: 3\nExplanation :\n3 pairs that are equal are (a, a), (i, i) and (r, r)\n\nInput : geeksforgeeks\nOutput : 31\n" }, { "code": null, "e": 25731, "s": 25555, "text": "The naive approach will be you to run two nested for loops and find out all pairs and keep a count of all pairs. But this is not efficient enough for longer length of strings." }, { "code": null, "e": 26252, "s": 25731, "text": "For an efficient approach, we need to count the number of equal pairs in linear time. Since pairs (x, y) and pairs (y, x) are considered different. We need to use a hash table to store the count of all occurrences of a character.So we know if a character occurs twice, then it will have 4 pairs – (i, i), (j, j), (i, j), (j, i). So using a hash function, store the occurrence of each character, then for each character the number of pairs will be occurrence^2. Hash table will be 256 in length as we have 256 characters." }, { "code": null, "e": 26304, "s": 26252, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 26308, "s": 26304, "text": "C++" }, { "code": null, "e": 26313, "s": 26308, "text": "Java" }, { "code": null, "e": 26322, "s": 26313, "text": "Python 3" }, { "code": null, "e": 26325, "s": 26322, "text": "C#" }, { "code": "// CPP program to count the number of pairs#include <bits/stdc++.h>using namespace std;#define MAX 256 // Function to count the number of equal pairsint countPairs(string s){ // Hash table int cnt[MAX] = { 0 }; // Traverse the string and count occurrence for (int i = 0; i < s.length(); i++) cnt[s[i]]++; // Stores the answer int ans = 0; // Traverse and check the occurrence of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans;} // Driver Codeint main(){ string s = \"geeksforgeeks\"; cout << countPairs(s); return 0;}", "e": 26935, "s": 26325, "text": null }, { "code": "// Java program to count the number of pairsimport java.io.*; class GFG { static int MAX = 256; // Function to count the number of equal pairs static int countPairs(String s) { // Hash table int cnt[] = new int[MAX]; // Traverse the string and count occurrence for (int i = 0; i < s.length(); i++) cnt[s.charAt(i)]++; // Stores the answer int ans = 0; // Traverse and check the occurrence // of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans; } // Driver Code public static void main (String[] args) { String s = \"geeksforgeeks\"; System.out.println(countPairs(s)); }} // This code is contributed by vt_m", "e": 27746, "s": 26935, "text": null }, { "code": "# Python3 program to count the # number of pairs MAX = 256 # Function to count the number # of equal pairsdef countPairs(s): # Hash table cnt = [0 for i in range(0, MAX)] # Traverse the string and count # occurrence for i in range(len(s)): cnt[ord(s[i]) - 97] += 1 # Stores the answer ans = 0 # Traverse and check the occurrence # of every character for i in range(0, MAX): ans += cnt[i] * cnt[i] return ans # Driver code if __name__==\"__main__\": s = \"geeksforgeeks\" print(countPairs(s)) # This code is contributed # by Sairahul099 ", "e": 28363, "s": 27746, "text": null }, { "code": "// C# program to count the number of pairsusing System; class GFG { static int MAX = 256; // Function to count the number of equal pairs static int countPairs(string s) { // Hash table int []cnt = new int[MAX]; // Traverse the string and count occurrence for (int i = 0; i < s.Length; i++) cnt[s[i]]++; // Stores the answer int ans = 0; // Traverse and check the occurrence // of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans; } // Driver Code public static void Main () { string s = \"geeksforgeeks\"; Console.WriteLine(countPairs(s)); }} // This code is contributed by vt_m", "e": 29145, "s": 28363, "text": null }, { "code": null, "e": 29149, "s": 29145, "text": "31\n" }, { "code": null, "e": 29164, "s": 29149, "text": "Sairahul Jella" }, { "code": null, "e": 29175, "s": 29164, "text": "nidhi_biet" }, { "code": null, "e": 29194, "s": 29175, "text": "frequency-counting" }, { "code": null, "e": 29208, "s": 29194, "text": "Combinatorial" }, { "code": null, "e": 29216, "s": 29208, "text": "Strings" }, { "code": null, "e": 29224, "s": 29216, "text": "Strings" }, { "code": null, "e": 29238, "s": 29224, "text": "Combinatorial" }, { "code": null, "e": 29336, "s": 29238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29345, "s": 29336, "text": "Comments" }, { "code": null, "e": 29358, "s": 29345, "text": "Old Comments" }, { "code": null, "e": 29399, "s": 29358, "text": "Print all subsets of given size of a set" }, { "code": null, "e": 29431, "s": 29399, "text": "Make all combinations of size k" }, { "code": null, "e": 29488, "s": 29431, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 29575, "s": 29488, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 29605, "s": 29575, "text": "Combinations with repetitions" }, { "code": null, "e": 29630, "s": 29605, "text": "Reverse a string in Java" }, { "code": null, "e": 29676, "s": 29630, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 29691, "s": 29676, "text": "C++ Data Types" }, { "code": null, "e": 29725, "s": 29691, "text": "Longest Common Subsequence | DP-4" } ]
A Tutorial on Luigi, the Spotify’s Pipeline | Towards Data Science
Luigi is a Python (2.7, 3.6, 3.7 tested) package that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization, handling failures, command line integration, and much more. Intro Pros and Cons Pipeline Structure:. Tasks. Targets. Parameters Building Blocks Execute it My experience with Luigi started a few years ago, when the sole person in charge of the company pipeline left, and I got “gifted” with a massive legacy codebase. At the time, I had no knowledge about pipelines in general, or Luigi in particular, so I started looking for tutorials and reading the official documentation in full. I didn’t find it particularly useful; it is, of course, factually correct, but it is not a tutorial. Nor, at the time, were many courses or blogs about it. This article, therefore, is my attempt to fill this gap. I’ve collected what learnt, and it will hopefully help you during your first steps with the Luigi package Before we dive into the code, let’s see the strengths and weaknesses of this package. The Luigi pipeline library has been designed and still used by Spotify. Over the years it has been adopted by other companies, notably like Deliveroo. But, exactly, because it was tailor-made for Spotify, it might not be suited to solve your need and I advise you to consider carefully if this system can work for you. It is Python! Thus, first, you already know how to code in it, plus you can blend the process that you want to automatize (your original code) with the pipeline infrastructure (thus, Luigi) Its “backward” structure allows it to recover from failed tasks without re-running the whole pipeline. An AWS batch wrapper to work directly with Amazon ECS. A GUI showing status of the tasks and graphical representation of your pipeline. It is hard to test. It has a central scheduler that makes it hard to parallelize tasks. It needs to be kept simple, or better linear (try to keep it <1k tasks). Too many branches and forks can slow the run time incredibly. There is no trigger. Thus, the pipeline won’t start when the needed files are in place, but you need to set up a cronjob to check them and make the pipeline start If you have decided to start using Luigi, run pip install luigi on your terminal, and let’s start to see how it works The structure of a pipeline in Luigi, like one of many pipeline systems, resembles that of a graph. It contains nodes, where information is processed and edges connecting the nodes, transferring the information to the next node. This process would, normally, follow a linear flow, in which the first node is considered the start node, this is the first to be executed, followed by a second, then a third until the end-node completes the workflow. Something resembling this: Start -> Node A -> Node B -> Node C -> End Instead, in Luigi, this process is reversed! The program starts from the last task, it checks if it can be executed or if it requires anything. If that is the case, it moves up to the pipeline until it finds a node that has all requirements satisfied, and only then, it starts running the nodes already visited. Like in the following: Start -> Node C -> Node B -> Node A -> Node B -> Node C -> End This methodology could seem counterintuitive at first, but it actually helps to avoid rerunning nodes already executed after a failure or error appears. Let’s image to run our pipeline a first time, and in this first run Node B fails: Start -> Node C-> Node B -> Node A (Done) -> Node B (Error) -X-> Node C -> End After we have manually fixed the error in Node B the pipeline can run again but, in this occasion, it will not consider Node A Start -> Node C-> Node B -> Node C-> Node. Avoiding running it entirely. As mentioned, the Luigi package works like a graph. The nodes in Luigi are called Tasks and the edges are called Targets Tasks are the basic building blocks of Luigi and where the real work actually happens. To create a task you have to create a class and inherit the class luigi.Task. Within the new class, there are contained at least one or all, of the following methods: requires() run() output() targets The method requires() is the first method that is executed, if present. It contains all the instances that have been executed before the current task. Most commonly this method makes a call to another Luigi Task above the workflow, allowing the code to move backward to the beginning of the pipeline. If we saw earlier that Targets are what connect a Task to the next requires() is what connects the Task to the previous one. Targets move the code to the end, required to the beginning. Only when a method requires is satisfied that Task can execute the second method run: In this method is contained the action that the task has to execute. It can be anything, a call to another method, the running of a script, etc. An example of a Task in Luigi with the two previous model would be: class MakeTaskA(luigi.Task): def requires(self): return MakeTaskB() def run(self): return luigi.LocalTarget(DoSomething()) The method output() as the name suggests return one or more Target objects. Although, it is recommended that any Task only return one single Target in output. Example A good example is present in the Luigi documentation: In this example, The first Task is CountLetters(), it requires the class GenerateWords() so it moves there GenerateWords() has no requires so it calls it’s run() method and it creates a file calls “words.txt” It’s the turn of output(). This method finds the file word.txt and it returns it in the form of a LocalTarget class object, back to the class CountLetters CountLetters() can execute run(), now. It takes what needed from self.input() Afterword, it execute output() Task.input() is a wrapper around Task.requires() that returns the corresponding Target objects instead of Task objects. Target is the edge connecting a Tasks to the next. These are usually represented as a file. Indeed, we have already seen one in the previous example. The file ‘hello.txt’ was a Target. A Task can be considered complete if and only if each of its output Targets exist. They can be as simple as empty files, an S3 or whatever. The last important element that we saw in the example, but we did not consider yet, are the Parameters. Parameters are in Luigi, the equivalent of creating a constructor for each Task. Those are instance variables of a class. Only one instance is created for each set of parameters. Personally, it reminds me of when in Java or C++, you have to declare variables, I know they are not the same thing, but it can help to understand the use of it. You can declare a parameter in the following way: class MakeSomething(luigi.Task): string = luigi.Parameter(default='hello world!') Now, we have a class with a parameter attribute ‘hello world!’ string. You can pass parameters back and forth between tasks. Besides the one seen above, there are different subclasses of Parameters: There are a few of them: DateParameter, DateIntervalParameter, IntParameter, FloatParameter, etc. These provide methods for serialization and reading, you can make your own ones. However, you are not obligated to specify the type of parameter. You can simply use the base class Parameter. The reason you would use a subclass like DateParameter is that Luigi needs to perform a conversion for the command line interaction. That is how it knows how to convert a string provided on the command line to the corresponding type (i.e. datetime.date instead of a string). To execute the code, type the following from your command line: python -m luigi — module file_name TaskName — local-schedule I hope that this article helps you to move your first steps with Luigi
[ { "code": null, "e": 404, "s": 171, "text": "Luigi is a Python (2.7, 3.6, 3.7 tested) package that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization, handling failures, command line integration, and much more." }, { "code": null, "e": 410, "s": 404, "text": "Intro" }, { "code": null, "e": 424, "s": 410, "text": "Pros and Cons" }, { "code": null, "e": 472, "s": 424, "text": "Pipeline Structure:. Tasks. Targets. Parameters" }, { "code": null, "e": 488, "s": 472, "text": "Building Blocks" }, { "code": null, "e": 499, "s": 488, "text": "Execute it" }, { "code": null, "e": 661, "s": 499, "text": "My experience with Luigi started a few years ago, when the sole person in charge of the company pipeline left, and I got “gifted” with a massive legacy codebase." }, { "code": null, "e": 828, "s": 661, "text": "At the time, I had no knowledge about pipelines in general, or Luigi in particular, so I started looking for tutorials and reading the official documentation in full." }, { "code": null, "e": 984, "s": 828, "text": "I didn’t find it particularly useful; it is, of course, factually correct, but it is not a tutorial. Nor, at the time, were many courses or blogs about it." }, { "code": null, "e": 1147, "s": 984, "text": "This article, therefore, is my attempt to fill this gap. I’ve collected what learnt, and it will hopefully help you during your first steps with the Luigi package" }, { "code": null, "e": 1233, "s": 1147, "text": "Before we dive into the code, let’s see the strengths and weaknesses of this package." }, { "code": null, "e": 1552, "s": 1233, "text": "The Luigi pipeline library has been designed and still used by Spotify. Over the years it has been adopted by other companies, notably like Deliveroo. But, exactly, because it was tailor-made for Spotify, it might not be suited to solve your need and I advise you to consider carefully if this system can work for you." }, { "code": null, "e": 1742, "s": 1552, "text": "It is Python! Thus, first, you already know how to code in it, plus you can blend the process that you want to automatize (your original code) with the pipeline infrastructure (thus, Luigi)" }, { "code": null, "e": 1845, "s": 1742, "text": "Its “backward” structure allows it to recover from failed tasks without re-running the whole pipeline." }, { "code": null, "e": 1900, "s": 1845, "text": "An AWS batch wrapper to work directly with Amazon ECS." }, { "code": null, "e": 1981, "s": 1900, "text": "A GUI showing status of the tasks and graphical representation of your pipeline." }, { "code": null, "e": 2001, "s": 1981, "text": "It is hard to test." }, { "code": null, "e": 2069, "s": 2001, "text": "It has a central scheduler that makes it hard to parallelize tasks." }, { "code": null, "e": 2204, "s": 2069, "text": "It needs to be kept simple, or better linear (try to keep it <1k tasks). Too many branches and forks can slow the run time incredibly." }, { "code": null, "e": 2367, "s": 2204, "text": "There is no trigger. Thus, the pipeline won’t start when the needed files are in place, but you need to set up a cronjob to check them and make the pipeline start" }, { "code": null, "e": 2413, "s": 2367, "text": "If you have decided to start using Luigi, run" }, { "code": null, "e": 2431, "s": 2413, "text": "pip install luigi" }, { "code": null, "e": 2485, "s": 2431, "text": "on your terminal, and let’s start to see how it works" }, { "code": null, "e": 2714, "s": 2485, "text": "The structure of a pipeline in Luigi, like one of many pipeline systems, resembles that of a graph. It contains nodes, where information is processed and edges connecting the nodes, transferring the information to the next node." }, { "code": null, "e": 2959, "s": 2714, "text": "This process would, normally, follow a linear flow, in which the first node is considered the start node, this is the first to be executed, followed by a second, then a third until the end-node completes the workflow. Something resembling this:" }, { "code": null, "e": 3002, "s": 2959, "text": "Start -> Node A -> Node B -> Node C -> End" }, { "code": null, "e": 3047, "s": 3002, "text": "Instead, in Luigi, this process is reversed!" }, { "code": null, "e": 3146, "s": 3047, "text": "The program starts from the last task, it checks if it can be executed or if it requires anything." }, { "code": null, "e": 3337, "s": 3146, "text": "If that is the case, it moves up to the pipeline until it finds a node that has all requirements satisfied, and only then, it starts running the nodes already visited. Like in the following:" }, { "code": null, "e": 3400, "s": 3337, "text": "Start -> Node C -> Node B -> Node A -> Node B -> Node C -> End" }, { "code": null, "e": 3553, "s": 3400, "text": "This methodology could seem counterintuitive at first, but it actually helps to avoid rerunning nodes already executed after a failure or error appears." }, { "code": null, "e": 3635, "s": 3553, "text": "Let’s image to run our pipeline a first time, and in this first run Node B fails:" }, { "code": null, "e": 3714, "s": 3635, "text": "Start -> Node C-> Node B -> Node A (Done) -> Node B (Error) -X-> Node C -> End" }, { "code": null, "e": 3841, "s": 3714, "text": "After we have manually fixed the error in Node B the pipeline can run again but, in this occasion, it will not consider Node A" }, { "code": null, "e": 3884, "s": 3841, "text": "Start -> Node C-> Node B -> Node C-> Node." }, { "code": null, "e": 3914, "s": 3884, "text": "Avoiding running it entirely." }, { "code": null, "e": 4035, "s": 3914, "text": "As mentioned, the Luigi package works like a graph. The nodes in Luigi are called Tasks and the edges are called Targets" }, { "code": null, "e": 4122, "s": 4035, "text": "Tasks are the basic building blocks of Luigi and where the real work actually happens." }, { "code": null, "e": 4200, "s": 4122, "text": "To create a task you have to create a class and inherit the class luigi.Task." }, { "code": null, "e": 4289, "s": 4200, "text": "Within the new class, there are contained at least one or all, of the following methods:" }, { "code": null, "e": 4300, "s": 4289, "text": "requires()" }, { "code": null, "e": 4306, "s": 4300, "text": "run()" }, { "code": null, "e": 4315, "s": 4306, "text": "output()" }, { "code": null, "e": 4323, "s": 4315, "text": "targets" }, { "code": null, "e": 4395, "s": 4323, "text": "The method requires() is the first method that is executed, if present." }, { "code": null, "e": 4624, "s": 4395, "text": "It contains all the instances that have been executed before the current task. Most commonly this method makes a call to another Luigi Task above the workflow, allowing the code to move backward to the beginning of the pipeline." }, { "code": null, "e": 4749, "s": 4624, "text": "If we saw earlier that Targets are what connect a Task to the next requires() is what connects the Task to the previous one." }, { "code": null, "e": 4810, "s": 4749, "text": "Targets move the code to the end, required to the beginning." }, { "code": null, "e": 4896, "s": 4810, "text": "Only when a method requires is satisfied that Task can execute the second method run:" }, { "code": null, "e": 5041, "s": 4896, "text": "In this method is contained the action that the task has to execute. It can be anything, a call to another method, the running of a script, etc." }, { "code": null, "e": 5109, "s": 5041, "text": "An example of a Task in Luigi with the two previous model would be:" }, { "code": null, "e": 5252, "s": 5109, "text": "class MakeTaskA(luigi.Task): def requires(self): return MakeTaskB() def run(self): return luigi.LocalTarget(DoSomething())" }, { "code": null, "e": 5411, "s": 5252, "text": "The method output() as the name suggests return one or more Target objects. Although, it is recommended that any Task only return one single Target in output." }, { "code": null, "e": 5419, "s": 5411, "text": "Example" }, { "code": null, "e": 5473, "s": 5419, "text": "A good example is present in the Luigi documentation:" }, { "code": null, "e": 5490, "s": 5473, "text": "In this example," }, { "code": null, "e": 5580, "s": 5490, "text": "The first Task is CountLetters(), it requires the class GenerateWords() so it moves there" }, { "code": null, "e": 5682, "s": 5580, "text": "GenerateWords() has no requires so it calls it’s run() method and it creates a file calls “words.txt”" }, { "code": null, "e": 5837, "s": 5682, "text": "It’s the turn of output(). This method finds the file word.txt and it returns it in the form of a LocalTarget class object, back to the class CountLetters" }, { "code": null, "e": 5915, "s": 5837, "text": "CountLetters() can execute run(), now. It takes what needed from self.input()" }, { "code": null, "e": 5946, "s": 5915, "text": "Afterword, it execute output()" }, { "code": null, "e": 6066, "s": 5946, "text": "Task.input() is a wrapper around Task.requires() that returns the corresponding Target objects instead of Task objects." }, { "code": null, "e": 6117, "s": 6066, "text": "Target is the edge connecting a Tasks to the next." }, { "code": null, "e": 6251, "s": 6117, "text": "These are usually represented as a file. Indeed, we have already seen one in the previous example. The file ‘hello.txt’ was a Target." }, { "code": null, "e": 6391, "s": 6251, "text": "A Task can be considered complete if and only if each of its output Targets exist. They can be as simple as empty files, an S3 or whatever." }, { "code": null, "e": 6495, "s": 6391, "text": "The last important element that we saw in the example, but we did not consider yet, are the Parameters." }, { "code": null, "e": 6674, "s": 6495, "text": "Parameters are in Luigi, the equivalent of creating a constructor for each Task. Those are instance variables of a class. Only one instance is created for each set of parameters." }, { "code": null, "e": 6836, "s": 6674, "text": "Personally, it reminds me of when in Java or C++, you have to declare variables, I know they are not the same thing, but it can help to understand the use of it." }, { "code": null, "e": 6886, "s": 6836, "text": "You can declare a parameter in the following way:" }, { "code": null, "e": 6971, "s": 6886, "text": "class MakeSomething(luigi.Task): string = luigi.Parameter(default='hello world!')" }, { "code": null, "e": 7042, "s": 6971, "text": "Now, we have a class with a parameter attribute ‘hello world!’ string." }, { "code": null, "e": 7096, "s": 7042, "text": "You can pass parameters back and forth between tasks." }, { "code": null, "e": 7170, "s": 7096, "text": "Besides the one seen above, there are different subclasses of Parameters:" }, { "code": null, "e": 7268, "s": 7170, "text": "There are a few of them: DateParameter, DateIntervalParameter, IntParameter, FloatParameter, etc." }, { "code": null, "e": 7414, "s": 7268, "text": "These provide methods for serialization and reading, you can make your own ones. However, you are not obligated to specify the type of parameter." }, { "code": null, "e": 7592, "s": 7414, "text": "You can simply use the base class Parameter. The reason you would use a subclass like DateParameter is that Luigi needs to perform a conversion for the command line interaction." }, { "code": null, "e": 7734, "s": 7592, "text": "That is how it knows how to convert a string provided on the command line to the corresponding type (i.e. datetime.date instead of a string)." }, { "code": null, "e": 7798, "s": 7734, "text": "To execute the code, type the following from your command line:" }, { "code": null, "e": 7859, "s": 7798, "text": "python -m luigi — module file_name TaskName — local-schedule" } ]
Bootstrap 5 Dropdowns - GeeksforGeeks
09 Feb, 2022 Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Dropdowns are toggleable, contextual overlays for displaying lists of links and more. They’re made interactive with the included Bootstrap dropdown JavaScript plugin. They’re toggled by clicking, not by hovering; this is an intentional design decision. Syntax: <div class="dropdown"> Contents... <div> Example 1: This example uses show the working of dropdown with button in Bootstrap 5. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select CS Subjects </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </body></html> Output: Dropdown Divider: The .dropdown-divider class is used to divide the dropdown menu list by using thin horizontal line. This example shows the working of collapsible cards in Bootstrap 5. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subjects </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Physics</a> <a class="dropdown-item" href="#">Mathematics</a> <a class="dropdown-item" href="#">Chemistry</a> </div> </div> </div> </body></html> Output: Dropdown Header: The .dropdown-header class is used to add header section inside the dropdown list. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subjects </button> <div class="dropdown-menu"> <strong class="dropdown-header"> CS Subjects</strong> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> <div class="dropdown-divider"></div> <strong class="dropdown-header"> Other Subjects</strong> <a class="dropdown-item" href="#">Physics</a> <a class="dropdown-item" href="#">Mathematics</a> <a class="dropdown-item" href="#">Chemistry</a> </div> </div> </div> </body></html> Output: Disable and Active items: The .active class is used to add the highlight the list items. The .disabled class is used to disable the list of items. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subjects </button> <div class="dropdown-menu"> <a class="dropdown-item active" href="#">Data Structure</a> <a class="dropdown-item disabled" href="#">Algorithm</a> <a class="dropdown-item active" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </body></html> Output: Dropdown Position: The .dropright and .dropleft classes are used to set the position of dropdown list in left and right side. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown dropright"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subjects </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </body></html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown dropleft"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subjects </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </body></html> Output: Dropdown Menu Right Aligned: The .dropdown-menu-right class is used to set the right-align of the dropdown menu. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Computer Science Subject from List </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </body></html> Output: Dropup: The .dropup class is used instead of .dropdown class to expand the menu list in upwards. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity= "sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropup" style="margin-top: 180px;"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subject </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Data Structure</a> <a class="dropdown-item" href="#">Algorithm</a> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </body></html> Output: Dropdown Text: The .dropdown-item-text class is used to add plain text in the dropdown menu list. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subject </button> <div class="dropdown-menu"> <div class="dropdown-item-text"> Data Structure</div> <div class="dropdown-item-text"> Algorithm</div> <div class="dropdown-item-text"> Operating System</div> <div class="dropdown-item-text"> Another Text</div> </div> </div> </div> </body></html> Output: Grouped Buttons with a Dropdown: The .btn-group class is used to create a group of buttons and the .dropdown-menu class is used to create a dropdown list. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="btn-group"> <button type="button" class="btn btn-success btn-primary"> Programming </button> <button type="button" class="btn btn-success btn-primary"> Theory </button> <div class="btn-group"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Select Subject </button> <div class="dropdown-menu"> <div class="dropdown-item-text"> Data Structure</div> <div class="dropdown-item-text"> Algorithm</div> <div class="dropdown-item-text"> Operating System</div> <div class="dropdown-item-text"> Computer Networks</div> </div> </div> </div> </div> </body></html> Output: Split Button Dropdowns: The .dropdown-toggle-split class is used to split the dropdown buttons. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"> </script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="btn-group"> <button type="button" class="btn btn-success btn-primary"> Programming </button> <button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">C Programming</a> <a class="dropdown-item" href="#">C++ Programming</a> <a class="dropdown-item" href="#">Java Programming</a> </div> </div> <div class="btn-group"> <button type="button" class="btn btn-success btn-primary"> Theory </button> <button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> <div class="btn-group"> <button type="button" class="btn btn-success btn-primary"> Select Subject </button> <button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button> <div class="dropdown-menu"> <div class="dropdown-item"> Data Structure</div> <div class="dropdown-item"> Algorithm</div> <div class="dropdown-item"> Operating System</div> <div class="dropdown-item"> Computer Networks</div> </div> </div> </div> </body></html> Output: Vertical Button Group Dropdown List: The .btn-group-vertical class is used to create vertical button group with fropdown list. HTML <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="btn-group-vertical"> <div class="btn-group dropright"> <button type="button" class="btn btn-success btn-primary"> Programming </button> <button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">C Programming</a> <a class="dropdown-item" href="#">C++ Programming</a> <a class="dropdown-item" href="#">Java Programming</a> </div> </div> <div class="btn-group dropright"> <button type="button" class="btn btn-success btn-primary"> Theory </button> <button type="button" class="btn btn-success dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"> </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Operating System</a> <a class="dropdown-item" href="#">Computer Networks</a> </div> </div> </div> </div> </body></html> Output: sumitgumber28 Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Form validation using jQuery How to change navigation bar color in Bootstrap ? How to align navbar items to the right in Bootstrap 4 ? How to set Bootstrap Timepicker using datetimepicker library ? How to pass data into a bootstrap modal? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28360, "s": 28332, "text": "\n09 Feb, 2022" }, { "code": null, "e": 28728, "s": 28360, "text": "Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Dropdowns are toggleable, contextual overlays for displaying lists of links and more. They’re made interactive with the included Bootstrap dropdown JavaScript plugin. They’re toggled by clicking, not by hovering; this is an intentional design decision. " }, { "code": null, "e": 28736, "s": 28728, "text": "Syntax:" }, { "code": null, "e": 28777, "s": 28736, "text": "<div class=\"dropdown\"> Contents... <div>" }, { "code": null, "e": 28863, "s": 28777, "text": "Example 1: This example uses show the working of dropdown with button in Bootstrap 5." }, { "code": null, "e": 28868, "s": 28863, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select CS Subjects </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </body></html>", "e": 30634, "s": 28868, "text": null }, { "code": null, "e": 30642, "s": 30634, "text": "Output:" }, { "code": null, "e": 30828, "s": 30642, "text": "Dropdown Divider: The .dropdown-divider class is used to divide the dropdown menu list by using thin horizontal line. This example shows the working of collapsible cards in Bootstrap 5." }, { "code": null, "e": 30836, "s": 30831, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subjects </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> <div class=\"dropdown-divider\"></div> <a class=\"dropdown-item\" href=\"#\">Physics</a> <a class=\"dropdown-item\" href=\"#\">Mathematics</a> <a class=\"dropdown-item\" href=\"#\">Chemistry</a> </div> </div> </div> </body></html>", "e": 32941, "s": 30836, "text": null }, { "code": null, "e": 32949, "s": 32941, "text": "Output:" }, { "code": null, "e": 33051, "s": 32949, "text": "Dropdown Header: The .dropdown-header class is used to add header section inside the dropdown list. " }, { "code": null, "e": 33056, "s": 33051, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subjects </button> <div class=\"dropdown-menu\"> <strong class=\"dropdown-header\"> CS Subjects</strong> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> <div class=\"dropdown-divider\"></div> <strong class=\"dropdown-header\"> Other Subjects</strong> <a class=\"dropdown-item\" href=\"#\">Physics</a> <a class=\"dropdown-item\" href=\"#\">Mathematics</a> <a class=\"dropdown-item\" href=\"#\">Chemistry</a> </div> </div> </div> </body></html>", "e": 35365, "s": 33056, "text": null }, { "code": null, "e": 35373, "s": 35365, "text": "Output:" }, { "code": null, "e": 35522, "s": 35373, "text": "Disable and Active items: The .active class is used to add the highlight the list items. The .disabled class is used to disable the list of items. " }, { "code": null, "e": 35527, "s": 35522, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subjects </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item active\" href=\"#\">Data Structure</a> <a class=\"dropdown-item disabled\" href=\"#\">Algorithm</a> <a class=\"dropdown-item active\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </body></html>", "e": 37332, "s": 35527, "text": null }, { "code": null, "e": 37340, "s": 37332, "text": "Output:" }, { "code": null, "e": 37468, "s": 37340, "text": "Dropdown Position: The .dropright and .dropleft classes are used to set the position of dropdown list in left and right side. " }, { "code": null, "e": 37473, "s": 37468, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown dropright\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subjects </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </body></html>", "e": 39247, "s": 37473, "text": null }, { "code": null, "e": 39255, "s": 39247, "text": "Output:" }, { "code": null, "e": 39268, "s": 39255, "text": "Example 2: " }, { "code": null, "e": 39273, "s": 39268, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown dropleft\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subjects </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </body></html>", "e": 41076, "s": 39273, "text": null }, { "code": null, "e": 41084, "s": 41076, "text": "Output:" }, { "code": null, "e": 41199, "s": 41084, "text": "Dropdown Menu Right Aligned: The .dropdown-menu-right class is used to set the right-align of the dropdown menu. " }, { "code": null, "e": 41204, "s": 41199, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Computer Science Subject from List </button> <div class=\"dropdown-menu dropdown-menu-right\"> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </body></html>", "e": 43032, "s": 41204, "text": null }, { "code": null, "e": 43040, "s": 43032, "text": "Output:" }, { "code": null, "e": 43139, "s": 43040, "text": "Dropup: The .dropup class is used instead of .dropdown class to expand the menu list in upwards. " }, { "code": null, "e": 43144, "s": 43139, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity= \"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropup\" style=\"margin-top: 180px;\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subject </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Data Structure</a> <a class=\"dropdown-item\" href=\"#\">Algorithm</a> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </body></html>", "e": 44979, "s": 43144, "text": null }, { "code": null, "e": 44987, "s": 44979, "text": "Output:" }, { "code": null, "e": 45087, "s": 44987, "text": "Dropdown Text: The .dropdown-item-text class is used to add plain text in the dropdown menu list. " }, { "code": null, "e": 45092, "s": 45087, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subject </button> <div class=\"dropdown-menu\"> <div class=\"dropdown-item-text\"> Data Structure</div> <div class=\"dropdown-item-text\"> Algorithm</div> <div class=\"dropdown-item-text\"> Operating System</div> <div class=\"dropdown-item-text\"> Another Text</div> </div> </div> </div> </body></html>", "e": 46838, "s": 45092, "text": null }, { "code": null, "e": 46846, "s": 46838, "text": "Output:" }, { "code": null, "e": 47003, "s": 46846, "text": "Grouped Buttons with a Dropdown: The .btn-group class is used to create a group of buttons and the .dropdown-menu class is used to create a dropdown list. " }, { "code": null, "e": 47008, "s": 47003, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"btn-group\"> <button type=\"button\" class=\"btn btn-success btn-primary\"> Programming </button> <button type=\"button\" class=\"btn btn-success btn-primary\"> Theory </button> <div class=\"btn-group\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Select Subject </button> <div class=\"dropdown-menu\"> <div class=\"dropdown-item-text\"> Data Structure</div> <div class=\"dropdown-item-text\"> Algorithm</div> <div class=\"dropdown-item-text\"> Operating System</div> <div class=\"dropdown-item-text\"> Computer Networks</div> </div> </div> </div> </div> </body></html>", "e": 49244, "s": 47008, "text": null }, { "code": null, "e": 49252, "s": 49244, "text": "Output:" }, { "code": null, "e": 49350, "s": 49252, "text": "Split Button Dropdowns: The .dropdown-toggle-split class is used to split the dropdown buttons. " }, { "code": null, "e": 49355, "s": 49350, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"> </script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"btn-group\"> <button type=\"button\" class=\"btn btn-success btn-primary\"> Programming </button> <button type=\"button\" class=\"btn btn-success dropdown-toggle dropdown-toggle-split\" data-toggle=\"dropdown\"> </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">C Programming</a> <a class=\"dropdown-item\" href=\"#\">C++ Programming</a> <a class=\"dropdown-item\" href=\"#\">Java Programming</a> </div> </div> <div class=\"btn-group\"> <button type=\"button\" class=\"btn btn-success btn-primary\"> Theory </button> <button type=\"button\" class=\"btn btn-success dropdown-toggle dropdown-toggle-split\" data-toggle=\"dropdown\"></button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> <div class=\"btn-group\"> <button type=\"button\" class=\"btn btn-success btn-primary\"> Select Subject </button> <button type=\"button\" class=\"btn btn-success dropdown-toggle dropdown-toggle-split\" data-toggle=\"dropdown\"></button> <div class=\"dropdown-menu\"> <div class=\"dropdown-item\"> Data Structure</div> <div class=\"dropdown-item\"> Algorithm</div> <div class=\"dropdown-item\"> Operating System</div> <div class=\"dropdown-item\"> Computer Networks</div> </div> </div> </div> </body></html>", "e": 52881, "s": 49355, "text": null }, { "code": null, "e": 52889, "s": 52881, "text": "Output:" }, { "code": null, "e": 53018, "s": 52889, "text": "Vertical Button Group Dropdown List: The .btn-group-vertical class is used to create vertical button group with fropdown list. " }, { "code": null, "e": 53023, "s": 53018, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"btn-group-vertical\"> <div class=\"btn-group dropright\"> <button type=\"button\" class=\"btn btn-success btn-primary\"> Programming </button> <button type=\"button\" class=\"btn btn-success dropdown-toggle dropdown-toggle-split\" data-toggle=\"dropdown\"></button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">C Programming</a> <a class=\"dropdown-item\" href=\"#\">C++ Programming</a> <a class=\"dropdown-item\" href=\"#\">Java Programming</a> </div> </div> <div class=\"btn-group dropright\"> <button type=\"button\" class=\"btn btn-success btn-primary\"> Theory </button> <button type=\"button\" class=\"btn btn-success dropdown-toggle dropdown-toggle-split\" data-toggle=\"dropdown\"> </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Operating System</a> <a class=\"dropdown-item\" href=\"#\">Computer Networks</a> </div> </div> </div> </div> </body></html>", "e": 55880, "s": 53023, "text": null }, { "code": null, "e": 55888, "s": 55880, "text": "Output:" }, { "code": null, "e": 55902, "s": 55888, "text": "sumitgumber28" }, { "code": null, "e": 55917, "s": 55902, "text": "Bootstrap-Misc" }, { "code": null, "e": 55927, "s": 55917, "text": "Bootstrap" }, { "code": null, "e": 55944, "s": 55927, "text": "Web Technologies" }, { "code": null, "e": 56042, "s": 55944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 56051, "s": 56042, "text": "Comments" }, { "code": null, "e": 56064, "s": 56051, "text": "Old Comments" }, { "code": null, "e": 56093, "s": 56064, "text": "Form validation using jQuery" }, { "code": null, "e": 56143, "s": 56093, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 56199, "s": 56143, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 56262, "s": 56199, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 56303, "s": 56262, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 56345, "s": 56303, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 56378, "s": 56345, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 56421, "s": 56378, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 56483, "s": 56421, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Elasticsearch - Search APIs
This API is used to search content in Elasticsearch. A user can search by sending a get request with query string as a parameter or they can post a query in the message body of post request. Mainly all the search APIS are multi-index, multi-type. Elasticsearch allows us to search for the documents present in all the indices or in some specific indices. For example, if we need to search all the documents with a name that contains central, we can do as shown here − GET /_all/_search?q=city:paprola On running the above code, we get the following response − { "took" : 33, "timed_out" : false, "_shards" : { "total" : 7, "successful" : 7, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 0.9808292, "hits" : [ { "_index" : "schools", "_type" : "school", "_id" : "5", "_score" : 0.9808292, "_source" : { "name" : "Central School", "description" : "CBSE Affiliation", "street" : "Nagan", "city" : "paprola", "state" : "HP", "zip" : "176115", "location" : [ 31.8955385, 76.8380405 ], "fees" : 2200, "tags" : [ "Senior Secondary", "beautiful campus" ], "rating" : "3.3" } } ] } } Many parameters can be passed in a search operation using Uniform Resource Identifier − Q This parameter is used to specify query string. lenient This parameter is used to specify query string.Format based errors can be ignored by just setting this parameter to true. It is false by default. fields This parameter is used to specify query string. sort We can get sorted result by using this parameter, the possible values for this parameter is fieldName, fieldName:asc/fieldname:desc timeout We can restrict the search time by using this parameter and response only contains the hits in that specified time. By default, there is no timeout. terminate_after We can restrict the response to a specified number of documents for each shard, upon reaching which the query will terminate early. By default, there is no terminate_after. from The starting from index of the hits to return. Defaults to 0. size It denotes the number of hits to return. Defaults to 10. We can also specify query using query DSL in request body and there are many examples already given in previous chapters. One such example is given here − POST /schools/_search { "query":{ "query_string":{ "query":"up" } } } On running the above code, we get the following response − { "took" : 11, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 0.47000363, "hits" : [ { "_index" : "schools", "_type" : "school", "_id" : "4", "_score" : 0.47000363, "_source" : { "name" : "City Best School", "description" : "ICSE", "street" : "West End", "city" : "Meerut", "state" : "UP", "zip" : "250002", "location" : [ 28.9926174, 77.692485 ], "fees" : 3500, "tags" : [ "fully computerized" ], "rating" : "4.5" } } ] } } 14 Lectures 5 hours Manuj Aggarwal 20 Lectures 1 hours Faizan Tayyab Print Add Notes Bookmark this page
[ { "code": null, "e": 2828, "s": 2581, "text": "This API is used to search content in Elasticsearch. A user can search by sending a get request with query string as a parameter or they can post a query in the message body of post request. Mainly all the search APIS are multi-index, multi-type." }, { "code": null, "e": 3049, "s": 2828, "text": "Elasticsearch allows us to search for the documents present in all the indices or in some\nspecific indices. For example, if we need to search all the documents with a name that contains central, we can do as shown here −" }, { "code": null, "e": 3084, "s": 3049, "text": "GET /_all/_search?q=city:paprola \n" }, { "code": null, "e": 3143, "s": 3084, "text": "On running the above code, we get the following response −" }, { "code": null, "e": 4147, "s": 3143, "text": "{\n \"took\" : 33,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 7,\n \"successful\" : 7,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.9808292,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 0.9808292,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n }\n ]\n }\n}\n" }, { "code": null, "e": 4235, "s": 4147, "text": "Many parameters can be passed in a search operation using Uniform Resource Identifier −" }, { "code": null, "e": 4237, "s": 4235, "text": "Q" }, { "code": null, "e": 4285, "s": 4237, "text": "This parameter is used to specify query string." }, { "code": null, "e": 4293, "s": 4285, "text": "lenient" }, { "code": null, "e": 4439, "s": 4293, "text": "This parameter is used to specify query string.Format based errors can be ignored by just setting this parameter to true. It\nis false by default." }, { "code": null, "e": 4446, "s": 4439, "text": "fields" }, { "code": null, "e": 4494, "s": 4446, "text": "This parameter is used to specify query string." }, { "code": null, "e": 4499, "s": 4494, "text": "sort" }, { "code": null, "e": 4631, "s": 4499, "text": "We can get sorted result by using this parameter, the possible values for this parameter is fieldName, fieldName:asc/fieldname:desc" }, { "code": null, "e": 4639, "s": 4631, "text": "timeout" }, { "code": null, "e": 4788, "s": 4639, "text": "We can restrict the search time by using this parameter and response only contains the hits in that specified time. By default, there is no timeout." }, { "code": null, "e": 4804, "s": 4788, "text": "terminate_after" }, { "code": null, "e": 4977, "s": 4804, "text": "We can restrict the response to a specified number of documents for each shard, upon reaching which the query will terminate early. By default, there is no terminate_after." }, { "code": null, "e": 4982, "s": 4977, "text": "from" }, { "code": null, "e": 5044, "s": 4982, "text": "The starting from index of the hits to return. Defaults to 0." }, { "code": null, "e": 5049, "s": 5044, "text": "size" }, { "code": null, "e": 5106, "s": 5049, "text": "It denotes the number of hits to return. Defaults to 10." }, { "code": null, "e": 5261, "s": 5106, "text": "We can also specify query using query DSL in request body and there are many examples already given in previous chapters. One such example is given here −" }, { "code": null, "e": 5358, "s": 5261, "text": "POST /schools/_search\n{\n \"query\":{\n \"query_string\":{\n \"query\":\"up\"\n }\n }\n}" }, { "code": null, "e": 5417, "s": 5358, "text": "On running the above code, we get the following response −" }, { "code": null, "e": 6378, "s": 5417, "text": "{\n \"took\" : 11,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.47000363,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 0.47000363,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n" }, { "code": null, "e": 6411, "s": 6378, "text": "\n 14 Lectures \n 5 hours \n" }, { "code": null, "e": 6427, "s": 6411, "text": " Manuj Aggarwal" }, { "code": null, "e": 6460, "s": 6427, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 6475, "s": 6460, "text": " Faizan Tayyab" }, { "code": null, "e": 6482, "s": 6475, "text": " Print" }, { "code": null, "e": 6493, "s": 6482, "text": " Add Notes" } ]
SQLSERVER Tryit Editor v1.0
SELECT CustomerName, ASCII(CustomerName) AS NumCodeOfFirstChar FROM Customers; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 63, "s": 0, "text": "SELECT CustomerName, ASCII(CustomerName) AS NumCodeOfFirstChar" }, { "code": null, "e": 79, "s": 63, "text": "FROM Customers;" }, { "code": null, "e": 81, "s": 79, "text": "​" }, { "code": null, "e": 153, "s": 90, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 213, "s": 153, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 281, "s": 213, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 319, "s": 281, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 404, "s": 319, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 578, "s": 404, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 629, "s": 578, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 697, "s": 629, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 868, "s": 697, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 968, "s": 868, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1018, "s": 968, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Starting Data Visualization with the Julia Language and Jupyter Notebooks | by Alan Jones | Towards Data Science
A while ago I wrote about data visualization using Julia and online Jupyter Notebook environment called JuliaBox. At the time JuliaBox was a free service; unfortunately, that is no longer so — it’s not expensive but it isn’t free. So here is a new version of that article where you use your own Jupyter Notebook environment (which is free). You’ll need to install Jupyter Notebooks, the Julia language and then configure them so that Jupyter knows about Julia. If that sounds complicated, don’t worry, it isn’t. The first thing you need is a Jupyter Notebook. If you have it installed already, great. If not you should follow this article : (The article has a mild Python focus but since Jupyter requires Python to be installed there is nothing very irrelevant here.) Julia is a relatively new language for data analysis. It has a high-level syntax and designed to be easy to use and understand. Some have called it the new Python. Unlike Python, though, it is a compiled language, which means that while it is as easy to write as Python, it runs much faster because it is converted to low-level code that is more easily understood by a computer. This is great if you have to deal with large data sets that require a lot of processing. Julia is also much less fussy about how a program is laid out than Python. Julia has all the features that you would expect of a modern programming language but, here, we are going to take a look at Julia’s data visualization capabilities. These are both impressive and easy to use. Once you’ve installed Julia and Jupyter, you can create Jupyter Notebooks that run Julia code, execute them and export them as HTML. You can save your visualizations as standard png files and save them to include in your documents. If you want to work through the examples in this article, you can download the data files and the Jupyter notebook to use with your own set up. I’ll put the links at the end of the article. To install Julia you need to go to https://julialang.org/ and download the appropriate version for your operating system. Installation is straightforward, just follow the instructions. Once you have installed it there are a couple of things you need to do. So start up Julia and you will see the command prompt in a window like this: The first thing is to allow Jupyter and Julia to talk to each other. Type this at the prompt and the press <return>: using Pkg this tells Julia that you are going to use the package manager. Then type the following and hit <return>: Pkg.add("IJulia") IJulia is the package that will provide the connection between Jupyter and Julia. You may need to wait while it downloads and installs. Once you have installed IJulia you will be able to open a new Notebook in Jupyter using Julia instead of Python. Now you need to add a couple more packages that we are going to use in the tutorial. Type in these lines: Pkg.add("Plots") and Pkg.add("CSV") and Pkg.add("DataFrames") You’ll be using each of these packages later. Now you can close Julia by executing: exit() or by simply closing the window. Now you are ready to start! So, fire up a Jupyter Notebook using Julia as the kernel and get going. Julia, as with most other languages, relies on libraries of code for particular specialist purposes. The one that we are initially interested in is called Plots. This provides us with the capability to create visualizations of data. So the first piece of code that we need to execute is this: using Plots When you type this into a code cell in your notebook and press ctrl/enter to execute it, it tells Julia to load the library that we will use to create our visualizations. When you execute a cell in a notebook for the first time, it may take a little while to execute. This is because the Julia code is compiled on the fly, the first time you execute. Subsequent code runs are much quicker. projectcodeed.blogspot.com I usually put different bits of code into new cells in the notebook. This means that I only have to run the code that I need and not the whole notebook. I suggest that you do the same, so in a new cell I typed in the following code: x = 1:10; y = rand(10); # These are the plotting data plot(x,y, label="my label") Running it produced the following graph: Impressive. Let me explain what’s going on. x = 1:10; y = rand(10); # These are the plotting data This bit of code creates two bits of data, one is called x and the other y. x is given the value of a range of numbers from 1 to 10, while y is given a range of 10 pseudo-random numbers (each will have a value between 0 and 1). So, we have the basis of a graph here: an x-axis that ranges from 1 to 10 and y values for each of the points on the x axis. The next bit is easy. plot(x,y, label=”my label”) This code calls a function to plot the graph and all we do is give it the x and y values — and, as an extra, we’ve given it a label, too. That was easy but, course, we really want to visualize some real data. I have a couple of tables that I have used for other articles. It’s a set of data about the weather in London, UK, over the last few decades. I derived it from public tables provided by the UK Met Office. The data records the maximum temperature, minimum temperature, rainfall and hours of sunshine recorded in each month. I have two files, one is the complete data set and the other is for 2018, only. They are in CSV format, such as you might import into a spreadsheet. To deal with these files we need another library that allows us to read CSV files. We can see the library referenced in the next chunk of code, i.e. using CSV and the following line actually reads in the data to a variable d, which is a DataFrame. using CSVd = CSV.read("london2018.csv", DataFrame) The result of running the code is that we now have a table of data that looks like this: The data that we have downloaded is formed of a table with 6 columns: Year, Month, Tmax (maximum temperature), Tmin (minimum temperature), Rain (rainfall in millimeters) and Sun (the number of hours of sunshine). This is a subset of the data (for 2018, only) so the Year column has the same value in all the rows. So, what we have is the data for each month of 2018. If we wanted to plot the maximum temperature in each month in a bar chart we would do this: bar(d.Month, d.Tmax) bar is a function that draws a bar chart (what else?) and we provide the columns for the x and y axes. We do this by using the name of the data table, followed by the name of the column. The two names are separated with a dot. Here we have the column Month as the x axis and Tmax as the y axis- so we are plotting the maximum recorded temperature for each of the 12 months in the table. Put this in a new code cell and run it and you will be pleasantly surprised (I hope) to see this chart: If you wanted to produce a line chart, you do much the same thing but use the function plot plot(d.Month, d.Tmax) And, if you wanted to plot both maximum and minimum temperatures on the same graph, you could do this: plot(d.Month, [d.Tmax, d.Tmin], label=["Tmax","Tmin"]) Note that the two values, d.Tmax and d.Tmin, are grouped together in square brackets and separated by a comma. This is the notation for a vector, or singled dimensional array. Additionally, we have added labels for the lines and these are grouped in the same way. We get a graph like this: Or how about a scatter chart? A scatter chart is often used to see if a pattern can be detected in the data. Here we plot the maximum temperature against the hours of sunshine. As you might expect there is a pattern: a visible correlation — the more hours of sunshine there are, the higher the temperature. scatter(d.Tmax, d.Sun) The data we have doesn’t really lend itself to being depicted as a pie chart, so we are going to generate some random data, again — 5 random numbers. x = 1:5; y = rand(5); # These are the plotting datapie(x,y) Now we are going to load in a bit more data: d2 = CSV.read("londonweather.csv"`, DataFrame) This is similar to the data table that we have been using but rather bigger as it covers several decades of data rather than just one year. This gives us plenty of rainfall data so that we can see the distribution of the levels of rain that occur in London over a longish period. histogram(d2.Rain, label="Rainfall") Here’s the result. It’s all very well seeing these charts in the Jupyter environment but to be useful, we need to be able to save them so as to use them in our documents. You can save the chart like this: histogram(d2.Rain, label="Rainfall") savefig("myhistogram.png") When this code is run the chart will not be displayed but it will be saved with the file name given. I hope that was useful — we’ve looked at the basic charts available in Julia Plots. There is a great deal more to Julia than we have seen in this short article and a lot more that you can do with Plots too, but I hope you have found that this introduction has whetted your appetite to find out more. Right click on the three links below to download the files and then copy them in the directory that Jupyter will use. Then in your file list open plotweatherjulia.ipynb. The notebook is here: plotweatherjulia.ipynb and the data files are here: london2018.csv and londonweather.csv As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here. If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commision.
[ { "code": null, "e": 402, "s": 171, "text": "A while ago I wrote about data visualization using Julia and online Jupyter Notebook environment called JuliaBox. At the time JuliaBox was a free service; unfortunately, that is no longer so — it’s not expensive but it isn’t free." }, { "code": null, "e": 632, "s": 402, "text": "So here is a new version of that article where you use your own Jupyter Notebook environment (which is free). You’ll need to install Jupyter Notebooks, the Julia language and then configure them so that Jupyter knows about Julia." }, { "code": null, "e": 683, "s": 632, "text": "If that sounds complicated, don’t worry, it isn’t." }, { "code": null, "e": 812, "s": 683, "text": "The first thing you need is a Jupyter Notebook. If you have it installed already, great. If not you should follow this article :" }, { "code": null, "e": 939, "s": 812, "text": "(The article has a mild Python focus but since Jupyter requires Python to be installed there is nothing very irrelevant here.)" }, { "code": null, "e": 1103, "s": 939, "text": "Julia is a relatively new language for data analysis. It has a high-level syntax and designed to be easy to use and understand. Some have called it the new Python." }, { "code": null, "e": 1407, "s": 1103, "text": "Unlike Python, though, it is a compiled language, which means that while it is as easy to write as Python, it runs much faster because it is converted to low-level code that is more easily understood by a computer. This is great if you have to deal with large data sets that require a lot of processing." }, { "code": null, "e": 1482, "s": 1407, "text": "Julia is also much less fussy about how a program is laid out than Python." }, { "code": null, "e": 1690, "s": 1482, "text": "Julia has all the features that you would expect of a modern programming language but, here, we are going to take a look at Julia’s data visualization capabilities. These are both impressive and easy to use." }, { "code": null, "e": 1922, "s": 1690, "text": "Once you’ve installed Julia and Jupyter, you can create Jupyter Notebooks that run Julia code, execute them and export them as HTML. You can save your visualizations as standard png files and save them to include in your documents." }, { "code": null, "e": 2112, "s": 1922, "text": "If you want to work through the examples in this article, you can download the data files and the Jupyter notebook to use with your own set up. I’ll put the links at the end of the article." }, { "code": null, "e": 2297, "s": 2112, "text": "To install Julia you need to go to https://julialang.org/ and download the appropriate version for your operating system. Installation is straightforward, just follow the instructions." }, { "code": null, "e": 2446, "s": 2297, "text": "Once you have installed it there are a couple of things you need to do. So start up Julia and you will see the command prompt in a window like this:" }, { "code": null, "e": 2563, "s": 2446, "text": "The first thing is to allow Jupyter and Julia to talk to each other. Type this at the prompt and the press <return>:" }, { "code": null, "e": 2573, "s": 2563, "text": "using Pkg" }, { "code": null, "e": 2679, "s": 2573, "text": "this tells Julia that you are going to use the package manager. Then type the following and hit <return>:" }, { "code": null, "e": 2697, "s": 2679, "text": "Pkg.add(\"IJulia\")" }, { "code": null, "e": 2833, "s": 2697, "text": "IJulia is the package that will provide the connection between Jupyter and Julia. You may need to wait while it downloads and installs." }, { "code": null, "e": 2946, "s": 2833, "text": "Once you have installed IJulia you will be able to open a new Notebook in Jupyter using Julia instead of Python." }, { "code": null, "e": 3052, "s": 2946, "text": "Now you need to add a couple more packages that we are going to use in the tutorial. Type in these lines:" }, { "code": null, "e": 3069, "s": 3052, "text": "Pkg.add(\"Plots\")" }, { "code": null, "e": 3073, "s": 3069, "text": "and" }, { "code": null, "e": 3088, "s": 3073, "text": "Pkg.add(\"CSV\")" }, { "code": null, "e": 3092, "s": 3088, "text": "and" }, { "code": null, "e": 3114, "s": 3092, "text": "Pkg.add(\"DataFrames\")" }, { "code": null, "e": 3160, "s": 3114, "text": "You’ll be using each of these packages later." }, { "code": null, "e": 3198, "s": 3160, "text": "Now you can close Julia by executing:" }, { "code": null, "e": 3205, "s": 3198, "text": "exit()" }, { "code": null, "e": 3238, "s": 3205, "text": "or by simply closing the window." }, { "code": null, "e": 3338, "s": 3238, "text": "Now you are ready to start! So, fire up a Jupyter Notebook using Julia as the kernel and get going." }, { "code": null, "e": 3571, "s": 3338, "text": "Julia, as with most other languages, relies on libraries of code for particular specialist purposes. The one that we are initially interested in is called Plots. This provides us with the capability to create visualizations of data." }, { "code": null, "e": 3631, "s": 3571, "text": "So the first piece of code that we need to execute is this:" }, { "code": null, "e": 3643, "s": 3631, "text": "using Plots" }, { "code": null, "e": 3814, "s": 3643, "text": "When you type this into a code cell in your notebook and press ctrl/enter to execute it, it tells Julia to load the library that we will use to create our visualizations." }, { "code": null, "e": 4033, "s": 3814, "text": "When you execute a cell in a notebook for the first time, it may take a little while to execute. This is because the Julia code is compiled on the fly, the first time you execute. Subsequent code runs are much quicker." }, { "code": null, "e": 4060, "s": 4033, "text": "projectcodeed.blogspot.com" }, { "code": null, "e": 4293, "s": 4060, "text": "I usually put different bits of code into new cells in the notebook. This means that I only have to run the code that I need and not the whole notebook. I suggest that you do the same, so in a new cell I typed in the following code:" }, { "code": null, "e": 4375, "s": 4293, "text": "x = 1:10; y = rand(10); # These are the plotting data plot(x,y, label=\"my label\")" }, { "code": null, "e": 4416, "s": 4375, "text": "Running it produced the following graph:" }, { "code": null, "e": 4460, "s": 4416, "text": "Impressive. Let me explain what’s going on." }, { "code": null, "e": 4514, "s": 4460, "text": "x = 1:10; y = rand(10); # These are the plotting data" }, { "code": null, "e": 4867, "s": 4514, "text": "This bit of code creates two bits of data, one is called x and the other y. x is given the value of a range of numbers from 1 to 10, while y is given a range of 10 pseudo-random numbers (each will have a value between 0 and 1). So, we have the basis of a graph here: an x-axis that ranges from 1 to 10 and y values for each of the points on the x axis." }, { "code": null, "e": 4889, "s": 4867, "text": "The next bit is easy." }, { "code": null, "e": 4917, "s": 4889, "text": "plot(x,y, label=”my label”)" }, { "code": null, "e": 5055, "s": 4917, "text": "This code calls a function to plot the graph and all we do is give it the x and y values — and, as an extra, we’ve given it a label, too." }, { "code": null, "e": 5126, "s": 5055, "text": "That was easy but, course, we really want to visualize some real data." }, { "code": null, "e": 5331, "s": 5126, "text": "I have a couple of tables that I have used for other articles. It’s a set of data about the weather in London, UK, over the last few decades. I derived it from public tables provided by the UK Met Office." }, { "code": null, "e": 5598, "s": 5331, "text": "The data records the maximum temperature, minimum temperature, rainfall and hours of sunshine recorded in each month. I have two files, one is the complete data set and the other is for 2018, only. They are in CSV format, such as you might import into a spreadsheet." }, { "code": null, "e": 5681, "s": 5598, "text": "To deal with these files we need another library that allows us to read CSV files." }, { "code": null, "e": 5846, "s": 5681, "text": "We can see the library referenced in the next chunk of code, i.e. using CSV and the following line actually reads in the data to a variable d, which is a DataFrame." }, { "code": null, "e": 5897, "s": 5846, "text": "using CSVd = CSV.read(\"london2018.csv\", DataFrame)" }, { "code": null, "e": 5986, "s": 5897, "text": "The result of running the code is that we now have a table of data that looks like this:" }, { "code": null, "e": 6199, "s": 5986, "text": "The data that we have downloaded is formed of a table with 6 columns: Year, Month, Tmax (maximum temperature), Tmin (minimum temperature), Rain (rainfall in millimeters) and Sun (the number of hours of sunshine)." }, { "code": null, "e": 6300, "s": 6199, "text": "This is a subset of the data (for 2018, only) so the Year column has the same value in all the rows." }, { "code": null, "e": 6445, "s": 6300, "text": "So, what we have is the data for each month of 2018. If we wanted to plot the maximum temperature in each month in a bar chart we would do this:" }, { "code": null, "e": 6466, "s": 6445, "text": "bar(d.Month, d.Tmax)" }, { "code": null, "e": 6693, "s": 6466, "text": "bar is a function that draws a bar chart (what else?) and we provide the columns for the x and y axes. We do this by using the name of the data table, followed by the name of the column. The two names are separated with a dot." }, { "code": null, "e": 6853, "s": 6693, "text": "Here we have the column Month as the x axis and Tmax as the y axis- so we are plotting the maximum recorded temperature for each of the 12 months in the table." }, { "code": null, "e": 6957, "s": 6853, "text": "Put this in a new code cell and run it and you will be pleasantly surprised (I hope) to see this chart:" }, { "code": null, "e": 7049, "s": 6957, "text": "If you wanted to produce a line chart, you do much the same thing but use the function plot" }, { "code": null, "e": 7071, "s": 7049, "text": "plot(d.Month, d.Tmax)" }, { "code": null, "e": 7174, "s": 7071, "text": "And, if you wanted to plot both maximum and minimum temperatures on the same graph, you could do this:" }, { "code": null, "e": 7229, "s": 7174, "text": "plot(d.Month, [d.Tmax, d.Tmin], label=[\"Tmax\",\"Tmin\"])" }, { "code": null, "e": 7519, "s": 7229, "text": "Note that the two values, d.Tmax and d.Tmin, are grouped together in square brackets and separated by a comma. This is the notation for a vector, or singled dimensional array. Additionally, we have added labels for the lines and these are grouped in the same way. We get a graph like this:" }, { "code": null, "e": 7826, "s": 7519, "text": "Or how about a scatter chart? A scatter chart is often used to see if a pattern can be detected in the data. Here we plot the maximum temperature against the hours of sunshine. As you might expect there is a pattern: a visible correlation — the more hours of sunshine there are, the higher the temperature." }, { "code": null, "e": 7849, "s": 7826, "text": "scatter(d.Tmax, d.Sun)" }, { "code": null, "e": 7999, "s": 7849, "text": "The data we have doesn’t really lend itself to being depicted as a pie chart, so we are going to generate some random data, again — 5 random numbers." }, { "code": null, "e": 8059, "s": 7999, "text": "x = 1:5; y = rand(5); # These are the plotting datapie(x,y)" }, { "code": null, "e": 8104, "s": 8059, "text": "Now we are going to load in a bit more data:" }, { "code": null, "e": 8151, "s": 8104, "text": "d2 = CSV.read(\"londonweather.csv\"`, DataFrame)" }, { "code": null, "e": 8431, "s": 8151, "text": "This is similar to the data table that we have been using but rather bigger as it covers several decades of data rather than just one year. This gives us plenty of rainfall data so that we can see the distribution of the levels of rain that occur in London over a longish period." }, { "code": null, "e": 8468, "s": 8431, "text": "histogram(d2.Rain, label=\"Rainfall\")" }, { "code": null, "e": 8487, "s": 8468, "text": "Here’s the result." }, { "code": null, "e": 8639, "s": 8487, "text": "It’s all very well seeing these charts in the Jupyter environment but to be useful, we need to be able to save them so as to use them in our documents." }, { "code": null, "e": 8673, "s": 8639, "text": "You can save the chart like this:" }, { "code": null, "e": 8737, "s": 8673, "text": "histogram(d2.Rain, label=\"Rainfall\") savefig(\"myhistogram.png\")" }, { "code": null, "e": 8838, "s": 8737, "text": "When this code is run the chart will not be displayed but it will be saved with the file name given." }, { "code": null, "e": 9138, "s": 8838, "text": "I hope that was useful — we’ve looked at the basic charts available in Julia Plots. There is a great deal more to Julia than we have seen in this short article and a lot more that you can do with Plots too, but I hope you have found that this introduction has whetted your appetite to find out more." }, { "code": null, "e": 9308, "s": 9138, "text": "Right click on the three links below to download the files and then copy them in the directory that Jupyter will use. Then in your file list open plotweatherjulia.ipynb." }, { "code": null, "e": 9353, "s": 9308, "text": "The notebook is here: plotweatherjulia.ipynb" }, { "code": null, "e": 9419, "s": 9353, "text": "and the data files are here: london2018.csv and londonweather.csv" }, { "code": null, "e": 9557, "s": 9419, "text": "As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here." } ]
Hailstone Numbers - GeeksforGeeks
29 Apr, 2021 We are provided with a number N. Our task is to generate all the Hailstone Numbers from N and find the number of steps taken by N to reduce to Collatz Conjecture: A problem posed by L. Collatz in 1937, also called the 3x+1 mapping, 3n+1 problem. Let N be a integer. According to Collatz conjecture, if we keep iterating N as following N = N / 2 // For Even N and N = 3 * N + 1 // For Odd N Our number will eventually converge to 1 irrespective of the choice of N. Hailstone Numbers: The sequence of integers generated by Collatz conjecture are called Hailstone Numbers. Examples: Input : N = 7 Output : Hailstone Numbers: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 No. of steps Required: 17 Input : N = 9 Output : Hailstone Numbers: 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 No. of steps Required: 20 In the first example, N = 7. The numbers will be calculated as follows: 7 3 * 7 + 1 = 22 // Since 7 is odd. 22 / 2 = 11 // 22 is even. 3 * 11 + 1 = 34 // 11 is odd. .... and so on upto 1. The idea is simple, we recursively print numbers until we reach base case. C++ Java Python C# PHP Javascript // C++ program to generate hailstone// numbers and calculate steps required// to reduce them to 1#include <bits/stdc++.h>using namespace std; // function to print hailstone numbers// and to calculate the number of steps// requiredint HailstoneNumbers(int N){ static int c; cout << N << " "; if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); }} // Driver codeint main(){ int N = 7; int x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps cout << endl; cout << "Number of Steps: " << x; return 0;} // Java program to generate hailstone// numbers and calculate steps required// to reduce them to 1import java.util.*;class GFG { static int c; // function to print hailstone numbers // and to calculate the number of steps // required static int HailstoneNumbers(int N) { System.out.print(N + " "); if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); } return c; } // Driver code public static void main(String[] args) { int N = 7; int x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps System.out.println(); System.out.println("Number of Steps: " + x); }}/* This code is contributed by Kriti Shukla */ # Python3 program to generate# hailstone numbers and# calculate steps required# to reduce them to 1 # function to print hailstone# numbers and to calculate# the number of steps required def HailstoneNumbers(N, c): print(N, end=" ") if (N == 1 and c == 0): # N is initially 1. return c elif (N == 1 and c != 0): # N is reduced to 1. c = c + 1 elif (N % 2 == 0): # If N is Even. c = c + 1 c = HailstoneNumbers(int(N / 2), c) elif (N % 2 != 0): # N is Odd. c = c + 1 c = HailstoneNumbers(3 * N + 1, c) return c # Driver CodeN = 7 # Function to generate# Hailstone Numbersx = HailstoneNumbers(N, 0) # Output: Number of Stepsprint("\nNumber of Steps: ", x) # This code is contributed# by mits // C# program to generate hailstone// numbers and calculate steps required// to reduce them to 1using System; class GFG { static int c; // function to print hailstone numbers // and to calculate the number of steps // required static int HailstoneNumbers(int N) { Console.Write(N + " "); if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); } return c; } // Driver code public static void Main() { int N = 7; int x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps Console.WriteLine(); Console.WriteLine("Number of Steps: " + x); }}// This code is contributed by vt_m <?php// PHP program to generate // hailstone numbers and// calculate steps required// to reduce them to 1 // function to print hailstone// numbers and to calculate the// number of steps requiredfunction HailstoneNumbers($N){ static $c; echo $N." "; if ($N == 1 && $c == 0) { // N is initially 1. return $c; } else if ($N == 1 && $c != 0) { // N is reduced to 1. $c++; return $c; } else if ($N % 2 == 0) { // If N is Even. $c++; HailstoneNumbers((int)($N / 2)); } else if ($N % 2 != 0) { // N is Odd. $c++; HailstoneNumbers(3 * $N + 1); } return $c;} // Driver Code$N = 7; // Function to generate// Hailstone Numbers$x = HailstoneNumbers($N); // Output: Number of Stepsecho "\nNumber of Steps: ". $x; // This code is contributed// by mits?> <script> // JavaScript program to generate hailstone// numbers and calculate steps required// to reduce them to 1 let c = 0; // function to print hailstone numbers // and to calculate the number of steps // required function HailstoneNumbers(N) { document.write(N + " "); if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); } return c; } // Driver Code let N = 7; let x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps document.write("<br/>"); document.write("Number of Steps: " + x); // This code is contributed by susmitakundugoaldanga.</script> 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 Number of Steps: 17 This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar venkataa_anand314159 susmitakundugoaldanga series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Fizz Buzz Implementation Program to multiply two matrices Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24325, "s": 24297, "text": "\n29 Apr, 2021" }, { "code": null, "e": 24468, "s": 24325, "text": "We are provided with a number N. Our task is to generate all the Hailstone Numbers from N and find the number of steps taken by N to reduce to" }, { "code": null, "e": 24895, "s": 24468, "text": "Collatz Conjecture: A problem posed by L. Collatz in 1937, also called the 3x+1 mapping, 3n+1 problem. Let N be a integer. According to Collatz conjecture, if we keep iterating N as following N = N / 2 // For Even N and N = 3 * N + 1 // For Odd N Our number will eventually converge to 1 irrespective of the choice of N. Hailstone Numbers: The sequence of integers generated by Collatz conjecture are called Hailstone Numbers." }, { "code": null, "e": 24906, "s": 24895, "text": "Examples: " }, { "code": null, "e": 25498, "s": 24906, "text": "Input : N = 7\nOutput : \nHailstone Numbers: 7, 22, 11, 34, 17,\n 52, 26, 13, 40, 20,\n 10, 5, 16, 8, 4, 2,\n 1\nNo. of steps Required: 17\n\nInput : N = 9\nOutput : \nHailstone Numbers: 9, 28, 14, 7, 22, 11,\n 34, 17, 52, 26, 13, \n 40, 20, 10, 5, 16, 8,\n 4, 2, 1\nNo. of steps Required: 20\n\nIn the first example, N = 7. \nThe numbers will be calculated as follows:\n7\n3 * 7 + 1 = 22 // Since 7 is odd.\n22 / 2 = 11 // 22 is even.\n3 * 11 + 1 = 34 // 11 is odd.\n.... and so on upto 1." }, { "code": null, "e": 25574, "s": 25498, "text": "The idea is simple, we recursively print numbers until we reach base case. " }, { "code": null, "e": 25578, "s": 25574, "text": "C++" }, { "code": null, "e": 25583, "s": 25578, "text": "Java" }, { "code": null, "e": 25590, "s": 25583, "text": "Python" }, { "code": null, "e": 25593, "s": 25590, "text": "C#" }, { "code": null, "e": 25597, "s": 25593, "text": "PHP" }, { "code": null, "e": 25608, "s": 25597, "text": "Javascript" }, { "code": "// C++ program to generate hailstone// numbers and calculate steps required// to reduce them to 1#include <bits/stdc++.h>using namespace std; // function to print hailstone numbers// and to calculate the number of steps// requiredint HailstoneNumbers(int N){ static int c; cout << N << \" \"; if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); }} // Driver codeint main(){ int N = 7; int x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps cout << endl; cout << \"Number of Steps: \" << x; return 0;}", "e": 26511, "s": 25608, "text": null }, { "code": "// Java program to generate hailstone// numbers and calculate steps required// to reduce them to 1import java.util.*;class GFG { static int c; // function to print hailstone numbers // and to calculate the number of steps // required static int HailstoneNumbers(int N) { System.out.print(N + \" \"); if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); } return c; } // Driver code public static void main(String[] args) { int N = 7; int x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps System.out.println(); System.out.println(\"Number of Steps: \" + x); }}/* This code is contributed by Kriti Shukla */", "e": 27666, "s": 26511, "text": null }, { "code": "# Python3 program to generate# hailstone numbers and# calculate steps required# to reduce them to 1 # function to print hailstone# numbers and to calculate# the number of steps required def HailstoneNumbers(N, c): print(N, end=\" \") if (N == 1 and c == 0): # N is initially 1. return c elif (N == 1 and c != 0): # N is reduced to 1. c = c + 1 elif (N % 2 == 0): # If N is Even. c = c + 1 c = HailstoneNumbers(int(N / 2), c) elif (N % 2 != 0): # N is Odd. c = c + 1 c = HailstoneNumbers(3 * N + 1, c) return c # Driver CodeN = 7 # Function to generate# Hailstone Numbersx = HailstoneNumbers(N, 0) # Output: Number of Stepsprint(\"\\nNumber of Steps: \", x) # This code is contributed# by mits", "e": 28448, "s": 27666, "text": null }, { "code": "// C# program to generate hailstone// numbers and calculate steps required// to reduce them to 1using System; class GFG { static int c; // function to print hailstone numbers // and to calculate the number of steps // required static int HailstoneNumbers(int N) { Console.Write(N + \" \"); if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); } return c; } // Driver code public static void Main() { int N = 7; int x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps Console.WriteLine(); Console.WriteLine(\"Number of Steps: \" + x); }}// This code is contributed by vt_m", "e": 29567, "s": 28448, "text": null }, { "code": "<?php// PHP program to generate // hailstone numbers and// calculate steps required// to reduce them to 1 // function to print hailstone// numbers and to calculate the// number of steps requiredfunction HailstoneNumbers($N){ static $c; echo $N.\" \"; if ($N == 1 && $c == 0) { // N is initially 1. return $c; } else if ($N == 1 && $c != 0) { // N is reduced to 1. $c++; return $c; } else if ($N % 2 == 0) { // If N is Even. $c++; HailstoneNumbers((int)($N / 2)); } else if ($N % 2 != 0) { // N is Odd. $c++; HailstoneNumbers(3 * $N + 1); } return $c;} // Driver Code$N = 7; // Function to generate// Hailstone Numbers$x = HailstoneNumbers($N); // Output: Number of Stepsecho \"\\nNumber of Steps: \". $x; // This code is contributed// by mits?>", "e": 30439, "s": 29567, "text": null }, { "code": "<script> // JavaScript program to generate hailstone// numbers and calculate steps required// to reduce them to 1 let c = 0; // function to print hailstone numbers // and to calculate the number of steps // required function HailstoneNumbers(N) { document.write(N + \" \"); if (N == 1 && c == 0) { // N is initially 1. return c; } else if (N == 1 && c != 0) { // N is reduced to 1. c++; return c; } else if (N % 2 == 0) { // If N is Even. c++; HailstoneNumbers(N / 2); } else if (N % 2 != 0) { // N is Odd. c++; HailstoneNumbers(3 * N + 1); } return c; } // Driver Code let N = 7; let x; // Function to generate Hailstone // Numbers x = HailstoneNumbers(N); // Output: Number of Steps document.write(\"<br/>\"); document.write(\"Number of Steps: \" + x); // This code is contributed by susmitakundugoaldanga.</script>", "e": 31538, "s": 30439, "text": null }, { "code": null, "e": 31604, "s": 31538, "text": "7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 \nNumber of Steps: 17" }, { "code": null, "e": 32023, "s": 31604, "text": "This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32036, "s": 32023, "text": "Mithun Kumar" }, { "code": null, "e": 32057, "s": 32036, "text": "venkataa_anand314159" }, { "code": null, "e": 32079, "s": 32057, "text": "susmitakundugoaldanga" }, { "code": null, "e": 32086, "s": 32079, "text": "series" }, { "code": null, "e": 32099, "s": 32086, "text": "Mathematical" }, { "code": null, "e": 32112, "s": 32099, "text": "Mathematical" }, { "code": null, "e": 32119, "s": 32112, "text": "series" }, { "code": null, "e": 32217, "s": 32119, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32226, "s": 32217, "text": "Comments" }, { "code": null, "e": 32239, "s": 32226, "text": "Old Comments" }, { "code": null, "e": 32284, "s": 32239, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 32316, "s": 32284, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32360, "s": 32316, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32394, "s": 32360, "text": "Program to add two binary strings" }, { "code": null, "e": 32419, "s": 32394, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32452, "s": 32419, "text": "Program to multiply two matrices" }, { "code": null, "e": 32491, "s": 32452, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 32542, "s": 32491, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 32613, "s": 32542, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Deep Learning with PyTorch. First contact with PyTorch for... | by Jordi TORRES.AI | Towards Data Science
We are to going to be using PyTorch in many of the posts in this series, so the reader need to make sure that she/he is familiar with it. This post will introduce the reader to the basics features of PyTorch which enables us to implement Deep Learning models using Python language. The post doesn’t pretend to be a complete manual of PyTorch, it only introduces the minimum knowledge of PyTorch to start coding neural networks in PyTorch and we will be introducing new features as we need them throughout the series. Enjoy it! Spanish version of this publication medium.com The clear leaders in Deep Learning frameworks arena are now the Google-developed TensorFlow and the Facebook-developed PyTorch, and they are pulling away from the rest of the market in usage, share, and momentum. Three years ago appeared the first version of PyTorch and without question, it is gaining great momentum. Initially incubated by Facebook, PyTorch rapidly developed a reputation from being an ideal flexible framework for rapid experimentation and prototyping gaining thousands of fans within the Deep Learning community. For instance, PhD students in my research team prefer to use PyTorch because it allows to them to write native looking Python code and still get all the benefits of a good framework like auto-differentiation and built-in optimization. This is the reason I decided to use PyTorch in this series. Though PyTorch has gained momentum in the marketplace thanks to Facebook (and AWS), TensorFlow continues to be ahead in all aspects and is the most used for the industry right now. Yo can read this brief post “TensorFlow vs PyTorch: The battle continues” for a more detail about both environments. I suggest using the Colaboratory (Colab) offered by Google to execute the code described in this post. It basically consists of a Jupyter notebook environment that requires no configuration and runs completely in the Cloud allowing the use different Deep Learning libraries as PyTorch and TensorFlow. One important feature of Colab is that it provides GPU (and TPU) totally free. Detailed information about the service can be found on the faq page. By default, Colab notebooks run on CPU. You can switch your notebook to run with GPU (or TPU). In order to obtain access to one GPU you need to choose the tab “Runtime” and then select “Change runtime type” as shown in the following figure: When a pop-up window appears, select GPU. Ensure “Hardware accelerator” is set to GPU (the default is CPU). Afterwards, ensure that you are connected to the runtime (there is a green check next to “CONNECTED” in the menu ribbon): Now you are able to run the code presented in this post. I suggest to copy & paste the code of this post in a Colab notebook in order to see the execution meanwhile you are reading this post. Ready? The entire code of this post can be found on GitHub and can be run as a Colab google notebook using this link. In this post we will program a neural network model that classifies handwritten digits presented in the previous post. Remember that we created a mathematical model that, given an image, the model identify the number it represents returning a vector with 10 positions indicating the likelihood of each of the ten possible digits. In order to guide the explanation, we will follow a list of steps to be taken to program a neural network: Import required librariesLoad and Preprocess the DataDefine the ModelDefine the Optimizer and the Loss FunctionTrain the ModelEvaluate the Model Import required libraries Load and Preprocess the Data Define the Model Define the Optimizer and the Loss Function Train the Model Evaluate the Model Let’s go for it! We always need to import torch, the core Python library for PyTorch. For our example we will also import the torchvision package, as well as the usual libraries numpy and matplotlib. import torch import torchvision For clarity of the code we could define here some hyperparameters that we will need for training: import numpy as np import matplotlib.pyplot as plt EPOCH = 10 BATCH_SIZE= 64 Next step is to load data that will be used to train our neural network . We will use the MNIST dataset already introduced in the previous post, which can be downloaded from The MNIST database page using torchvision.dataset. PyTorch Datasets are objects that return a single datapoint on request. Then it is passed on to a Dataloader which handles batching of datapoints and parallelism. This is the code for our example: xy_trainPT = torchvision.datasets.MNIST(root='./data', train=True, download=True,transform= torchvision.transforms.Compose( [torchvision.transforms.ToTensor()]))xy_trainPT_loader = torch.utils.data.DataLoader (xy_trainPT, batch_size=BATCH_SIZE) Because data is usually too large to fit data into CPU or GPU memory at once, it is split into batches of equal size. Every batch includes data samples and target labels, and both of them have to be tensors (which we will present below). The BATCH_SIZE argument indicates the number of data that we will use for each update of the model parameters. This dataset contains 60,000 images of hand-made digits to train the model and it is ideal for entering pattern recognition techniques for the first time without having to spend much time preprocessing and formatting data, both very important and expensive steps in the analysis of data and of special complexity when working with images. We can verify that the previous code have loaded the expected data with the library matplotlib.pyplot : fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): image, label = xy_trainPT [idx] ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(torch.squeeze(image, dim = 0).numpy(), cmap=plt.cm.binary) ax.set_title(str(label)) Remember that in the previous post we explained that to facilitate the entry of data into our neural network we make a transformation of the input (image) from 2 dimensions (2D) to a vector of 1 dimension (1D). That is, the matrix of 28×28 numbers can be represented by a vector (array) of 784 numbers (concatenating row by row). We will apply this transformation when we ingest the data to the neural network using this type of transformation (e.g. applied to the first image): image, _ = xy_trainPT[0] print(image.size())image_flatten = image.view(image.shape[0], -1)print (image_flatten.size())torch.Size([1, 28, 28]) torch.Size([1, 784]) A Tensor is a multi-dimensional array, fundamental building block of PyTorch, equivalent to NumPy, that stores a collection of numbers: a = torch.randn(2, 3)print(a)tensor([[ 1.1049, 0.2676, -0.4528], [ 0.0105, -0.5095, 0.7777]]) And we can know its dimensions and size with: print(a.size())print(a.dim())torch.Size([2, 3])2 Apart from dimensions, a tensor is characterized by the type of its elements. For this we have the dtype argument that is deliberately similar to the standard NumPy argument type of the same name: matrix=torch.zeros([2, 4], dtype=torch.int32)print(matrix)tensor([[0, 0, 0, 0], [0, 0, 0, 0]], dtype=torch.int32)print(matrix.dtype)torch.int32 Torch defines nine types of CPU tensor and nine types of GPU tensor: As you can see there are a specific types for GPU tensors. PyTorch transparently supports CUDA GPUs, which means that all operations have two versions — CPU and GPU — that are automatically selected. The decision is made based on the type of tensors that you are operating on. There are different ways to create a tensor in PyTorch: calling a constructor of the required type, converting a NumPy array (or a Python list) into a tensor or asking PyTorch to create a tensor with specific data. For example we can use torch.zeros() function to create a tensor filled with zero values: b = torch.zeros(2, 3)print(b)tensor([[0., 0., 0.], [0., 0., 0.]])c = torch.ones(2, 3)print(c)tensor([[1., 1., 1.], [1., 1., 1.]]) An element of a tensor can be accessed using its index (which starts at 0): c[0,0]=222 print(c)tensor([[222., 1., 1.], [ 1., 1., 1.]]) Furthermore, just like in the usual data structures in Python, we can use the range notation in indexing to select and manipulate portions of the tensor with the help of the “ : ” character. Indexes start at 0 and we can use negative values for the indexes, where -1 is the last element and so on. Let’s look at a the following code for examples: x = torch.Tensor([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print (x)tensor([[ 1., 2., 3., 4.], [ 5., 6., 7., 8.], [ 9., 10., 11., 12.]])print (“x column 1: “, x[:, 1])print (“x row 0: “, x[0, :])print (“x rows 0,1 & cols 1,2: \n”, x[0:2, 1:3])x column 1: tensor([ 2., 6., 10.])x row 0: tensor([1., 2., 3., 4.])x rows 0,1 & cols 1,2:tensor([[2., 3.], [6., 7.]]) PyTorch tensors can be converted to NumPy matrices and vice versa very efficiently. By doing so, we can take advantage of the tremendous amount of functionality in Python ecosystem that has evolved around the NumPy array type. Let’s see with a simple code how it works: x = np.array([[1,2], [3,4], [5,6]])print (x)[[1 2] [3 4] [5 6]] This array x can be easily converted to a tensor as follows: y=torch.from_numpy(x)print(y)tensor([[1, 2], [3, 4], [5, 6]]) We can see that the second print indicates that it is a tensor. Conversely, if we want to transform a tensor into a NumPy array, we can do it as follows: z = y.numpy()print (z)[[1. 2.] [3. 4.] [5. 6.]] We will use reshape() function, that returns a tensor with the same data and number of elements as input , but with the specified shape. When possible, the returned tensor will be a view of input. Otherwise, it will be a copy (in memory): one_d = torch.arange(0,16)print (one_d)two_d= one_d.reshape(4,4)print (two_d)print(two_d.size())tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])tensor([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])torch.Size([4, 4]) In the torch.nn package, you can find many predefined classes providing the basic functionality blocks required for programming neural networks. To define the model presented in the previous post, it can be done with the Sequentialclass from this package: modelPT= torch.nn.Sequential( torch.nn.Linear(784,10), torch.nn.Sigmoid(), torch.nn.Linear(10,10), torch.nn.LogSoftmax(dim=1) ) The code is defining a neural network composed of a two dense layers (linear layer) of 10 neurons each, one with a Sigmoid activation function and the other with the Softmax activation function. As we advance the series we will introduce other activation functions, as ReLU, that we will use in a next post in this series. I would like to highlight that the previous code adds a small transformation to the neural network presented in the previous post: additionally, it is applying a logarithm operation to each of the outputs of the last layer. Specifically, the LogSoftmax function which can be seen as: where Softmax is calculated as defined in the previous post. There are a number of practical and theoretical advantages of LogSoftmax over Softmax that motivate its use in building neural networks that we will discuss in a later section. In summary, the network that we have defined can be visually represented as shown in the following figure: The first layer of the neural network receives a tensor of 784 characteristics that represent the pixels that are passed to each and every one of the 10 neurons in the first layer. Once these 10 neurons have processed this information, each of them passes the information to all the neurons in the next layer, that is, all 10 neurons in the first layer are connected to all 10 neurons in the second layer. The second layer is a layer with a softmax activation function of 10 neurons, which means it will return a tensor of 10 probability values, representing the 10 possible digits. In general, the output layer of a classification network will have as many neurons as classes, except in a binary classification, where it is only needed one neuron. Let’s remember that we have used a LogSoftmax layer, instead of Softmax, so that each value that returns will be the logarithm of the probability that the image of the current digit belongs to each of the classes. We can use this simple example to analyze the parameters that make up a neural network. For example, in the first layer, for each of the ten neurons, 784 parameters are required for the weights, and therefore 10 × 784 parameters to store the weights of the 10 neurons. Furthermore, 10 additional parameters are required for the 10 biases corresponding to each of the neurons. Therefore, for the first layer 7,850 parameters are required. In the second layer, being a softmax function, it is required to connect all its 10 neurons with the 10 neurons of the previous layer and, therefore, 10 × 10 parameters are required for the weights; in addition to the 10 biases corresponding to each node. This gives us a total of 110 required parameters in the second layer. In summary, for our extremely simple neural network we see that 7,960 parameters are required, 7,850 parameters for the first layer and 110 for the second. By subclassing the nn.Module, the base class for all neural network modules, we can create our own building blocks, which can be stacked together and reused later, which is what is usually done. But given the initiation nature of this post, we can move forward with this basic way of defining our neural networks. The reader can check the oficial documentation for more details on this topic. As we shown in the previous post these models are trained by solving iteratively an unconstrained optimization problem. In each iteration, a random batch of the training data is fed into the model to compute the Loss function value. Then, the gradient of the Loss function with respect to the weights of the network is computed (backpropagation) and an update of the weights in the negative direction of the gradient is done. These networks are trained until they converge into a Loss function minimum. Loss functions, around 20 different in PyTorch, reside in the nn package and are implemented as an nn.Module subclass. Some of the common standard loss functions that we will use in this series are: nn.MSELoss: The mean square error between arguments, which is the standard loss for regression problems. nn.NLLLoss: It computes the “maximum likelihood” criteria and generaly are used in multi-class classification problems (as our MNIST example). nn.CrossEntropyLoss: computes the same as nn.NLLLoss, however it expects raw scores for each class and applies LogSoftmax internally (while nn.NLLLoss expects to have log probabilities as the input). Since we are dealing with a multi-class classification problem, we chose cross-entropy as our Loss function. In this example, we use negative log-likelihood nn.NLLLoss () that combines with the softmax nn.LogSoftmax () function that we have already introduced. As we said we don’t apply Softmax to increase the numerical stability of the training process presenting an alternative way to calculate the Softmax first, which uses exponentiation, and then calculating cross-entropy loss, which uses a logarithm of probabilities. If the reader is interested in more details about this, I recommend having a look at this article. The downside of defining a neural network with LogSoftmax is that we need to remember to apply softmax every time we need to get probabilities from our neural network output. In general, the reader will see the Loss function assigned to criterion in PyTorch codes: criterion = torch.nn.NLLLoss() Therefore the way to calculate the error made will be as: loss = criterion(logps, labels) where we indicate in the arguments the output of our neural network and the correct label. Remember that the optimizer takes the gradients of model parameters and change these parameters in order to decrease the loss value. We make use of torch.optim which is a module provided by PyTorch to optimize the model, perform gradient descent and update the weights by backpropagation. This package allows us to choose between several algorithms (AdaGrad, RMSProp, Adam, etc.) that are different variants of the gradient descent algorithm, the generic optimization algorithm capable of finding optimal solutions to a wide range of problems. At the moment in this example we will use the basic Stochastic Gradient Descent (SGD): optimizer = torch.optim.SGD(modelPT.parameters(), lr=0.01) The arguments are the parameters that the optimizer must adjust and a learning rate that indicates how these adjustments should be. Remember that the optimizer iteratively adjusts the parameters (weights and biases) of the model in the right direction (adding a “little” or subtracting a “little” to its value, where this “little” is defined by the learning rate) so that lead to a decrease in error. In general, the procedure is repeated until the error falls below an acceptable level. Derivatives are used to calculate the correct direction, and specifically the gradient of the error with respect to the parameters. The autograd package in PyTorch provides exactly this functionality by automatic differentiation to automate the computation of backward passes in neural networks. Once our model has been defined and the learning method configured, it is ready to be trained. Therefore, we only have to define the training loop that will iterate over all the data so that the optimizer iteratively adjusts the weights. Let’s discuss the common blueprint of a training loop with these lines of code: 1: for e in range(EPOCHS): running_loss = 02: for images, labels in xy_trainPT_loader:3: images = images.view(images.shape[0], -1)4: output = modelPT(images)5: loss = criterion(output, labels)6: loss.backward()7: optimizer.step()8: optimizer.zero_grad() running_loss += loss.item() print(“Epoch {} — Training loss: {}”.format(e, running_loss/len(xy_trainPT_loader))) Line 1: Usually, the training loop iterates over our data over and over again. Remember that one iteration over a full set of examples is called an epoch. The EPOCHS variable indicates the number of iterations over the full set of examples. Line 2: We already presented that data is usually too large to fit into CPU or GPU memory at once, so it is split into batches of equal size. Every batch includes data samples and target labels, and both of them have to be tensors. Line 3: To facilitate the entry of data into our neural network we must make a transformation of the input (image) from 2 dimensions (2D) to a vector of 1 dimension (1D). Line 4: We pass each batch of image tensors into the model which will return a tensor having predictions for that batch, the forward pass. Line 5: Having got the predictions we pass them into the cross-entropy Loss function ( criterion ) along with their actual labels and calculate the Loss. Usually, Loss functions accept two arguments: output from the network (prediction) and desired output (ground-truth data, which is also called the label of the data sample). Some PyTorch’s Loss functions take class labels as their targets (e.g. NLLloss), so if we use them (as in our case), we don’t need to convert targets into one-hot vectors as we presented in the previous post (for ease the explanation). Line 6: We do a backward pass using the Loss value in order to compute gradient of the Loss with respect to model parameters. After loss.backward() call is finished, we have the gradients accumulated. Line 7: Now it’s time for the optimizer to modify the model parameters with the method step() that takes all gradients from the parameters and applies them. Line 8: The last, but not least, piece of the training loop is our responsibility to zero gradients of parameters. Calling zero_grad() on our network clear the gradients of all optimized variables. In order to check how the training process evolve we have added a couple of lines of code in this training loop. First, we get the training loss for the entire epoch by adding all the losses for each batch iteration: running_loss += loss.item() And second averaging it over by the iteration count and print it: print(“Epoch {} — Training loss: {}”.format(e, running_loss/len(xy_trainPT_loader))) Looking at this output we see how the training loop adjusts the weights of the network so that in each iteration the loss function produces a smaller loss. Epoch 0 — Training loss: 2.1822925415882932 Epoch 1 — Training loss: 1.8671700155048736Epoch 2 — Training loss: 1.5379922698809902Epoch 3 — Training loss: 1.287035460029838. . .Epoch 15 — Training loss: 0.5162741374264139Epoch 16 — Training loss: 0.49991638108547815Epoch 17 — Training loss: 0.48541215611800453Epoch 18 — Training loss: 0.4724724407929347Epoch 19 — Training loss: 0.4608637086554631 In PyTorch, there is no a “prefab” data model tuning function as fit() in Keras or Scikit-learn, so the training loop must be specified by the programmer. Now, that we have finished the training of our model, we will probably want to test how well our model was generalized by applying it on a test dataset. In PyTorch it is required again that the programmer specifies the evaluation loop: xy_testPT = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=torchvision.transforms. Compose([torchvision.transforms.ToTensor()]))xy_test_loaderPT = torch.utils.data.DataLoader(xy_testPT)correct_count, all_count = 0, 0for images,labels in xy_test_loaderPT: for i in range(len(labels)): img = images[i].view(1, 784) logps = modelPT(img) ps = torch.exp(logps) probab = list(ps.detach().numpy()[0]) pred_label = probab.index(max(probab)) true_label = labels.numpy()[i] if(true_label == pred_label): correct_count += 1 all_count += 1print("\nAccuracy of the model =", (correct_count/all_count)) Accuracy of the model = 0.8657 The reader can see the similarity of the instructions in this loop with those of the previous training loop. But in this case, instead of keeping the Loss calculation, the Accuracy is calculated, that is, the percentage of hits with data that the model has never seen before. And that’s all! You have already programmed an entire neural network. Congrats! See you in the next post! by UPC Barcelona Tech and Barcelona Supercomputing Center A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence. I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made. Disclaimers — These posts were written during this period of lockdown in Barcelona as a personal distraction and dissemination of scientific knowledge, in case it could be of help to someone, but without the purpose of being an academic reference document in the DRL area. If the reader needs a more rigorous document, the last post in the series offers an extensive list of academic resources and books that the reader can consult. The author is aware that this series of posts may contain some errors and suffers from a revision of the English text to improve it if the purpose were an academic document. But although the author would like to improve the content in quantity and quality, his professional commitments do not leave him free time to do so. However, the author agrees to refine all those errors that readers can report as soon as he can.
[ { "code": null, "e": 698, "s": 171, "text": "We are to going to be using PyTorch in many of the posts in this series, so the reader need to make sure that she/he is familiar with it. This post will introduce the reader to the basics features of PyTorch which enables us to implement Deep Learning models using Python language. The post doesn’t pretend to be a complete manual of PyTorch, it only introduces the minimum knowledge of PyTorch to start coding neural networks in PyTorch and we will be introducing new features as we need them throughout the series. Enjoy it!" }, { "code": null, "e": 734, "s": 698, "text": "Spanish version of this publication" }, { "code": null, "e": 745, "s": 734, "text": "medium.com" }, { "code": null, "e": 958, "s": 745, "text": "The clear leaders in Deep Learning frameworks arena are now the Google-developed TensorFlow and the Facebook-developed PyTorch, and they are pulling away from the rest of the market in usage, share, and momentum." }, { "code": null, "e": 1574, "s": 958, "text": "Three years ago appeared the first version of PyTorch and without question, it is gaining great momentum. Initially incubated by Facebook, PyTorch rapidly developed a reputation from being an ideal flexible framework for rapid experimentation and prototyping gaining thousands of fans within the Deep Learning community. For instance, PhD students in my research team prefer to use PyTorch because it allows to them to write native looking Python code and still get all the benefits of a good framework like auto-differentiation and built-in optimization. This is the reason I decided to use PyTorch in this series." }, { "code": null, "e": 1872, "s": 1574, "text": "Though PyTorch has gained momentum in the marketplace thanks to Facebook (and AWS), TensorFlow continues to be ahead in all aspects and is the most used for the industry right now. Yo can read this brief post “TensorFlow vs PyTorch: The battle continues” for a more detail about both environments." }, { "code": null, "e": 2321, "s": 1872, "text": "I suggest using the Colaboratory (Colab) offered by Google to execute the code described in this post. It basically consists of a Jupyter notebook environment that requires no configuration and runs completely in the Cloud allowing the use different Deep Learning libraries as PyTorch and TensorFlow. One important feature of Colab is that it provides GPU (and TPU) totally free. Detailed information about the service can be found on the faq page." }, { "code": null, "e": 2562, "s": 2321, "text": "By default, Colab notebooks run on CPU. You can switch your notebook to run with GPU (or TPU). In order to obtain access to one GPU you need to choose the tab “Runtime” and then select “Change runtime type” as shown in the following figure:" }, { "code": null, "e": 2792, "s": 2562, "text": "When a pop-up window appears, select GPU. Ensure “Hardware accelerator” is set to GPU (the default is CPU). Afterwards, ensure that you are connected to the runtime (there is a green check next to “CONNECTED” in the menu ribbon):" }, { "code": null, "e": 2991, "s": 2792, "text": "Now you are able to run the code presented in this post. I suggest to copy & paste the code of this post in a Colab notebook in order to see the execution meanwhile you are reading this post. Ready?" }, { "code": null, "e": 3102, "s": 2991, "text": "The entire code of this post can be found on GitHub and can be run as a Colab google notebook using this link." }, { "code": null, "e": 3432, "s": 3102, "text": "In this post we will program a neural network model that classifies handwritten digits presented in the previous post. Remember that we created a mathematical model that, given an image, the model identify the number it represents returning a vector with 10 positions indicating the likelihood of each of the ten possible digits." }, { "code": null, "e": 3539, "s": 3432, "text": "In order to guide the explanation, we will follow a list of steps to be taken to program a neural network:" }, { "code": null, "e": 3684, "s": 3539, "text": "Import required librariesLoad and Preprocess the DataDefine the ModelDefine the Optimizer and the Loss FunctionTrain the ModelEvaluate the Model" }, { "code": null, "e": 3710, "s": 3684, "text": "Import required libraries" }, { "code": null, "e": 3739, "s": 3710, "text": "Load and Preprocess the Data" }, { "code": null, "e": 3756, "s": 3739, "text": "Define the Model" }, { "code": null, "e": 3799, "s": 3756, "text": "Define the Optimizer and the Loss Function" }, { "code": null, "e": 3815, "s": 3799, "text": "Train the Model" }, { "code": null, "e": 3834, "s": 3815, "text": "Evaluate the Model" }, { "code": null, "e": 3851, "s": 3834, "text": "Let’s go for it!" }, { "code": null, "e": 4034, "s": 3851, "text": "We always need to import torch, the core Python library for PyTorch. For our example we will also import the torchvision package, as well as the usual libraries numpy and matplotlib." }, { "code": null, "e": 4066, "s": 4034, "text": "import torch import torchvision" }, { "code": null, "e": 4164, "s": 4066, "text": "For clarity of the code we could define here some hyperparameters that we will need for training:" }, { "code": null, "e": 4241, "s": 4164, "text": "import numpy as np import matplotlib.pyplot as plt EPOCH = 10 BATCH_SIZE= 64" }, { "code": null, "e": 4663, "s": 4241, "text": "Next step is to load data that will be used to train our neural network . We will use the MNIST dataset already introduced in the previous post, which can be downloaded from The MNIST database page using torchvision.dataset. PyTorch Datasets are objects that return a single datapoint on request. Then it is passed on to a Dataloader which handles batching of datapoints and parallelism. This is the code for our example:" }, { "code": null, "e": 4964, "s": 4663, "text": "xy_trainPT = torchvision.datasets.MNIST(root='./data', train=True, download=True,transform= torchvision.transforms.Compose( [torchvision.transforms.ToTensor()]))xy_trainPT_loader = torch.utils.data.DataLoader (xy_trainPT, batch_size=BATCH_SIZE)" }, { "code": null, "e": 5313, "s": 4964, "text": "Because data is usually too large to fit data into CPU or GPU memory at once, it is split into batches of equal size. Every batch includes data samples and target labels, and both of them have to be tensors (which we will present below). The BATCH_SIZE argument indicates the number of data that we will use for each update of the model parameters." }, { "code": null, "e": 5652, "s": 5313, "text": "This dataset contains 60,000 images of hand-made digits to train the model and it is ideal for entering pattern recognition techniques for the first time without having to spend much time preprocessing and formatting data, both very important and expensive steps in the analysis of data and of special complexity when working with images." }, { "code": null, "e": 5756, "s": 5652, "text": "We can verify that the previous code have loaded the expected data with the library matplotlib.pyplot :" }, { "code": null, "e": 6022, "s": 5756, "text": "fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): image, label = xy_trainPT [idx] ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(torch.squeeze(image, dim = 0).numpy(), cmap=plt.cm.binary) ax.set_title(str(label))" }, { "code": null, "e": 6352, "s": 6022, "text": "Remember that in the previous post we explained that to facilitate the entry of data into our neural network we make a transformation of the input (image) from 2 dimensions (2D) to a vector of 1 dimension (1D). That is, the matrix of 28×28 numbers can be represented by a vector (array) of 784 numbers (concatenating row by row)." }, { "code": null, "e": 6501, "s": 6352, "text": "We will apply this transformation when we ingest the data to the neural network using this type of transformation (e.g. applied to the first image):" }, { "code": null, "e": 6664, "s": 6501, "text": "image, _ = xy_trainPT[0] print(image.size())image_flatten = image.view(image.shape[0], -1)print (image_flatten.size())torch.Size([1, 28, 28]) torch.Size([1, 784])" }, { "code": null, "e": 6800, "s": 6664, "text": "A Tensor is a multi-dimensional array, fundamental building block of PyTorch, equivalent to NumPy, that stores a collection of numbers:" }, { "code": null, "e": 6901, "s": 6800, "text": "a = torch.randn(2, 3)print(a)tensor([[ 1.1049, 0.2676, -0.4528], [ 0.0105, -0.5095, 0.7777]])" }, { "code": null, "e": 6947, "s": 6901, "text": "And we can know its dimensions and size with:" }, { "code": null, "e": 6996, "s": 6947, "text": "print(a.size())print(a.dim())torch.Size([2, 3])2" }, { "code": null, "e": 7193, "s": 6996, "text": "Apart from dimensions, a tensor is characterized by the type of its elements. For this we have the dtype argument that is deliberately similar to the standard NumPy argument type of the same name:" }, { "code": null, "e": 7344, "s": 7193, "text": "matrix=torch.zeros([2, 4], dtype=torch.int32)print(matrix)tensor([[0, 0, 0, 0], [0, 0, 0, 0]], dtype=torch.int32)print(matrix.dtype)torch.int32" }, { "code": null, "e": 7413, "s": 7344, "text": "Torch defines nine types of CPU tensor and nine types of GPU tensor:" }, { "code": null, "e": 7690, "s": 7413, "text": "As you can see there are a specific types for GPU tensors. PyTorch transparently supports CUDA GPUs, which means that all operations have two versions — CPU and GPU — that are automatically selected. The decision is made based on the type of tensors that you are operating on." }, { "code": null, "e": 7995, "s": 7690, "text": "There are different ways to create a tensor in PyTorch: calling a constructor of the required type, converting a NumPy array (or a Python list) into a tensor or asking PyTorch to create a tensor with specific data. For example we can use torch.zeros() function to create a tensor filled with zero values:" }, { "code": null, "e": 8139, "s": 7995, "text": "b = torch.zeros(2, 3)print(b)tensor([[0., 0., 0.], [0., 0., 0.]])c = torch.ones(2, 3)print(c)tensor([[1., 1., 1.], [1., 1., 1.]])" }, { "code": null, "e": 8215, "s": 8139, "text": "An element of a tensor can be accessed using its index (which starts at 0):" }, { "code": null, "e": 8300, "s": 8215, "text": "c[0,0]=222 print(c)tensor([[222., 1., 1.], [ 1., 1., 1.]]) " }, { "code": null, "e": 8647, "s": 8300, "text": "Furthermore, just like in the usual data structures in Python, we can use the range notation in indexing to select and manipulate portions of the tensor with the help of the “ : ” character. Indexes start at 0 and we can use negative values for the indexes, where -1 is the last element and so on. Let’s look at a the following code for examples:" }, { "code": null, "e": 9025, "s": 8647, "text": "x = torch.Tensor([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print (x)tensor([[ 1., 2., 3., 4.], [ 5., 6., 7., 8.], [ 9., 10., 11., 12.]])print (“x column 1: “, x[:, 1])print (“x row 0: “, x[0, :])print (“x rows 0,1 & cols 1,2: \\n”, x[0:2, 1:3])x column 1: tensor([ 2., 6., 10.])x row 0: tensor([1., 2., 3., 4.])x rows 0,1 & cols 1,2:tensor([[2., 3.], [6., 7.]])" }, { "code": null, "e": 9295, "s": 9025, "text": "PyTorch tensors can be converted to NumPy matrices and vice versa very efficiently. By doing so, we can take advantage of the tremendous amount of functionality in Python ecosystem that has evolved around the NumPy array type. Let’s see with a simple code how it works:" }, { "code": null, "e": 9359, "s": 9295, "text": "x = np.array([[1,2], [3,4], [5,6]])print (x)[[1 2] [3 4] [5 6]]" }, { "code": null, "e": 9420, "s": 9359, "text": "This array x can be easily converted to a tensor as follows:" }, { "code": null, "e": 9494, "s": 9420, "text": "y=torch.from_numpy(x)print(y)tensor([[1, 2], [3, 4], [5, 6]])" }, { "code": null, "e": 9648, "s": 9494, "text": "We can see that the second print indicates that it is a tensor. Conversely, if we want to transform a tensor into a NumPy array, we can do it as follows:" }, { "code": null, "e": 9696, "s": 9648, "text": "z = y.numpy()print (z)[[1. 2.] [3. 4.] [5. 6.]]" }, { "code": null, "e": 9935, "s": 9696, "text": "We will use reshape() function, that returns a tensor with the same data and number of elements as input , but with the specified shape. When possible, the returned tensor will be a view of input. Otherwise, it will be a copy (in memory):" }, { "code": null, "e": 10207, "s": 9935, "text": "one_d = torch.arange(0,16)print (one_d)two_d= one_d.reshape(4,4)print (two_d)print(two_d.size())tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])tensor([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])torch.Size([4, 4])" }, { "code": null, "e": 10463, "s": 10207, "text": "In the torch.nn package, you can find many predefined classes providing the basic functionality blocks required for programming neural networks. To define the model presented in the previous post, it can be done with the Sequentialclass from this package:" }, { "code": null, "e": 10646, "s": 10463, "text": "modelPT= torch.nn.Sequential( torch.nn.Linear(784,10), torch.nn.Sigmoid(), torch.nn.Linear(10,10), torch.nn.LogSoftmax(dim=1) )" }, { "code": null, "e": 10969, "s": 10646, "text": "The code is defining a neural network composed of a two dense layers (linear layer) of 10 neurons each, one with a Sigmoid activation function and the other with the Softmax activation function. As we advance the series we will introduce other activation functions, as ReLU, that we will use in a next post in this series." }, { "code": null, "e": 11253, "s": 10969, "text": "I would like to highlight that the previous code adds a small transformation to the neural network presented in the previous post: additionally, it is applying a logarithm operation to each of the outputs of the last layer. Specifically, the LogSoftmax function which can be seen as:" }, { "code": null, "e": 11491, "s": 11253, "text": "where Softmax is calculated as defined in the previous post. There are a number of practical and theoretical advantages of LogSoftmax over Softmax that motivate its use in building neural networks that we will discuss in a later section." }, { "code": null, "e": 11598, "s": 11491, "text": "In summary, the network that we have defined can be visually represented as shown in the following figure:" }, { "code": null, "e": 12004, "s": 11598, "text": "The first layer of the neural network receives a tensor of 784 characteristics that represent the pixels that are passed to each and every one of the 10 neurons in the first layer. Once these 10 neurons have processed this information, each of them passes the information to all the neurons in the next layer, that is, all 10 neurons in the first layer are connected to all 10 neurons in the second layer." }, { "code": null, "e": 12561, "s": 12004, "text": "The second layer is a layer with a softmax activation function of 10 neurons, which means it will return a tensor of 10 probability values, representing the 10 possible digits. In general, the output layer of a classification network will have as many neurons as classes, except in a binary classification, where it is only needed one neuron. Let’s remember that we have used a LogSoftmax layer, instead of Softmax, so that each value that returns will be the logarithm of the probability that the image of the current digit belongs to each of the classes." }, { "code": null, "e": 12999, "s": 12561, "text": "We can use this simple example to analyze the parameters that make up a neural network. For example, in the first layer, for each of the ten neurons, 784 parameters are required for the weights, and therefore 10 × 784 parameters to store the weights of the 10 neurons. Furthermore, 10 additional parameters are required for the 10 biases corresponding to each of the neurons. Therefore, for the first layer 7,850 parameters are required." }, { "code": null, "e": 13325, "s": 12999, "text": "In the second layer, being a softmax function, it is required to connect all its 10 neurons with the 10 neurons of the previous layer and, therefore, 10 × 10 parameters are required for the weights; in addition to the 10 biases corresponding to each node. This gives us a total of 110 required parameters in the second layer." }, { "code": null, "e": 13481, "s": 13325, "text": "In summary, for our extremely simple neural network we see that 7,960 parameters are required, 7,850 parameters for the first layer and 110 for the second." }, { "code": null, "e": 13874, "s": 13481, "text": "By subclassing the nn.Module, the base class for all neural network modules, we can create our own building blocks, which can be stacked together and reused later, which is what is usually done. But given the initiation nature of this post, we can move forward with this basic way of defining our neural networks. The reader can check the oficial documentation for more details on this topic." }, { "code": null, "e": 14377, "s": 13874, "text": "As we shown in the previous post these models are trained by solving iteratively an unconstrained optimization problem. In each iteration, a random batch of the training data is fed into the model to compute the Loss function value. Then, the gradient of the Loss function with respect to the weights of the network is computed (backpropagation) and an update of the weights in the negative direction of the gradient is done. These networks are trained until they converge into a Loss function minimum." }, { "code": null, "e": 14576, "s": 14377, "text": "Loss functions, around 20 different in PyTorch, reside in the nn package and are implemented as an nn.Module subclass. Some of the common standard loss functions that we will use in this series are:" }, { "code": null, "e": 14681, "s": 14576, "text": "nn.MSELoss: The mean square error between arguments, which is the standard loss for regression problems." }, { "code": null, "e": 14824, "s": 14681, "text": "nn.NLLLoss: It computes the “maximum likelihood” criteria and generaly are used in multi-class classification problems (as our MNIST example)." }, { "code": null, "e": 15024, "s": 14824, "text": "nn.CrossEntropyLoss: computes the same as nn.NLLLoss, however it expects raw scores for each class and applies LogSoftmax internally (while nn.NLLLoss expects to have log probabilities as the input)." }, { "code": null, "e": 15649, "s": 15024, "text": "Since we are dealing with a multi-class classification problem, we chose cross-entropy as our Loss function. In this example, we use negative log-likelihood nn.NLLLoss () that combines with the softmax nn.LogSoftmax () function that we have already introduced. As we said we don’t apply Softmax to increase the numerical stability of the training process presenting an alternative way to calculate the Softmax first, which uses exponentiation, and then calculating cross-entropy loss, which uses a logarithm of probabilities. If the reader is interested in more details about this, I recommend having a look at this article." }, { "code": null, "e": 15824, "s": 15649, "text": "The downside of defining a neural network with LogSoftmax is that we need to remember to apply softmax every time we need to get probabilities from our neural network output." }, { "code": null, "e": 15914, "s": 15824, "text": "In general, the reader will see the Loss function assigned to criterion in PyTorch codes:" }, { "code": null, "e": 15945, "s": 15914, "text": "criterion = torch.nn.NLLLoss()" }, { "code": null, "e": 16003, "s": 15945, "text": "Therefore the way to calculate the error made will be as:" }, { "code": null, "e": 16035, "s": 16003, "text": "loss = criterion(logps, labels)" }, { "code": null, "e": 16126, "s": 16035, "text": "where we indicate in the arguments the output of our neural network and the correct label." }, { "code": null, "e": 16757, "s": 16126, "text": "Remember that the optimizer takes the gradients of model parameters and change these parameters in order to decrease the loss value. We make use of torch.optim which is a module provided by PyTorch to optimize the model, perform gradient descent and update the weights by backpropagation. This package allows us to choose between several algorithms (AdaGrad, RMSProp, Adam, etc.) that are different variants of the gradient descent algorithm, the generic optimization algorithm capable of finding optimal solutions to a wide range of problems. At the moment in this example we will use the basic Stochastic Gradient Descent (SGD):" }, { "code": null, "e": 16816, "s": 16757, "text": "optimizer = torch.optim.SGD(modelPT.parameters(), lr=0.01)" }, { "code": null, "e": 17304, "s": 16816, "text": "The arguments are the parameters that the optimizer must adjust and a learning rate that indicates how these adjustments should be. Remember that the optimizer iteratively adjusts the parameters (weights and biases) of the model in the right direction (adding a “little” or subtracting a “little” to its value, where this “little” is defined by the learning rate) so that lead to a decrease in error. In general, the procedure is repeated until the error falls below an acceptable level." }, { "code": null, "e": 17600, "s": 17304, "text": "Derivatives are used to calculate the correct direction, and specifically the gradient of the error with respect to the parameters. The autograd package in PyTorch provides exactly this functionality by automatic differentiation to automate the computation of backward passes in neural networks." }, { "code": null, "e": 17918, "s": 17600, "text": "Once our model has been defined and the learning method configured, it is ready to be trained. Therefore, we only have to define the training loop that will iterate over all the data so that the optimizer iteratively adjusts the weights. Let’s discuss the common blueprint of a training loop with these lines of code:" }, { "code": null, "e": 18362, "s": 17918, "text": "1: for e in range(EPOCHS): running_loss = 02: for images, labels in xy_trainPT_loader:3: images = images.view(images.shape[0], -1)4: output = modelPT(images)5: loss = criterion(output, labels)6: loss.backward()7: optimizer.step()8: optimizer.zero_grad() running_loss += loss.item() print(“Epoch {} — Training loss: {}”.format(e, running_loss/len(xy_trainPT_loader)))" }, { "code": null, "e": 18603, "s": 18362, "text": "Line 1: Usually, the training loop iterates over our data over and over again. Remember that one iteration over a full set of examples is called an epoch. The EPOCHS variable indicates the number of iterations over the full set of examples." }, { "code": null, "e": 18835, "s": 18603, "text": "Line 2: We already presented that data is usually too large to fit into CPU or GPU memory at once, so it is split into batches of equal size. Every batch includes data samples and target labels, and both of them have to be tensors." }, { "code": null, "e": 19006, "s": 18835, "text": "Line 3: To facilitate the entry of data into our neural network we must make a transformation of the input (image) from 2 dimensions (2D) to a vector of 1 dimension (1D)." }, { "code": null, "e": 19145, "s": 19006, "text": "Line 4: We pass each batch of image tensors into the model which will return a tensor having predictions for that batch, the forward pass." }, { "code": null, "e": 19473, "s": 19145, "text": "Line 5: Having got the predictions we pass them into the cross-entropy Loss function ( criterion ) along with their actual labels and calculate the Loss. Usually, Loss functions accept two arguments: output from the network (prediction) and desired output (ground-truth data, which is also called the label of the data sample)." }, { "code": null, "e": 19709, "s": 19473, "text": "Some PyTorch’s Loss functions take class labels as their targets (e.g. NLLloss), so if we use them (as in our case), we don’t need to convert targets into one-hot vectors as we presented in the previous post (for ease the explanation)." }, { "code": null, "e": 19910, "s": 19709, "text": "Line 6: We do a backward pass using the Loss value in order to compute gradient of the Loss with respect to model parameters. After loss.backward() call is finished, we have the gradients accumulated." }, { "code": null, "e": 20067, "s": 19910, "text": "Line 7: Now it’s time for the optimizer to modify the model parameters with the method step() that takes all gradients from the parameters and applies them." }, { "code": null, "e": 20265, "s": 20067, "text": "Line 8: The last, but not least, piece of the training loop is our responsibility to zero gradients of parameters. Calling zero_grad() on our network clear the gradients of all optimized variables." }, { "code": null, "e": 20482, "s": 20265, "text": "In order to check how the training process evolve we have added a couple of lines of code in this training loop. First, we get the training loss for the entire epoch by adding all the losses for each batch iteration:" }, { "code": null, "e": 20510, "s": 20482, "text": "running_loss += loss.item()" }, { "code": null, "e": 20576, "s": 20510, "text": "And second averaging it over by the iteration count and print it:" }, { "code": null, "e": 20674, "s": 20576, "text": "print(“Epoch {} — Training loss: {}”.format(e, running_loss/len(xy_trainPT_loader)))" }, { "code": null, "e": 20830, "s": 20674, "text": "Looking at this output we see how the training loop adjusts the weights of the network so that in each iteration the loss function produces a smaller loss." }, { "code": null, "e": 21230, "s": 20830, "text": "Epoch 0 — Training loss: 2.1822925415882932 Epoch 1 — Training loss: 1.8671700155048736Epoch 2 — Training loss: 1.5379922698809902Epoch 3 — Training loss: 1.287035460029838. . .Epoch 15 — Training loss: 0.5162741374264139Epoch 16 — Training loss: 0.49991638108547815Epoch 17 — Training loss: 0.48541215611800453Epoch 18 — Training loss: 0.4724724407929347Epoch 19 — Training loss: 0.4608637086554631" }, { "code": null, "e": 21385, "s": 21230, "text": "In PyTorch, there is no a “prefab” data model tuning function as fit() in Keras or Scikit-learn, so the training loop must be specified by the programmer." }, { "code": null, "e": 21538, "s": 21385, "text": "Now, that we have finished the training of our model, we will probably want to test how well our model was generalized by applying it on a test dataset." }, { "code": null, "e": 21621, "s": 21538, "text": "In PyTorch it is required again that the programmer specifies the evaluation loop:" }, { "code": null, "e": 22349, "s": 21621, "text": "xy_testPT = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=torchvision.transforms. Compose([torchvision.transforms.ToTensor()]))xy_test_loaderPT = torch.utils.data.DataLoader(xy_testPT)correct_count, all_count = 0, 0for images,labels in xy_test_loaderPT: for i in range(len(labels)): img = images[i].view(1, 784) logps = modelPT(img) ps = torch.exp(logps) probab = list(ps.detach().numpy()[0]) pred_label = probab.index(max(probab)) true_label = labels.numpy()[i] if(true_label == pred_label): correct_count += 1 all_count += 1print(\"\\nAccuracy of the model =\", (correct_count/all_count)) Accuracy of the model = 0.8657" }, { "code": null, "e": 22625, "s": 22349, "text": "The reader can see the similarity of the instructions in this loop with those of the previous training loop. But in this case, instead of keeping the Loss calculation, the Accuracy is calculated, that is, the percentage of hits with data that the model has never seen before." }, { "code": null, "e": 22705, "s": 22625, "text": "And that’s all! You have already programmed an entire neural network. Congrats!" }, { "code": null, "e": 22731, "s": 22705, "text": "See you in the next post!" }, { "code": null, "e": 22789, "s": 22731, "text": "by UPC Barcelona Tech and Barcelona Supercomputing Center" }, { "code": null, "e": 23014, "s": 22789, "text": "A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence." }, { "code": null, "e": 23280, "s": 23014, "text": "I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made." } ]
How do you split a list into evenly sized chunks in Python?
The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number. In following example, a list with 12 elements is present. We split it into 3 lists each of length 4 l=[10,20,30,40,50,60,70,80,90,100,110,120] x=0 y=12 for i in range(x,y,4): x=i print (l[x:x+4]) [10, 20, 30, 40] [50, 60, 70, 80] [90, 100, 110, 120]
[ { "code": null, "e": 1215, "s": 1062, "text": "The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number." }, { "code": null, "e": 1315, "s": 1215, "text": "In following example, a list with 12 elements is present. We split it into 3 lists each of length 4" }, { "code": null, "e": 1467, "s": 1315, "text": "l=[10,20,30,40,50,60,70,80,90,100,110,120]\nx=0\ny=12\nfor i in range(x,y,4):\nx=i\nprint (l[x:x+4])\n\n\n[10, 20, 30, 40]\n[50, 60, 70, 80]\n[90, 100, 110, 120]" } ]
Flask - Quick Guide
Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc. Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases. Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application. Some of the popular Flask extensions are discussed later in the tutorial. Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7. virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries. The following command installs virtualenv pip install virtualenv This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager. Sudo apt-get install virtualenv Once installed, new virtual environment is created in a folder. mkdir newproj cd newproj virtualenv venv To activate corresponding environment, on Linux/OS X, use the following − venv/bin/activate On Windows, following can be used venv\scripts\activate We are now ready to install Flask in this environment. pip install Flask The above command can be run directly, without virtual environment for system-wide installation. In order to test Flask installation, type the following code in the editor as Hello.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World’ if __name__ == '__main__': app.run() Importing flask module in the project is mandatory. An object of Flask class is our WSGI application. Flask constructor takes the name of current module (__name__) as argument. The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function. app.route(rule, options) The rule parameter represents URL binding with the function. The rule parameter represents URL binding with the function. The options is a list of parameters to be forwarded to the underlying Rule object. The options is a list of parameters to be forwarded to the underlying Rule object. In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered. Finally the run() method of Flask class runs the application on the local development server. app.run(host, port, debug, options) All parameters are optional host Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally port Defaults to 5000 debug Defaults to false. If set to true, provides a debug information options To be forwarded to underlying Werkzeug server. The above given Python script is executed from Python shell. Python Hello.py A message in Python shell informs you that * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it. A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application. The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method. app.debug = True app.run() app.run(debug = True) Modern web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page. The route() decorator in Flask is used to bind URL to a function. For example − @app.route(‘/hello’) def hello_world(): return ‘hello world’ Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser. The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used. A decorator’s purpose is also served by the following representation − def hello_world(): return ‘hello world’ app.add_url_rule(‘/’, ‘hello’, hello_world) It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as <variable-name>. It is passed as a keyword argument to the function with which the rule is associated. In the following example, the rule parameter of route() decorator contains <name> variable part attached to URL ‘/hello’. Hence, if the http://localhost:5000/hello/TutorialsPoint is entered as a URL in the browser, ‘TutorialPoint’ will be supplied to hello() function as argument. from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True) Save the above script as hello.py and run it from Python shell. Next, open the browser and enter URL http://localhost:5000/hello/TutorialsPoint. The following output will be displayed in the browser. Hello TutorialsPoint! In addition to the default string variable part, rules can be constructed using the following converters − int accepts integer float For floating point value path accepts slashes used as directory separator character In the following code, all these constructors are used. from flask import Flask app = Flask(__name__) @app.route('/blog/<int:postID>') def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>') def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run() Run the above code from Python Shell. Visit the URL http://localhost:5000/blog/11 in the browser. The given number is used as argument to the show_blog() function. The browser displays the following output − Blog Number 11 Enter this URL in the browser − http://localhost:5000/rev/1.1 The revision() function takes up the floating point number as argument. The following result appears in the browser window − Revision Number 1.100000 The URL rules of Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache. Consider the rules defined in the following script − from flask import Flask app = Flask(__name__) @app.route('/flask') def hello_flask(): return 'Hello Flask' @app.route('/python/') def hello_python(): return 'Hello Python' if __name__ == '__main__': app.run() Both the rules appear similar but in the second rule, trailing slash (/) is used. As a result, it becomes a canonical URL. Hence, using /python or /python/ returns the same output. However, in case of the first rule, /flask/ URL results in 404 Not Found page. The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL. The following script demonstrates use of url_for() function. from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') def hello_user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest = name)) if __name__ == '__main__': app.run(debug = True) The above script has a function user(name) which accepts a value to its argument from the URL. The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it. Save the above code and run from Python shell. Open the browser and enter URL as − http://localhost:5000/user/admin The application response in browser is − Hello Admin Enter the following URL in the browser − http://localhost:5000/user/mvl The application response now changes to − Hello mvl as Guest Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The following table summarizes different http methods − GET Sends data in unencrypted form to the server. Most common method. HEAD Same as GET, but without response body POST Used to send HTML form data to server. Data received by POST method is not cached by server. PUT Replaces all current representations of the target resource with the uploaded content. DELETE Removes all current representations of the target resource given by a URL By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL. Save the following script as login.html <html> <body> <form action = "http://localhost:5000/login" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html> Now enter the following script in Python shell. from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/<name>') def success(name): return 'welcome %s' % name @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user)) if __name__ == '__main__': app.run(debug = True) After the development server starts running, open login.html in the browser, enter name in the text field and click Submit. Form data is POSTed to the URL in action clause of form tag. http://localhost/login is mapped to the login() function. Since the server has received data by POST method, value of ‘nm’ parameter obtained from the form data is obtained by − user = request.form['nm'] It is passed to ‘/success’ URL as variable part. The browser displays a welcome message in the window. Change the method parameter to ‘GET’ in login.html and open it again in the browser. The data received on server is by the GET method. The value of ‘nm’ parameter is now obtained by − User = request.args.get(‘nm’) Here, args is dictionary object containing a list of pairs of form parameter and its corresponding value. The value corresponding to ‘nm’ parameter is passed on to ‘/success’ URL as before. It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render ‘Hello World’ with <h1> tag attached to it. from flask import Flask app = Flask(__name__) @app.route('/') def index(): return '<html><body><h1>Hello World</h1></body></html>' if __name__ == '__main__': app.run(debug = True) However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML. This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function. from flask import Flask app = Flask(__name__) @app.route('/') def index(): return render_template(‘hello.html’) if __name__ == '__main__': app.run(debug = True) Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present. Application folder Hello.py templates hello.html Hello.py templates hello.html hello.html The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor. Flask uses Jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered. The following code is saved as hello.html in the templates folder. <!doctype html> <html> <body> <h1>Hello {{ name }}!</h1> </body> </html> Next, run the following script from Python shell. from flask import Flask, render_template app = Flask(__name__) @app.route('/hello/<user>') def hello_name(user): return render_template('hello.html', name = user) if __name__ == '__main__': app.run(debug = True) As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl The variable part of URL is inserted at {{ name }} place holder. The Jinja2 template engine uses the following delimiters for escaping from HTML. {% ... %} for Statements {{ ... }} for Expressions to print to the template output {# ... #} for Comments not included in the template output # ... ## for Line Statements In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered. The Python Script is as follows − from flask import Flask, render_template app = Flask(__name__) @app.route('/hello/<int:score>') def hello_name(score): return render_template('hello.html', marks = score) if __name__ == '__main__': app.run(debug = True) HTML template script of hello.html is as follows − <!doctype html> <html> <body> {% if marks>50 %} <h1> Your result is pass!</h1> {% else %} <h1>Your result is fail</h1> {% endif %} </body> </html> Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}. Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally. The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser. The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table. Run the following code from Python shell. from flask import Flask, render_template app = Flask(__name__) @app.route('/result') def result(): dict = {'phy':50,'che':60,'maths':70} return render_template('result.html', result = dict) if __name__ == '__main__': app.run(debug = True) Save the following HTML script as result.html in the templates folder. <!doctype html> <html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html> Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}. After the development starts running, open http://localhost:5000/result in the browser to get the following output. A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application. A special endpoint ‘static’ is used to generate URL for static files. In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application. from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug = True) The HTML script of index.html is given below. <html> <head> <script type = "text/javascript" src = "{{ url_for('static', filename = 'hello.js') }}" ></script> </head> <body> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html> hello.js contains sayHello() function. function sayHello() { alert("Hello World") } The data from a client’s web page is sent to the server as a global request object. In order to process the request data, it should be imported from the Flask module. Important attributes of request object are listed below − Form − It is a dictionary object containing key and value pairs of form parameters and their values. Form − It is a dictionary object containing key and value pairs of form parameters and their values. args − parsed contents of query string which is part of URL after question mark (?). args − parsed contents of query string which is part of URL after question mark (?). Cookies − dictionary object holding Cookie names and values. Cookies − dictionary object holding Cookie names and values. files − data pertaining to uploaded file. files − data pertaining to uploaded file. method − current request method. method − current request method. We have already seen that the http method can be specified in URL rule. The Form data received by the triggered function can collect it in the form of a dictionary object and forward it to a template to render it on a corresponding web page. In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html. The template dynamically renders an HTML table of form data. Given below is the Python code of application − from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def student(): return render_template('student.html') @app.route('/result',methods = ['POST', 'GET']) def result(): if request.method == 'POST': result = request.form return render_template("result.html",result = result) if __name__ == '__main__': app.run(debug = True) Given below is the HTML script of student.html. <html> <body> <form action = "http://localhost:5000/result" method = "POST"> <p>Name <input type = "text" name = "Name" /></p> <p>Physics <input type = "text" name = "Physics" /></p> <p>Chemistry <input type = "text" name = "chemistry" /></p> <p>Maths <input type ="text" name = "Mathematics" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html> Code of template (result.html) is given below − <!doctype html> <html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html> Run the Python script and enter the URL http://localhost:5000/ in the browser. When the Submit button is clicked, form data is rendered on result.html in the form of HTML table. A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics. A Request object contains a cookie’s attribute. It is a dictionary object of all the cookie variables and their corresponding values, a client has transmitted. In addition to it, a cookie also stores its expiry time, path and domain name of the site. In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie. Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie. In the following Flask application, a simple form opens up as you visit ‘/’ URL. @app.route('/') def index(): return render_template('index.html') This HTML page contains one text input. <html> <body> <form action = "/setcookie" method = "POST"> <p><h3>Enter userID</h3></p> <p><input type = 'text' name = 'nm'/></p> <p><input type = 'submit' value = 'Login'/></p> </form> </body> </html> The Form is posted to ‘/setcookie’ URL. The associated view function sets a Cookie name userID and renders another page. @app.route('/setcookie', methods = ['POST', 'GET']) def setcookie(): if request.method == 'POST': user = request.form['nm'] resp = make_response(render_template('readcookie.html')) resp.set_cookie('userID', user) return resp ‘readcookie.html’ contains a hyperlink to another view function getcookie(), which reads back and displays the cookie value in browser. @app.route('/getcookie') def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>' Run the application and visit http://localhost:5000/ The result of setting a cookie is displayed like this − The output of read back cookie is shown below. Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser. A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY. Session object is also a dictionary object containing key-value pairs of session variables and associated values. For example, to set a ‘username’ session variable use the statement − Session[‘username’] = ’admin’ To release a session variable use pop() method. session.pop('username', None) The following code is a simple demonstration of session works in Flask. URL ‘/’ simply prompts user to log in, as session variable ‘username’ is not set. @app.route('/') def index(): if 'username' in session: username = session['username'] return 'Logged in as ' + username + '<br>' + \ "<b><a href = '/logout'>click here to log out</a></b>" return "You are not logged in <br><a href = '/login'></b>" + \ "click here to log in</b></a>" As user browses to ‘/login’ the login() view function, because it is called through GET method, opens up a login form. A Form is posted back to ‘/login’ and now session variable is set. Application is redirected to ‘/’. This time session variable ‘username’ is found. @app.route('/login', methods = ['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return ''' <form action = "" method = "post"> <p><input type = text name = username/></p> <p<<input type = submit value = Login/></p> </form> ''' The application also contains a logout() view function, which pops out ‘username’ session variable. Hence, ‘/’ URL again shows the opening page. @app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('username', None) return redirect(url_for('index')) Run the application and visit the homepage. (Ensure to set secret_key of the application) from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = 'any random string’ The output will be displayed as shown below. Click the link “click here to log in”. The link will be directed to another screen. Type ‘admin’. The screen will show you the message, ‘Logged in as admin’. Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. Prototype of redirect() function is as below − Flask.redirect(location, statuscode, response) In the above function − location parameter is the URL where response should be redirected. location parameter is the URL where response should be redirected. statuscode sent to browser’s header, defaults to 302. statuscode sent to browser’s header, defaults to 302. response parameter is used to instantiate response. response parameter is used to instantiate response. The following status codes are standardized − HTTP_300_MULTIPLE_CHOICES HTTP_301_MOVED_PERMANENTLY HTTP_302_FOUND HTTP_303_SEE_OTHER HTTP_304_NOT_MODIFIED HTTP_305_USE_PROXY HTTP_306_RESERVED HTTP_307_TEMPORARY_REDIRECT The default status code is 302, which is for ‘found’. In the following example, the redirect() function is used to display the login page again when a login attempt fails. from flask import Flask, redirect, url_for, render_template, request # Initialize the Flask application app = Flask(__name__) @app.route('/') def index(): return render_template('log_in.html') @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST' and request.form['username'] == 'admin' : return redirect(url_for('success')) else: return redirect(url_for('index')) @app.route('/success') def success(): return 'logged in successfully' if __name__ == '__main__': app.run(debug = True) Flask class has abort() function with an error code. Flask.abort(code) The Code parameter takes one of following values − 400 − for Bad Request 400 − for Bad Request 401 − for Unauthenticated 401 − for Unauthenticated 403 − for Forbidden 403 − for Forbidden 404 − for Not Found 404 − for Not Found 406 − for Not Acceptable 406 − for Not Acceptable 415 − for Unsupported Media Type 415 − for Unsupported Media Type 429 − Too Many Requests 429 − Too Many Requests Let us make a slight change in the login() function in the above code. Instead of re-displaying the login page, if ‘Unauthourized’ page is to be displayed, replace it with call to abort(401). from flask import Flask, redirect, url_for, render_template, request, abort app = Flask(__name__) @app.route('/') def index(): return render_template('log_in.html') @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST': if request.form['username'] == 'admin' : return redirect(url_for('success')) else: abort(401) else: return redirect(url_for('index')) @app.route('/success') def success(): return 'logged in successfully' if __name__ == '__main__': app.run(debug = True) A good GUI based application provides feedback to a user about the interaction. For example, the desktop applications use dialog or message box and JavaScript uses alerts for similar purpose. Generating such informative messages is easy in Flask web application. Flashing system of Flask framework makes it possible to create a message in one view and render it in a view function called next. A Flask module contains flash() method. It passes a message to the next request, which generally is a template. flash(message, category) Here, message parameter is the actual message to be flashed. message parameter is the actual message to be flashed. category parameter is optional. It can be either ‘error’, ‘info’ or ‘warning’. category parameter is optional. It can be either ‘error’, ‘info’ or ‘warning’. In order to remove message from session, template calls get_flashed_messages(). get_flashed_messages(with_categories, category_filter) Both parameters are optional. The first parameter is a tuple if received messages are having category. The second parameter is useful to display only specific messages. The following flashes received messages in a template. {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %} Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the following code, a ‘/’ URL displays link to the login page, with no message to flash. @app.route('/') def index(): return render_template('index.html') The link leads a user to ‘/login’ URL which displays a login form. When submitted, the login() view function verifies a username and password and accordingly flashes a ‘success’ message or creates ‘error’ variable. @app.route('/login', methods = ['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or \ request.form['password'] != 'admin': error = 'Invalid username or password. Please try again!' else: flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error = error) In case of error, the login template is redisplayed with error message. <!doctype html> <html> <body> <h1>Login</h1> {% if error %} <p><strong>Error:</strong> {{ error }} {% endif %} <form action = "" method = post> <dl> <dt>Username:</dt> <dd> <input type = text name = username value = "{{request.form.username }}"> </dd> <dt>Password:</dt> <dd><input type = password name = password></dd> </dl> <p><input type = submit value = Login></p> </form> </body> </html> On the other hand, if login is successful, a success message is flashed on the index template. <!doctype html> <html> <head> <title>Flask Message flashing</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li<{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <h1>Flask Message Flashing Example</h1> <p>Do you want to <a href = "{{ url_for('login') }}"> <b>log in?</b></a></p> </body> </html> A complete code for Flask message flashing example is given below − from flask import Flask, flash, redirect, render_template, request, url_for app = Flask(__name__) app.secret_key = 'random string' @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods = ['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or \ request.form['password'] != 'admin': error = 'Invalid username or password. Please try again!' else: flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error = error) if __name__ == "__main__": app.run(debug = True) After executing the above codes, you will see the screen as shown below. When you click on the link, you will be directed to the Login page. Enter the Username and password. Click Login. A message will be displayed “You were successfully logged in” . Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to ‘multipart/form-data’, posting the file to a URL. The URL handler fetches file from request.files[] object and saves it to the desired location. Each uploaded file is first saved in a temporary location on the server, before it is actually saved to its ultimate location. Name of destination file can be hard-coded or can be obtained from filename property of request.files[file] object. However, it is recommended to obtain a secure version of it using the secure_filename() function. It is possible to define the path of default upload folder and maximum size of uploaded file in configuration settings of Flask object. The following code has ‘/upload’ URL rule that displays ‘upload.html’ from the templates folder, and ‘/upload-file’ URL rule that calls uploader() function handling upload process. ‘upload.html’ has a file chooser button and a submit button. <html> <body> <form action = "http://localhost:5000/uploader" method = "POST" enctype = "multipart/form-data"> <input type = "file" name = "file" /> <input type = "submit"/> </form> </body> </html> You will see the screen as shown below. Click Submit after choosing file. Form’s post method invokes ‘/upload_file’ URL. The underlying function uploader() does the save operation. Following is the Python code of Flask application. from flask import Flask, render_template, request from werkzeug import secure_filename app = Flask(__name__) @app.route('/upload') def upload_file(): return render_template('upload.html') @app.route('/uploader', methods = ['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['file'] f.save(secure_filename(f.filename)) return 'file uploaded successfully' if __name__ == '__main__': app.run(debug = True) Flask is often referred to as a micro framework, because a core functionality includes WSGI and routing based on Werkzeug and template engine based on Jinja2. In addition, Flask framework has support for cookie and sessions as well as web helpers like JSON, static files etc. Obviously, this is not enough for the development of a full-fledged web application. This is where the Flask extensions come in picture. Flask extensions give extensibility to Flask framework. There are a large number of Flask extensions available. A Flask extension is a Python module, which adds specific type of support to the Flask application. Flask Extension Registry is a directory of extensions available. The required extension can be downloaded by pip utility. In this tutorial, we will discuss the following important Flask extensions − Flask Mail − provides SMTP interface to Flask application Flask Mail − provides SMTP interface to Flask application Flask WTF − adds rendering and validation of WTForms Flask WTF − adds rendering and validation of WTForms Flask SQLAlchemy − adds SQLAlchemy support to Flask application Flask SQLAlchemy − adds SQLAlchemy support to Flask application Flask Sijax − Interface for Sijax - Python/jQuery library that makes AJAX easy to use in web applications Flask Sijax − Interface for Sijax - Python/jQuery library that makes AJAX easy to use in web applications Each type of extension usually provides extensive documentation about its usage. Since an extension is a Python module, it needs to be imported for it to be used. Flask extensions are generally named as flask-foo. To import, from flask_foo import [class, function] For versions of Flask later than 0.7, you can also use the syntax − from flask.ext import foo For this usage, a compatibility module needs to be activated. It can be installed by running flaskext_compat.py import flaskext_compat flaskext_compat.activate() from flask.ext import foo A web based application is often required to have a feature of sending mail to the users/clients. Flask-Mail extension makes it very easy to set up a simple interface with any email server. At first, Flask-Mail extension should be installed with the help of pip utility. pip install Flask-Mail Then Flask-Mail needs to be configured by setting values of the following application parameters. MAIL_SERVER Name/IP address of email server MAIL_PORT Port number of server used MAIL_USE_TLS Enable/disable Transport Security Layer encryption MAIL_USE_SSL Enable/disable Secure Sockets Layer encryption MAIL_DEBUG Debug support. Default is Flask application’s debug status MAIL_USERNAME User name of sender MAIL_PASSWORD password of sender MAIL_DEFAULT_SENDER sets default sender MAIL_MAX_EMAILS Sets maximum mails to be sent MAIL_SUPPRESS_SEND Sending suppressed if app.testing set to true MAIL_ASCII_ATTACHMENTS If set to true, attached filenames converted to ASCII The flask-mail module contains definitions of the following important classes. It manages email-messaging requirements. The class constructor takes the following form − flask-mail.Mail(app = None) The Constructor takes the Flask application object as a parameter. send() Sends contents of Message class object connect() Opens connection with mail host send_message() Sends message object It encapsulates an email message. Message class constructor has several parameters − flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, reply-to, date, charset, extra_headers, mail_options, rcpt_options) attach() − adds an attachment to message. This method takes the following parameters − filename − name of file to attach filename − name of file to attach content_type − MIME type of file content_type − MIME type of file data − raw file data data − raw file data disposition − content disposition, if any. disposition − content disposition, if any. add_recipient() − adds another recipient to message In the following example, SMTP server of Google’s gmail service is used as MAIL_SERVER for Flask-Mail configuration. Step 1 − Import Mail and Message class from flask-mail module in the code. from flask_mail import Mail, Message Step 2 − Then Flask-Mail is configured as per following settings. app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = '[email protected]' app.config['MAIL_PASSWORD'] = '*****' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True Step 3 − Create an instance of Mail class. mail = Mail(app) Step 4 − Set up a Message object in a Python function mapped by URL rule (‘/’). @app.route("/") def index(): msg = Message('Hello', sender = '[email protected]', recipients = ['[email protected]']) msg.body = "This is the email body" mail.send(msg) return "Sent" Step 5 − The entire code is given below. Run the following script in Python Shell and visit http://localhost:5000/. from flask import Flask from flask_mail import Mail, Message app =Flask(__name__) mail=Mail(app) app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = '[email protected]' app.config['MAIL_PASSWORD'] = '*****' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True mail = Mail(app) @app.route("/") def index(): msg = Message('Hello', sender = '[email protected]', recipients = ['[email protected]']) msg.body = "Hello Flask message sent from Flask-Mail" mail.send(msg) return "Sent" if __name__ == '__main__': app.run(debug = True) Note that the built-insecurity features in Gmail service may block this login attempt. You may have to decrease the security level. Please log in to your Gmail account and visit this link to decrease the security. One of the essential aspects of a web application is to present a user interface for the user. HTML provides a <form> tag, which is used to design an interface. A Form’s elements such as text input, radio, select etc. can be used appropriately. Data entered by a user is submitted in the form of Http request message to the server side script by either GET or POST method. The Server side script has to recreate the form elements from http request data. So in effect, form elements have to be defined twice – once in HTML and again in the server side script. The Server side script has to recreate the form elements from http request data. So in effect, form elements have to be defined twice – once in HTML and again in the server side script. Another disadvantage of using HTML form is that it is difficult (if not impossible) to render the form elements dynamically. HTML itself provides no way to validate a user’s input. Another disadvantage of using HTML form is that it is difficult (if not impossible) to render the form elements dynamically. HTML itself provides no way to validate a user’s input. This is where WTForms, a flexible form, rendering and validation library comes handy. Flask-WTF extension provides a simple interface with this WTForms library. Using Flask-WTF, we can define the form fields in our Python script and render them using an HTML template. It is also possible to apply validation to the WTF field. Let us see how this dynamic generation of HTML works. First, Flask-WTF extension needs to be installed. pip install flask-WTF The installed package contains a Form class, which has to be used as a parent for user- defined form. WTforms package contains definitions of various form fields. Some Standard form fields are listed below. TextField Represents <input type = 'text'> HTML form element BooleanField Represents <input type = 'checkbox'> HTML form element DecimalField Textfield for displaying number with decimals IntegerField TextField for displaying integer RadioField Represents <input type = 'radio'> HTML form element SelectField Represents select form element TextAreaField Represents <testarea> html form element PasswordField Represents <input type = 'password'> HTML form element SubmitField Represents <input type = 'submit'> form element For example, a form containing a text field can be designed as below − from flask_wtf import Form from wtforms import TextField class ContactForm(Form): name = TextField("Name Of Student") In addition to the ‘name’ field, a hidden field for CSRF token is created automatically. This is to prevent Cross Site Request Forgery attack. When rendered, this will result into an equivalent HTML script as shown below. <input id = "csrf_token" name = "csrf_token" type = "hidden" /> <label for = "name">Name Of Student</label><br> <input id = "name" name = "name" type = "text" value = "" /> A user-defined form class is used in a Flask application and the form is rendered using a template. from flask import Flask, render_template from forms import ContactForm app = Flask(__name__) app.secret_key = 'development key' @app.route('/contact') def contact(): form = ContactForm() return render_template('contact.html', form = form) if __name__ == '__main__': app.run(debug = True) WTForms package also contains validator class. It is useful in applying validation to form fields. Following list shows commonly used validators. DataRequired Checks whether input field is empty Email Checks whether text in the field follows email ID conventions IPAddress Validates IP address in input field Length Verifies if length of string in input field is in given range NumberRange Validates a number in input field within given range URL Validates URL entered in input field We shall now apply ‘DataRequired’ validation rule for the name field in contact form. name = TextField("Name Of Student",[validators.Required("Please enter your name.")]) The validate() function of form object validates the form data and throws the validation errors if validation fails. The Error messages are sent to the template. In the HTML template, error messages are rendered dynamically. {% for message in form.name.errors %} {{ message }} {% endfor %} The following example demonstrates the concepts given above. The design of Contact form is given below (forms.py). from flask_wtf import Form from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField from wtforms import validators, ValidationError class ContactForm(Form): name = TextField("Name Of Student",[validators.Required("Please enter your name.")]) Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')]) Address = TextAreaField("Address") email = TextField("Email",[validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")]) Age = IntegerField("age") language = SelectField('Languages', choices = [('cpp', 'C++'), ('py', 'Python')]) submit = SubmitField("Send") Validators are applied to the Name and Email fields. Given below is the Flask application script (formexample.py). from flask import Flask, render_template, request, flash from forms import ContactForm app = Flask(__name__) app.secret_key = 'development key' @app.route('/contact', methods = ['GET', 'POST']) def contact(): form = ContactForm() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') return render_template('contact.html', form = form) else: return render_template('success.html') elif request.method == 'GET': return render_template('contact.html', form = form) if __name__ == '__main__': app.run(debug = True) The Script of the template (contact.html) is as follows − <!doctype html> <html> <body> <h2 style = "text-align: center;">Contact Form</h2> {% for message in form.name.errors %} <div>{{ message }}</div> {% endfor %} {% for message in form.email.errors %} <div>{{ message }}</div> {% endfor %} <form action = "http://localhost:5000/contact" method = post> <fieldset> <legend>Contact Form</legend> {{ form.hidden_tag() }} <div style = font-size:20px; font-weight:bold; margin-left:150px;> {{ form.name.label }}<br> {{ form.name }} <br> {{ form.Gender.label }} {{ form.Gender }} {{ form.Address.label }}<br> {{ form.Address }} <br> {{ form.email.label }}<br> {{ form.email }} <br> {{ form.Age.label }}<br> {{ form.Age }} <br> {{ form.language.label }}<br> {{ form.language }} <br> {{ form.submit }} </div> </fieldset> </form> </body> </html> Run formexample.py in Python shell and visit URL http://localhost:5000/contact. The Contact form will be displayed as shown below. If there are any errors, the page will look like this − If there are no errors, ‘success.html’ will be rendered. Python has an in-built support for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, please refer to this link. In this section we shall see how a Flask application interacts with SQLite. Create an SQLite database ‘database.db’ and create a students’ table in it. import sqlite3 conn = sqlite3.connect('database.db') print "Opened database successfully"; conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)') print "Table created successfully"; conn.close() Our Flask application has three View functions. First new_student() function is bound to the URL rule (‘/addnew’). It renders an HTML file containing student information form. @app.route('/enternew') def new_student(): return render_template('student.html') The HTML script for ‘student.html’ is as follows − <html> <body> <form action = "{{ url_for('addrec') }}" method = "POST"> <h3>Student Information</h3> Name<br> <input type = "text" name = "nm" /></br> Address<br> <textarea name = "add" ></textarea><br> City<br> <input type = "text" name = "city" /><br> PINCODE<br> <input type = "text" name = "pin" /><br> <input type = "submit" value = "submit" /><br> </form> </body> </html> As it can be seen, form data is posted to the ‘/addrec’ URL which binds the addrec() function. This addrec() function retrieves the form’s data by POST method and inserts in students table. Message corresponding to success or error in insert operation is rendered to ‘result.html’. @app.route('/addrec',methods = ['POST', 'GET']) def addrec(): if request.method == 'POST': try: nm = request.form['nm'] addr = request.form['add'] city = request.form['city'] pin = request.form['pin'] with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html",msg = msg) con.close() The HTML script of result.html contains an escaping statement {{msg}} that displays the result of Insert operation. <!doctype html> <html> <body> result of addition : {{ msg }} <h2><a href = "\">go back to home page</a></h2> </body> </html> The application contains another list() function represented by ‘/list’ URL. It populates ‘rows’ as a MultiDict object containing all records in the students table. This object is passed to the list.html template. @app.route('/list') def list(): con = sql.connect("database.db") con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from students") rows = cur.fetchall(); return render_template("list.html",rows = rows) This list.html is a template, which iterates over the row set and renders the data in an HTML table. <!doctype html> <html> <body> <table border = 1> <thead> <td>Name</td> <td>Address>/td< <td>city</td> <td>Pincode</td> </thead> {% for row in rows %} <tr> <td>{{row["name"]}}</td> <td>{{row["addr"]}}</td> <td> {{ row["city"]}}</td> <td>{{row['pin']}}</td> </tr> {% endfor %} </table> <a href = "/">Go back to home page</a> </body> </html> Finally, the ‘/’ URL rule renders a ‘home.html’ which acts as the entry point of the application. @app.route('/') def home(): return render_template('home.html') Here is the complete code of Flask-SQLite application. from flask import Flask, render_template, request import sqlite3 as sql app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/enternew') def new_student(): return render_template('student.html') @app.route('/addrec',methods = ['POST', 'GET']) def addrec(): if request.method == 'POST': try: nm = request.form['nm'] addr = request.form['add'] city = request.form['city'] pin = request.form['pin'] with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html",msg = msg) con.close() @app.route('/list') def list(): con = sql.connect("database.db") con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from students") rows = cur.fetchall(); return render_template("list.html",rows = rows) if __name__ == '__main__': app.run(debug = True) Run this script from Python shell and as the development server starts running. Visit http://localhost:5000/ in browser which displays a simple menu like this − Click ‘Add New Record’ link to open the Student Information Form. Fill the form fields and submit it. The underlying function inserts the record in the students table. Go back to the home page and click ‘Show List’ link. The table showing the sample data will be displayed. Using raw SQL in Flask web applications to perform CRUD operations on database can be tedious. Instead, SQLAlchemy, a Python toolkit is a powerful OR Mapper that gives application developers the full power and flexibility of SQL. Flask-SQLAlchemy is the Flask extension that adds support for SQLAlchemy to your Flask application. What is ORM (Object Relation Mapping)? Most programming language platforms are object oriented. Data in RDBMS servers on the other hand is stored as tables. Object relation mapping is a technique of mapping object parameters to the underlying RDBMS table structure. An ORM API provides methods to perform CRUD operations without having to write raw SQL statements. In this section, we are going to study the ORM techniques of Flask-SQLAlchemy and build a small web application. Step 1 − Install Flask-SQLAlchemy extension. pip install flask-sqlalchemy Step 2 − You need to import SQLAlchemy class from this module. from flask_sqlalchemy import SQLAlchemy Step 3 − Now create a Flask application object and set URI for the database to be used. app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3' Step 4 − Then create an object of SQLAlchemy class with application object as the parameter. This object contains helper functions for ORM operations. It also provides a parent Model class using which user defined models are declared. In the snippet below, a students model is created. db = SQLAlchemy(app) class students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin Step 5 − To create / use database mentioned in URI, run the create_all() method. db.create_all() The Session object of SQLAlchemy manages all persistence operations of ORM object. The following session methods perform CRUD operations − db.session.add(model object) − inserts a record into mapped table db.session.add(model object) − inserts a record into mapped table db.session.delete(model object) − deletes record from table db.session.delete(model object) − deletes record from table model.query.all() − retrieves all records from table (corresponding to SELECT query). model.query.all() − retrieves all records from table (corresponding to SELECT query). You can apply a filter to the retrieved record set by using the filter attribute. For instance, in order to retrieve records with city = ’Hyderabad’ in students table, use following statement − Students.query.filter_by(city = ’Hyderabad’).all() With this much of background, now we shall provide view functions for our application to add a student data. The entry point of the application is show_all() function bound to ‘/’ URL. The Record set of students table is sent as parameter to the HTML template. The Server side code in the template renders the records in HTML table form. @app.route('/') def show_all(): return render_template('show_all.html', students = students.query.all() ) The HTML script of the template (‘show_all.html’) is like this − <!DOCTYPE html> <html lang = "en"> <head></head> <body> <h3> <a href = "{{ url_for('show_all') }}">Comments - Flask SQLAlchemy example</a> </h3> <hr/> {%- for message in get_flashed_messages() %} {{ message }} {%- endfor %} <h3>Students (<a href = "{{ url_for('new') }}">Add Student </a>)</h3> <table> <thead> <tr> <th>Name</th> <th>City</th> <th>Address</th> <th>Pin</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.city }}</td> <td>{{ student.addr }}</td> <td>{{ student.pin }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> The above page contains a hyperlink to ‘/new’ URL mapping new() function. When clicked, it opens a Student Information form. The data is posted to the same URL in POST method. <!DOCTYPE html> <html> <body> <h3>Students - Flask SQLAlchemy example</h3> <hr/> {%- for category, message in get_flashed_messages(with_categories = true) %} <div class = "alert alert-danger"> {{ message }} </div> {%- endfor %} <form action = "{{ request.path }}" method = "post"> <label for = "name">Name</label><br> <input type = "text" name = "name" placeholder = "Name" /><br> <label for = "email">City</label><br> <input type = "text" name = "city" placeholder = "city" /><br> <label for = "addr">addr</label><br> <textarea name = "addr" placeholder = "addr"></textarea><br> <label for = "PIN">City</label><br> <input type = "text" name = "pin" placeholder = "pin" /><br> <input type = "submit" value = "Submit" /> </form> </body> </html> When the http method is detected as POST, the form data is added in the students table and the application returns to homepage showing the added data. @app.route('/new', methods = ['GET', 'POST']) def new(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Please enter all the fields', 'error') else: student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) db.session.add(student) db.session.commit() flash('Record was successfully added') return redirect(url_for('show_all')) return render_template('new.html') Given below is the complete code of application (app.py). from flask import Flask, request, flash, url_for, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3' app.config['SECRET_KEY'] = "random string" db = SQLAlchemy(app) class students(db.Model): id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(50)) addr = db.Column(db.String(200)) pin = db.Column(db.String(10)) def __init__(self, name, city, addr,pin): self.name = name self.city = city self.addr = addr self.pin = pin @app.route('/') def show_all(): return render_template('show_all.html', students = students.query.all() ) @app.route('/new', methods = ['GET', 'POST']) def new(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Please enter all the fields', 'error') else: student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin']) db.session.add(student) db.session.commit() flash('Record was successfully added') return redirect(url_for('show_all')) return render_template('new.html') if __name__ == '__main__': db.create_all() app.run(debug = True) Run the script from Python shell and enter http://localhost:5000/ in the browser. Click the ‘Add Student’ link to open Student information form. Fill the form and submit. The home page reappears with the submitted data. We can see the output as shown below. Sijax stands for ‘Simple Ajax’ and it is a Python/jQuery library designed to help you easily bring Ajax to your application. It uses jQuery.ajax to make AJAX requests. Installation of Flask-Sijax is easy. pip install flask-sijax SIJAX_STATIC_PATH − the static path where you want the Sijax javascript files to be mirrored. The default location is static/js/sijax. In this folder, sijax.js and json2.js files are kept. SIJAX_STATIC_PATH − the static path where you want the Sijax javascript files to be mirrored. The default location is static/js/sijax. In this folder, sijax.js and json2.js files are kept. SIJAX_JSON_URI − the URI to load the json2.js static file from SIJAX_JSON_URI − the URI to load the json2.js static file from Sijax uses JSON to pass the data between the browser and the server. This means that the browsers need either to support JSON natively or get JSON support from the json2.js file. Functions registered that way cannot provide Sijax functionality, because they cannot be accessed using a POST method by default (and Sijax uses POST requests). To make a View function capable of handling Sijax requests, make it accessible via POST using @app.route('/url', methods = ['GET', 'POST']) or use the @flask_sijax.route helper decorator like this − @flask_sijax.route(app, '/hello') Every Sijax handler function (like this one) receives at least one parameter automatically, much like Python passes ‘self’ to the object methods. The ‘obj_response’ parameter is the function's way of talking back to the browser. def say_hi(obj_response): obj_response.alert('Hi there!') When Sijax request is detected, Sijax handles it like this − g.sijax.register_callback('say_hi', say_hi) return g.sijax.process_request() A minimal Sijax application code looks as follows − import os from flask import Flask, g from flask_sijax import sijax path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/') app = Flask(__name__) app.config['SIJAX_STATIC_PATH'] = path app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' flask_sijax.Sijax(app) @app.route('/') def index(): return 'Index' @flask_sijax.route(app, '/hello') def hello(): def say_hi(obj_response): obj_response.alert('Hi there!') if g.sijax.is_sijax_request: # Sijax request detected - let Sijax handle it g.sijax.register_callback('say_hi', say_hi) return g.sijax.process_request() return _render_template('sijaxexample.html') if __name__ == '__main__': app.run(debug = True) When a Sijax requests (a special jQuery.ajax() request) to the server, this request is detected on the server by g.sijax.is_sijax_request(), in which case you let Sijax handle the request. All the functions registered using g.sijax.register_callback() are exposed for calling from the browser. Calling g.sijax.process_request() tells Sijax to execute the appropriate (previously registered) function and return the response to the browser. A Flask application on the development server is accessible only on the computer on which the development environment is set up. This is a default behavior, because in debugging mode, a user can execute arbitrary code on the computer. If debug is disabled, the development server on local computer can be made available to the users on network by setting the host name as ‘0.0.0.0’. app.run(host = ’0.0.0.0’) Thereby, your operating system listens to all public IPs. To switch over from a development environment to a full-fledged production environment, an application needs to be deployed on a real web server. Depending upon what you have, there are different options available to deploy a Flask web application. For small application, you can consider deploying it on any of the following hosted platforms, all of which offer free plan for small application. Heroku dotcloud webfaction Flask application can be deployed on these cloud platforms. In addition, it is possible to deploy Flask app on Google cloud platform. Localtunnel service allows you to share your application on localhost without messing with DNS and firewall settings. If you are inclined to use a dedicated web server in place of above mentioned shared platforms, following options are there to explore. mod_wsgi is an Apache module that provides a WSGI compliant interface for hosting Python based web applications on Apache server. To install an official release direct from PyPi, you can run − pip install mod_wsgi To verify that the installation was successful, run the mod_wsgi-express script with the start-server command − mod_wsgi-express start-server This will start up Apache/mod_wsgi on port 8000. You can then verify that the installation worked by pointing your browser at − http://localhost:8000/ There should be a yourapplication.wsgi file. This file contains the code mod_wsgi, which executes on startup to get the application object. For most applications, the following file should be sufficient − from yourapplication import app as application Make sure that yourapplication and all the libraries that are in use are on the python load path. You need to tell mod_wsgi, the location of your application. <VirtualHost *> ServerName example.com WSGIScriptAlias / C:\yourdir\yourapp.wsgi <Directory C:\yourdir> Order deny,allow Allow from all </Directory> </VirtualHost> There are many popular servers written in Python that contains WSGI applications and serve HTTP. Gunicorn Tornado Gevent Twisted Web FastCGI is another deployment option for Flask application on web servers like nginix, lighttpd, and Cherokee. First, you need to create the FastCGI server file. Let us call it yourapplication.fcgi. from flup.server.fcgi import WSGIServer from yourapplication import app if __name__ == '__main__': WSGIServer(app).run() nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work, you need to pass the path to the socket to the WSGIServer. WSGIServer(application, bindAddress = '/path/to/fcgi.sock').run() For a basic Apache deployment, your .fcgi file will appear in your application URL e.g. example.com/yourapplication.fcgi/hello/. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL. <VirtualHost *> ServerName example.com ScriptAlias / /path/to/yourapplication.fcgi/ </VirtualHost> Basic configuration of lighttpd looks like this − fastcgi.server = ("/yourapplication.fcgi" => (( "socket" => "/tmp/yourapplication-fcgi.sock", "bin-path" => "/var/www/yourapplication/yourapplication.fcgi", "check-local" => "disable", "max-procs" => 1 ))) alias.url = ( "/static/" => "/path/to/your/static" ) url.rewrite-once = ( "^(/static($|/.*))$" => "$1", "^(/.*)$" => "/yourapplication.fcgi$1" ) Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication. 22 Lectures 6 hours Malhar Lathkar 21 Lectures 1.5 hours Jack Chan 16 Lectures 4 hours Malhar Lathkar 54 Lectures 6 hours Srikanth Guskra 88 Lectures 3.5 hours Jorge Escobar 80 Lectures 12 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2286, "s": 2033, "text": "Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc." }, { "code": null, "e": 2542, "s": 2286, "text": "Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects." }, { "code": null, "e": 2748, "s": 2542, "text": "Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications." }, { "code": null, "e": 2951, "s": 2748, "text": "It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases." }, { "code": null, "e": 3101, "s": 2951, "text": "Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages." }, { "code": null, "e": 3489, "s": 3101, "text": "Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application. Some of the popular Flask extensions are discussed later in the tutorial." }, { "code": null, "e": 3760, "s": 3489, "text": "Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7." }, { "code": null, "e": 3973, "s": 3760, "text": "virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries." }, { "code": null, "e": 4015, "s": 3973, "text": "The following command installs virtualenv" }, { "code": null, "e": 4039, "s": 4015, "text": "pip install virtualenv\n" }, { "code": null, "e": 4234, "s": 4039, "text": "This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager." }, { "code": null, "e": 4267, "s": 4234, "text": "Sudo apt-get install virtualenv\n" }, { "code": null, "e": 4331, "s": 4267, "text": "Once installed, new virtual environment is created in a folder." }, { "code": null, "e": 4373, "s": 4331, "text": "mkdir newproj\ncd newproj\nvirtualenv venv\n" }, { "code": null, "e": 4447, "s": 4373, "text": "To activate corresponding environment, on Linux/OS X, use the following −" }, { "code": null, "e": 4466, "s": 4447, "text": "venv/bin/activate\n" }, { "code": null, "e": 4500, "s": 4466, "text": "On Windows, following can be used" }, { "code": null, "e": 4523, "s": 4500, "text": "venv\\scripts\\activate\n" }, { "code": null, "e": 4578, "s": 4523, "text": "We are now ready to install Flask in this environment." }, { "code": null, "e": 4597, "s": 4578, "text": "pip install Flask\n" }, { "code": null, "e": 4694, "s": 4597, "text": "The above command can be run directly, without virtual environment for system-wide installation." }, { "code": null, "e": 4781, "s": 4694, "text": "In order to test Flask installation, type the following code in the editor as Hello.py" }, { "code": null, "e": 4928, "s": 4781, "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected]('/')\ndef hello_world():\n return 'Hello World’\n\nif __name__ == '__main__':\n app.run()" }, { "code": null, "e": 5030, "s": 4928, "text": "Importing flask module in the project is mandatory. An object of Flask class is our WSGI application." }, { "code": null, "e": 5105, "s": 5030, "text": "Flask constructor takes the name of current module (__name__) as argument." }, { "code": null, "e": 5236, "s": 5105, "text": "The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function." }, { "code": null, "e": 5262, "s": 5236, "text": "app.route(rule, options)\n" }, { "code": null, "e": 5323, "s": 5262, "text": "The rule parameter represents URL binding with the function." }, { "code": null, "e": 5384, "s": 5323, "text": "The rule parameter represents URL binding with the function." }, { "code": null, "e": 5467, "s": 5384, "text": "The options is a list of parameters to be forwarded to the underlying Rule object." }, { "code": null, "e": 5550, "s": 5467, "text": "The options is a list of parameters to be forwarded to the underlying Rule object." }, { "code": null, "e": 5726, "s": 5550, "text": "In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered." }, { "code": null, "e": 5820, "s": 5726, "text": "Finally the run() method of Flask class runs the application on the local development server." }, { "code": null, "e": 5857, "s": 5820, "text": "app.run(host, port, debug, options)\n" }, { "code": null, "e": 5885, "s": 5857, "text": "All parameters are optional" }, { "code": null, "e": 5890, "s": 5885, "text": "host" }, { "code": null, "e": 6001, "s": 5890, "text": "Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally" }, { "code": null, "e": 6006, "s": 6001, "text": "port" }, { "code": null, "e": 6023, "s": 6006, "text": "Defaults to 5000" }, { "code": null, "e": 6029, "s": 6023, "text": "debug" }, { "code": null, "e": 6093, "s": 6029, "text": "Defaults to false. If set to true, provides a debug information" }, { "code": null, "e": 6101, "s": 6093, "text": "options" }, { "code": null, "e": 6148, "s": 6101, "text": "To be forwarded to underlying Werkzeug server." }, { "code": null, "e": 6209, "s": 6148, "text": "The above given Python script is executed from Python shell." }, { "code": null, "e": 6226, "s": 6209, "text": "Python Hello.py\n" }, { "code": null, "e": 6269, "s": 6226, "text": "A message in Python shell informs you that" }, { "code": null, "e": 6329, "s": 6269, "text": "* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n" }, { "code": null, "e": 6428, "s": 6329, "text": "Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it." }, { "code": null, "e": 6796, "s": 6428, "text": "A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application." }, { "code": null, "e": 6953, "s": 6796, "text": "The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method." }, { "code": null, "e": 7002, "s": 6953, "text": "app.debug = True\napp.run()\napp.run(debug = True)" }, { "code": null, "e": 7188, "s": 7002, "text": "Modern web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page." }, { "code": null, "e": 7268, "s": 7188, "text": "The route() decorator in Flask is used to bind URL to a function. For example −" }, { "code": null, "e": 7332, "s": 7268, "text": "@app.route(‘/hello’)\ndef hello_world():\n return ‘hello world’" }, { "code": null, "e": 7533, "s": 7332, "text": "Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser." }, { "code": null, "e": 7676, "s": 7533, "text": "The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used." }, { "code": null, "e": 7747, "s": 7676, "text": "A decorator’s purpose is also served by the following representation −" }, { "code": null, "e": 7834, "s": 7747, "text": "def hello_world():\n return ‘hello world’\napp.add_url_rule(‘/’, ‘hello’, hello_world)" }, { "code": null, "e": 8060, "s": 7834, "text": "It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as <variable-name>. It is passed as a keyword argument to the function with which the rule is associated." }, { "code": null, "e": 8341, "s": 8060, "text": "In the following example, the rule parameter of route() decorator contains <name> variable part attached to URL ‘/hello’. Hence, if the http://localhost:5000/hello/TutorialsPoint is entered as a URL in the browser, ‘TutorialPoint’ will be supplied to hello() function as argument." }, { "code": null, "e": 8520, "s": 8341, "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected]('/hello/<name>')\ndef hello_name(name):\n return 'Hello %s!' % name\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 8665, "s": 8520, "text": "Save the above script as hello.py and run it from Python shell. Next, open the browser and enter URL http://localhost:5000/hello/TutorialsPoint." }, { "code": null, "e": 8720, "s": 8665, "text": "The following output will be displayed in the browser." }, { "code": null, "e": 8743, "s": 8720, "text": "Hello TutorialsPoint!\n" }, { "code": null, "e": 8850, "s": 8743, "text": "In addition to the default string variable part, rules can be constructed using the following converters −" }, { "code": null, "e": 8854, "s": 8850, "text": "int" }, { "code": null, "e": 8870, "s": 8854, "text": "accepts integer" }, { "code": null, "e": 8876, "s": 8870, "text": "float" }, { "code": null, "e": 8901, "s": 8876, "text": "For floating point value" }, { "code": null, "e": 8906, "s": 8901, "text": "path" }, { "code": null, "e": 8960, "s": 8906, "text": "accepts slashes used as directory separator character" }, { "code": null, "e": 9016, "s": 8960, "text": "In the following code, all these constructors are used." }, { "code": null, "e": 9290, "s": 9016, "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected]('/blog/<int:postID>')\ndef show_blog(postID):\n return 'Blog Number %d' % postID\n\[email protected]('/rev/<float:revNo>')\ndef revision(revNo):\n return 'Revision Number %f' % revNo\n\nif __name__ == '__main__':\n app.run()" }, { "code": null, "e": 9388, "s": 9290, "text": "Run the above code from Python Shell. Visit the URL http://localhost:5000/blog/11 in the browser." }, { "code": null, "e": 9498, "s": 9388, "text": "The given number is used as argument to the show_blog() function. The browser displays the following output −" }, { "code": null, "e": 9514, "s": 9498, "text": "Blog Number 11\n" }, { "code": null, "e": 9576, "s": 9514, "text": "Enter this URL in the browser − http://localhost:5000/rev/1.1" }, { "code": null, "e": 9701, "s": 9576, "text": "The revision() function takes up the floating point number as argument. The following result appears in the browser window −" }, { "code": null, "e": 9727, "s": 9701, "text": "Revision Number 1.100000\n" }, { "code": null, "e": 9880, "s": 9727, "text": "The URL rules of Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache." }, { "code": null, "e": 9933, "s": 9880, "text": "Consider the rules defined in the following script −" }, { "code": null, "e": 10154, "s": 9933, "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected]('/flask')\ndef hello_flask():\n return 'Hello Flask'\n\[email protected]('/python/')\ndef hello_python():\n return 'Hello Python'\n\nif __name__ == '__main__':\n app.run()" }, { "code": null, "e": 10414, "s": 10154, "text": "Both the rules appear similar but in the second rule, trailing slash (/) is used. As a result, it becomes a canonical URL. Hence, using /python or /python/ returns the same output. However, in case of the first rule, /flask/ URL results in 404 Not Found page." }, { "code": null, "e": 10654, "s": 10414, "text": "The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL." }, { "code": null, "e": 10715, "s": 10654, "text": "The following script demonstrates use of url_for() function." }, { "code": null, "e": 11176, "s": 10715, "text": "from flask import Flask, redirect, url_for\napp = Flask(__name__)\n\[email protected]('/admin')\ndef hello_admin():\n return 'Hello Admin'\n\[email protected]('/guest/<guest>')\ndef hello_guest(guest):\n return 'Hello %s as Guest' % guest\n\[email protected]('/user/<name>')\ndef hello_user(name):\n if name =='admin':\n return redirect(url_for('hello_admin'))\n else:\n return redirect(url_for('hello_guest',guest = name))\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 11271, "s": 11176, "text": "The above script has a function user(name) which accepts a value to its argument from the URL." }, { "code": null, "e": 11534, "s": 11271, "text": "The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it." }, { "code": null, "e": 11581, "s": 11534, "text": "Save the above code and run from Python shell." }, { "code": null, "e": 11650, "s": 11581, "text": "Open the browser and enter URL as − http://localhost:5000/user/admin" }, { "code": null, "e": 11691, "s": 11650, "text": "The application response in browser is −" }, { "code": null, "e": 11704, "s": 11691, "text": "Hello Admin\n" }, { "code": null, "e": 11776, "s": 11704, "text": "Enter the following URL in the browser − http://localhost:5000/user/mvl" }, { "code": null, "e": 11818, "s": 11776, "text": "The application response now changes to −" }, { "code": null, "e": 11838, "s": 11818, "text": "Hello mvl as Guest\n" }, { "code": null, "e": 11996, "s": 11838, "text": "Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol." }, { "code": null, "e": 12052, "s": 11996, "text": "The following table summarizes different http methods −" }, { "code": null, "e": 12056, "s": 12052, "text": "GET" }, { "code": null, "e": 12122, "s": 12056, "text": "Sends data in unencrypted form to the server. Most common method." }, { "code": null, "e": 12127, "s": 12122, "text": "HEAD" }, { "code": null, "e": 12166, "s": 12127, "text": "Same as GET, but without response body" }, { "code": null, "e": 12171, "s": 12166, "text": "POST" }, { "code": null, "e": 12264, "s": 12171, "text": "Used to send HTML form data to server. Data received by POST method is not cached by server." }, { "code": null, "e": 12268, "s": 12264, "text": "PUT" }, { "code": null, "e": 12355, "s": 12268, "text": "Replaces all current representations of the target resource with the uploaded content." }, { "code": null, "e": 12362, "s": 12355, "text": "DELETE" }, { "code": null, "e": 12436, "s": 12362, "text": "Removes all current representations of the target resource given by a URL" }, { "code": null, "e": 12586, "s": 12436, "text": "By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator." }, { "code": null, "e": 12734, "s": 12586, "text": "In order to demonstrate the use of POST method in URL routing, first let us create an HTML form and use the POST method to send form data to a URL." }, { "code": null, "e": 12774, "s": 12734, "text": "Save the following script as login.html" }, { "code": null, "e": 13031, "s": 12774, "text": "<html>\n <body>\n <form action = \"http://localhost:5000/login\" method = \"post\">\n <p>Enter Name:</p>\n <p><input type = \"text\" name = \"nm\" /></p>\n <p><input type = \"submit\" value = \"submit\" /></p>\n </form>\n </body>\n</html>" }, { "code": null, "e": 13079, "s": 13031, "text": "Now enter the following script in Python shell." }, { "code": null, "e": 13564, "s": 13079, "text": "from flask import Flask, redirect, url_for, request\napp = Flask(__name__)\n\[email protected]('/success/<name>')\ndef success(name):\n return 'welcome %s' % name\n\[email protected]('/login',methods = ['POST', 'GET'])\ndef login():\n if request.method == 'POST':\n user = request.form['nm']\n return redirect(url_for('success',name = user))\n else:\n user = request.args.get('nm')\n return redirect(url_for('success',name = user))\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 13688, "s": 13564, "text": "After the development server starts running, open login.html in the browser, enter name in the text field and click Submit." }, { "code": null, "e": 13749, "s": 13688, "text": "Form data is POSTed to the URL in action clause of form tag." }, { "code": null, "e": 13927, "s": 13749, "text": "http://localhost/login is mapped to the login() function. Since the server has received data by POST method, value of ‘nm’ parameter obtained from the form data is obtained by −" }, { "code": null, "e": 13954, "s": 13927, "text": "user = request.form['nm']\n" }, { "code": null, "e": 14057, "s": 13954, "text": "It is passed to ‘/success’ URL as variable part. The browser displays a welcome message in the window." }, { "code": null, "e": 14241, "s": 14057, "text": "Change the method parameter to ‘GET’ in login.html and open it again in the browser. The data received on server is by the GET method. The value of ‘nm’ parameter is now obtained by −" }, { "code": null, "e": 14272, "s": 14241, "text": "User = request.args.get(‘nm’)\n" }, { "code": null, "e": 14462, "s": 14272, "text": "Here, args is dictionary object containing a list of pairs of form parameter and its corresponding value. The value corresponding to ‘nm’ parameter is passed on to ‘/success’ URL as before." }, { "code": null, "e": 14668, "s": 14462, "text": "It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render ‘Hello World’ with <h1> tag attached to it." }, { "code": null, "e": 14856, "s": 14668, "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return '<html><body><h1>Hello World</h1></body></html>'\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 15071, "s": 14856, "text": "However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML." }, { "code": null, "e": 15277, "s": 15071, "text": "This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function." }, { "code": null, "e": 15446, "s": 15277, "text": "from flask import Flask\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return render_template(‘hello.html’)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 15560, "s": 15446, "text": "Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present." }, { "code": null, "e": 15615, "s": 15560, "text": "Application folder\n\nHello.py\ntemplates\n\nhello.html\n\n\n\n" }, { "code": null, "e": 15624, "s": 15615, "text": "Hello.py" }, { "code": null, "e": 15648, "s": 15624, "text": "templates\n\nhello.html\n\n" }, { "code": null, "e": 15659, "s": 15648, "text": "hello.html" }, { "code": null, "e": 15888, "s": 15659, "text": "The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor." }, { "code": null, "e": 16107, "s": 15888, "text": "Flask uses Jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered." }, { "code": null, "e": 16174, "s": 16107, "text": "The following code is saved as hello.html in the templates folder." }, { "code": null, "e": 16270, "s": 16174, "text": "<!doctype html>\n<html>\n <body>\n \n <h1>Hello {{ name }}!</h1>\n \n </body>\n</html>" }, { "code": null, "e": 16320, "s": 16270, "text": "Next, run the following script from Python shell." }, { "code": null, "e": 16540, "s": 16320, "text": "from flask import Flask, render_template\napp = Flask(__name__)\n\[email protected]('/hello/<user>')\ndef hello_name(user):\n return render_template('hello.html', name = user)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 16650, "s": 16540, "text": "As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl" }, { "code": null, "e": 16715, "s": 16650, "text": "The variable part of URL is inserted at {{ name }} place holder." }, { "code": null, "e": 16796, "s": 16715, "text": "The Jinja2 template engine uses the following delimiters for escaping from HTML." }, { "code": null, "e": 16821, "s": 16796, "text": "{% ... %} for Statements" }, { "code": null, "e": 16879, "s": 16821, "text": "{{ ... }} for Expressions to print to the template output" }, { "code": null, "e": 16938, "s": 16879, "text": "{# ... #} for Comments not included in the template output" }, { "code": null, "e": 16967, "s": 16938, "text": "# ... ## for Line Statements" }, { "code": null, "e": 17298, "s": 16967, "text": "In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered." }, { "code": null, "e": 17332, "s": 17298, "text": "The Python Script is as follows −" }, { "code": null, "e": 17560, "s": 17332, "text": "from flask import Flask, render_template\napp = Flask(__name__)\n\[email protected]('/hello/<int:score>')\ndef hello_name(score):\n return render_template('hello.html', marks = score)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 17611, "s": 17560, "text": "HTML template script of hello.html is as follows −" }, { "code": null, "e": 17800, "s": 17611, "text": "<!doctype html>\n<html>\n <body>\n {% if marks>50 %}\n <h1> Your result is pass!</h1>\n {% else %}\n <h1>Your result is fail</h1>\n {% endif %}\n </body>\n</html>" }, { "code": null, "e": 17889, "s": 17800, "text": "Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}." }, { "code": null, "e": 18036, "s": 17889, "text": "Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally." }, { "code": null, "e": 18267, "s": 18036, "text": "The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser." }, { "code": null, "e": 18406, "s": 18267, "text": "The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table." }, { "code": null, "e": 18448, "s": 18406, "text": "Run the following code from Python shell." }, { "code": null, "e": 18698, "s": 18448, "text": "from flask import Flask, render_template\napp = Flask(__name__)\n\[email protected]('/result')\ndef result():\n dict = {'phy':50,'che':60,'maths':70}\n return render_template('result.html', result = dict)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 18769, "s": 18698, "text": "Save the following HTML script as result.html in the templates folder." }, { "code": null, "e": 19040, "s": 18769, "text": "<!doctype html>\n<html>\n <body>\n <table border = 1>\n {% for key, value in result.items() %}\n <tr>\n <th> {{ key }} </th>\n <td> {{ value }} </td>\n </tr>\n {% endfor %}\n </table>\n </body>\n</html>" }, { "code": null, "e": 19188, "s": 19040, "text": "Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}." }, { "code": null, "e": 19304, "s": 19188, "text": "After the development starts running, open http://localhost:5000/result in the browser to get the following output." }, { "code": null, "e": 19655, "s": 19304, "text": "A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application." }, { "code": null, "e": 19725, "s": 19655, "text": "A special endpoint ‘static’ is used to generate URL for static files." }, { "code": null, "e": 19905, "s": 19725, "text": "In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application." }, { "code": null, "e": 20091, "s": 19905, "text": "from flask import Flask, render_template\napp = Flask(__name__)\n\[email protected](\"/\")\ndef index():\n return render_template(\"index.html\")\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 20137, "s": 20091, "text": "The HTML script of index.html is given below." }, { "code": null, "e": 20388, "s": 20137, "text": "<html>\n <head>\n <script type = \"text/javascript\" \n src = \"{{ url_for('static', filename = 'hello.js') }}\" ></script>\n </head>\n \n <body>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" />\n </body>\n</html>" }, { "code": null, "e": 20427, "s": 20388, "text": "hello.js contains sayHello() function." }, { "code": null, "e": 20475, "s": 20427, "text": "function sayHello() {\n alert(\"Hello World\")\n}" }, { "code": null, "e": 20642, "s": 20475, "text": "The data from a client’s web page is sent to the server as a global request object. In order to process the request data, it should be imported from the Flask module." }, { "code": null, "e": 20700, "s": 20642, "text": "Important attributes of request object are listed below −" }, { "code": null, "e": 20801, "s": 20700, "text": "Form − It is a dictionary object containing key and value pairs of form parameters and their values." }, { "code": null, "e": 20902, "s": 20801, "text": "Form − It is a dictionary object containing key and value pairs of form parameters and their values." }, { "code": null, "e": 20987, "s": 20902, "text": "args − parsed contents of query string which is part of URL after question mark (?)." }, { "code": null, "e": 21072, "s": 20987, "text": "args − parsed contents of query string which is part of URL after question mark (?)." }, { "code": null, "e": 21133, "s": 21072, "text": "Cookies − dictionary object holding Cookie names and values." }, { "code": null, "e": 21194, "s": 21133, "text": "Cookies − dictionary object holding Cookie names and values." }, { "code": null, "e": 21236, "s": 21194, "text": "files − data pertaining to uploaded file." }, { "code": null, "e": 21278, "s": 21236, "text": "files − data pertaining to uploaded file." }, { "code": null, "e": 21311, "s": 21278, "text": "method − current request method." }, { "code": null, "e": 21344, "s": 21311, "text": "method − current request method." }, { "code": null, "e": 21586, "s": 21344, "text": "We have already seen that the http method can be specified in URL rule. The Form data received by the triggered function can collect it in the form of a dictionary object and forward it to a template to render it on a corresponding web page." }, { "code": null, "e": 21763, "s": 21586, "text": "In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function." }, { "code": null, "e": 21895, "s": 21763, "text": "The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html." }, { "code": null, "e": 21956, "s": 21895, "text": "The template dynamically renders an HTML table of form data." }, { "code": null, "e": 22004, "s": 21956, "text": "Given below is the Python code of application −" }, { "code": null, "e": 22386, "s": 22004, "text": "from flask import Flask, render_template, request\napp = Flask(__name__)\n\[email protected]('/')\ndef student():\n return render_template('student.html')\n\[email protected]('/result',methods = ['POST', 'GET'])\ndef result():\n if request.method == 'POST':\n result = request.form\n return render_template(\"result.html\",result = result)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 22434, "s": 22386, "text": "Given below is the HTML script of student.html." }, { "code": null, "e": 22871, "s": 22434, "text": "<html>\n <body>\n <form action = \"http://localhost:5000/result\" method = \"POST\">\n <p>Name <input type = \"text\" name = \"Name\" /></p>\n <p>Physics <input type = \"text\" name = \"Physics\" /></p>\n <p>Chemistry <input type = \"text\" name = \"chemistry\" /></p>\n <p>Maths <input type =\"text\" name = \"Mathematics\" /></p>\n <p><input type = \"submit\" value = \"submit\" /></p>\n </form>\n </body>\n</html>" }, { "code": null, "e": 22919, "s": 22871, "text": "Code of template (result.html) is given below −" }, { "code": null, "e": 23190, "s": 22919, "text": "<!doctype html>\n<html>\n <body>\n <table border = 1>\n {% for key, value in result.items() %}\n <tr>\n <th> {{ key }} </th>\n <td> {{ value }} </td>\n </tr>\n {% endfor %}\n </table>\n </body>\n</html>" }, { "code": null, "e": 23269, "s": 23190, "text": "Run the Python script and enter the URL http://localhost:5000/ in the browser." }, { "code": null, "e": 23368, "s": 23269, "text": "When the Submit button is clicked, form data is rendered on result.html in the form of HTML table." }, { "code": null, "e": 23562, "s": 23368, "text": "A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics." }, { "code": null, "e": 23813, "s": 23562, "text": "A Request object contains a cookie’s attribute. It is a dictionary object of all the cookie variables and their corresponding values, a client has transmitted. In addition to it, a cookie also stores its expiry time, path and domain name of the site." }, { "code": null, "e": 24029, "s": 23813, "text": "In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie." }, { "code": null, "e": 24132, "s": 24029, "text": "Reading back a cookie is easy. The get() method of request.cookies attribute is used to read a cookie." }, { "code": null, "e": 24213, "s": 24132, "text": "In the following Flask application, a simple form opens up as you visit ‘/’ URL." }, { "code": null, "e": 24282, "s": 24213, "text": "@app.route('/')\ndef index():\n return render_template('index.html')" }, { "code": null, "e": 24322, "s": 24282, "text": "This HTML page contains one text input." }, { "code": null, "e": 24569, "s": 24322, "text": "<html>\n <body>\n <form action = \"/setcookie\" method = \"POST\">\n <p><h3>Enter userID</h3></p>\n <p><input type = 'text' name = 'nm'/></p>\n <p><input type = 'submit' value = 'Login'/></p>\n </form>\n </body>\n</html>" }, { "code": null, "e": 24690, "s": 24569, "text": "The Form is posted to ‘/setcookie’ URL. The associated view function sets a Cookie name userID and renders another page." }, { "code": null, "e": 24938, "s": 24690, "text": "@app.route('/setcookie', methods = ['POST', 'GET'])\ndef setcookie():\n if request.method == 'POST':\n user = request.form['nm']\n \n resp = make_response(render_template('readcookie.html'))\n resp.set_cookie('userID', user)\n \n return resp" }, { "code": null, "e": 25074, "s": 24938, "text": "‘readcookie.html’ contains a hyperlink to another view function getcookie(), which reads back and displays the cookie value in browser." }, { "code": null, "e": 25194, "s": 25074, "text": "@app.route('/getcookie')\ndef getcookie():\n name = request.cookies.get('userID')\n return '<h1>welcome '+name+'</h1>'" }, { "code": null, "e": 25247, "s": 25194, "text": "Run the application and visit http://localhost:5000/" }, { "code": null, "e": 25303, "s": 25247, "text": "The result of setting a cookie is displayed like this −" }, { "code": null, "e": 25350, "s": 25303, "text": "The output of read back cookie is shown below." }, { "code": null, "e": 25570, "s": 25350, "text": "Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser." }, { "code": null, "e": 25782, "s": 25570, "text": "A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY." }, { "code": null, "e": 25896, "s": 25782, "text": "Session object is also a dictionary object containing key-value pairs of session variables and associated values." }, { "code": null, "e": 25966, "s": 25896, "text": "For example, to set a ‘username’ session variable use the statement −" }, { "code": null, "e": 25997, "s": 25966, "text": "Session[‘username’] = ’admin’\n" }, { "code": null, "e": 26045, "s": 25997, "text": "To release a session variable use pop() method." }, { "code": null, "e": 26076, "s": 26045, "text": "session.pop('username', None)\n" }, { "code": null, "e": 26230, "s": 26076, "text": "The following code is a simple demonstration of session works in Flask. URL ‘/’ simply prompts user to log in, as session variable ‘username’ is not set." }, { "code": null, "e": 26548, "s": 26230, "text": "@app.route('/')\ndef index():\n if 'username' in session:\n username = session['username']\n return 'Logged in as ' + username + '<br>' + \\\n \"<b><a href = '/logout'>click here to log out</a></b>\"\n return \"You are not logged in <br><a href = '/login'></b>\" + \\\n \"click here to log in</b></a>\"" }, { "code": null, "e": 26667, "s": 26548, "text": "As user browses to ‘/login’ the login() view function, because it is called through GET method, opens up a login form." }, { "code": null, "e": 26816, "s": 26667, "text": "A Form is posted back to ‘/login’ and now session variable is set. Application is redirected to ‘/’. This time session variable ‘username’ is found." }, { "code": null, "e": 27176, "s": 26816, "text": "@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n session['username'] = request.form['username']\n return redirect(url_for('index'))\n return '''\n\t\n <form action = \"\" method = \"post\">\n <p><input type = text name = username/></p>\n <p<<input type = submit value = Login/></p>\n </form>\n\t\n '''" }, { "code": null, "e": 27321, "s": 27176, "text": "The application also contains a logout() view function, which pops out ‘username’ session variable. Hence, ‘/’ URL again shows the opening page." }, { "code": null, "e": 27484, "s": 27321, "text": "@app.route('/logout')\ndef logout():\n # remove the username from the session if it is there\n session.pop('username', None)\n return redirect(url_for('index'))" }, { "code": null, "e": 27574, "s": 27484, "text": "Run the application and visit the homepage. (Ensure to set secret_key of the application)" }, { "code": null, "e": 27702, "s": 27574, "text": "from flask import Flask, session, redirect, url_for, escape, request\napp = Flask(__name__)\napp.secret_key = 'any random string’" }, { "code": null, "e": 27786, "s": 27702, "text": "The output will be displayed as shown below. Click the link “click here to log in”." }, { "code": null, "e": 27845, "s": 27786, "text": "The link will be directed to another screen. Type ‘admin’." }, { "code": null, "e": 27905, "s": 27845, "text": "The screen will show you the message, ‘Logged in as admin’." }, { "code": null, "e": 28064, "s": 27905, "text": "Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code." }, { "code": null, "e": 28111, "s": 28064, "text": "Prototype of redirect() function is as below −" }, { "code": null, "e": 28159, "s": 28111, "text": "Flask.redirect(location, statuscode, response)\n" }, { "code": null, "e": 28183, "s": 28159, "text": "In the above function −" }, { "code": null, "e": 28250, "s": 28183, "text": "location parameter is the URL where response should be redirected." }, { "code": null, "e": 28317, "s": 28250, "text": "location parameter is the URL where response should be redirected." }, { "code": null, "e": 28371, "s": 28317, "text": "statuscode sent to browser’s header, defaults to 302." }, { "code": null, "e": 28425, "s": 28371, "text": "statuscode sent to browser’s header, defaults to 302." }, { "code": null, "e": 28477, "s": 28425, "text": "response parameter is used to instantiate response." }, { "code": null, "e": 28529, "s": 28477, "text": "response parameter is used to instantiate response." }, { "code": null, "e": 28575, "s": 28529, "text": "The following status codes are standardized −" }, { "code": null, "e": 28601, "s": 28575, "text": "HTTP_300_MULTIPLE_CHOICES" }, { "code": null, "e": 28628, "s": 28601, "text": "HTTP_301_MOVED_PERMANENTLY" }, { "code": null, "e": 28643, "s": 28628, "text": "HTTP_302_FOUND" }, { "code": null, "e": 28662, "s": 28643, "text": "HTTP_303_SEE_OTHER" }, { "code": null, "e": 28684, "s": 28662, "text": "HTTP_304_NOT_MODIFIED" }, { "code": null, "e": 28703, "s": 28684, "text": "HTTP_305_USE_PROXY" }, { "code": null, "e": 28721, "s": 28703, "text": "HTTP_306_RESERVED" }, { "code": null, "e": 28749, "s": 28721, "text": "HTTP_307_TEMPORARY_REDIRECT" }, { "code": null, "e": 28803, "s": 28749, "text": "The default status code is 302, which is for ‘found’." }, { "code": null, "e": 28921, "s": 28803, "text": "In the following example, the redirect() function is used to display the login page again when a login attempt fails." }, { "code": null, "e": 29473, "s": 28921, "text": "from flask import Flask, redirect, url_for, render_template, request\n# Initialize the Flask application\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return render_template('log_in.html')\n\[email protected]('/login',methods = ['POST', 'GET']) \ndef login(): \n if request.method == 'POST' and request.form['username'] == 'admin' :\n return redirect(url_for('success'))\n else:\n return redirect(url_for('index'))\n\[email protected]('/success')\ndef success():\n return 'logged in successfully'\n\t\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 29526, "s": 29473, "text": "Flask class has abort() function with an error code." }, { "code": null, "e": 29545, "s": 29526, "text": "Flask.abort(code)\n" }, { "code": null, "e": 29596, "s": 29545, "text": "The Code parameter takes one of following values −" }, { "code": null, "e": 29618, "s": 29596, "text": "400 − for Bad Request" }, { "code": null, "e": 29640, "s": 29618, "text": "400 − for Bad Request" }, { "code": null, "e": 29666, "s": 29640, "text": "401 − for Unauthenticated" }, { "code": null, "e": 29692, "s": 29666, "text": "401 − for Unauthenticated" }, { "code": null, "e": 29712, "s": 29692, "text": "403 − for Forbidden" }, { "code": null, "e": 29732, "s": 29712, "text": "403 − for Forbidden" }, { "code": null, "e": 29752, "s": 29732, "text": "404 − for Not Found" }, { "code": null, "e": 29772, "s": 29752, "text": "404 − for Not Found" }, { "code": null, "e": 29797, "s": 29772, "text": "406 − for Not Acceptable" }, { "code": null, "e": 29822, "s": 29797, "text": "406 − for Not Acceptable" }, { "code": null, "e": 29855, "s": 29822, "text": "415 − for Unsupported Media Type" }, { "code": null, "e": 29888, "s": 29855, "text": "415 − for Unsupported Media Type" }, { "code": null, "e": 29912, "s": 29888, "text": "429 − Too Many Requests" }, { "code": null, "e": 29936, "s": 29912, "text": "429 − Too Many Requests" }, { "code": null, "e": 30128, "s": 29936, "text": "Let us make a slight change in the login() function in the above code. Instead of re-displaying the login page, if ‘Unauthourized’ page is to be displayed, replace it with call to abort(401)." }, { "code": null, "e": 30690, "s": 30128, "text": "from flask import Flask, redirect, url_for, render_template, request, abort\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return render_template('log_in.html')\n\[email protected]('/login',methods = ['POST', 'GET'])\ndef login():\n if request.method == 'POST':\n if request.form['username'] == 'admin' :\n return redirect(url_for('success'))\n else:\n abort(401)\n else:\n return redirect(url_for('index'))\n\[email protected]('/success')\ndef success():\n return 'logged in successfully'\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 30882, "s": 30690, "text": "A good GUI based application provides feedback to a user about the interaction. For example, the desktop applications use dialog or message box and JavaScript uses alerts for similar purpose." }, { "code": null, "e": 31084, "s": 30882, "text": "Generating such informative messages is easy in Flask web application. Flashing system of Flask framework makes it possible to create a message in one view and render it in a view function called next." }, { "code": null, "e": 31196, "s": 31084, "text": "A Flask module contains flash() method. It passes a message to the next request, which generally is a template." }, { "code": null, "e": 31222, "s": 31196, "text": "flash(message, category)\n" }, { "code": null, "e": 31228, "s": 31222, "text": "Here," }, { "code": null, "e": 31283, "s": 31228, "text": "message parameter is the actual message to be flashed." }, { "code": null, "e": 31338, "s": 31283, "text": "message parameter is the actual message to be flashed." }, { "code": null, "e": 31417, "s": 31338, "text": "category parameter is optional. It can be either ‘error’, ‘info’ or ‘warning’." }, { "code": null, "e": 31496, "s": 31417, "text": "category parameter is optional. It can be either ‘error’, ‘info’ or ‘warning’." }, { "code": null, "e": 31576, "s": 31496, "text": "In order to remove message from session, template calls get_flashed_messages()." }, { "code": null, "e": 31632, "s": 31576, "text": "get_flashed_messages(with_categories, category_filter)\n" }, { "code": null, "e": 31801, "s": 31632, "text": "Both parameters are optional. The first parameter is a tuple if received messages are having category. The second parameter is useful to display only specific messages." }, { "code": null, "e": 31856, "s": 31801, "text": "The following flashes received messages in a template." }, { "code": null, "e": 32029, "s": 31856, "text": "{% with messages = get_flashed_messages() %}\n {% if messages %}\n {% for message in messages %}\n {{ message }}\n {% endfor %}\n {% endif %}\n{% endwith %}" }, { "code": null, "e": 32201, "s": 32029, "text": "Let us now see a simple example, demonstrating the flashing mechanism in Flask. In the following code, a ‘/’ URL displays link to the login page, with no message to flash." }, { "code": null, "e": 32270, "s": 32201, "text": "@app.route('/')\ndef index():\n return render_template('index.html')" }, { "code": null, "e": 32485, "s": 32270, "text": "The link leads a user to ‘/login’ URL which displays a login form. When submitted, the login() view function verifies a username and password and accordingly flashes a ‘success’ message or creates ‘error’ variable." }, { "code": null, "e": 32921, "s": 32485, "text": "@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n error = None\n \n if request.method == 'POST':\n if request.form['username'] != 'admin' or \\\n request.form['password'] != 'admin':\n error = 'Invalid username or password. Please try again!'\n else:\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n return render_template('login.html', error = error)" }, { "code": null, "e": 32993, "s": 32921, "text": "In case of error, the login template is redisplayed with error message." }, { "code": null, "e": 33560, "s": 32993, "text": "<!doctype html>\n<html>\n <body>\n <h1>Login</h1>\n\n {% if error %}\n <p><strong>Error:</strong> {{ error }}\n {% endif %}\n \n <form action = \"\" method = post>\n <dl>\n <dt>Username:</dt>\n <dd>\n <input type = text name = username \n value = \"{{request.form.username }}\">\n </dd>\n <dt>Password:</dt>\n <dd><input type = password name = password></dd>\n </dl>\n <p><input type = submit value = Login></p>\n </form>\n </body>\n</html>" }, { "code": null, "e": 33655, "s": 33560, "text": "On the other hand, if login is successful, a success message is flashed on the index template." }, { "code": null, "e": 34178, "s": 33655, "text": "<!doctype html>\n<html>\n <head>\n <title>Flask Message flashing</title>\n </head>\n <body>\n {% with messages = get_flashed_messages() %}\n {% if messages %}\n <ul>\n {% for message in messages %}\n <li<{{ message }}</li>\n {% endfor %}\n </ul>\n {% endif %}\n {% endwith %}\n\t\t\n <h1>Flask Message Flashing Example</h1>\n <p>Do you want to <a href = \"{{ url_for('login') }}\">\n <b>log in?</b></a></p>\n </body>\n</html>" }, { "code": null, "e": 34246, "s": 34178, "text": "A complete code for Flask message flashing example is given below −" }, { "code": null, "e": 34941, "s": 34246, "text": "from flask import Flask, flash, redirect, render_template, request, url_for\napp = Flask(__name__)\napp.secret_key = 'random string'\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\[email protected]('/login', methods = ['GET', 'POST'])\ndef login():\n error = None\n \n if request.method == 'POST':\n if request.form['username'] != 'admin' or \\\n request.form['password'] != 'admin':\n error = 'Invalid username or password. Please try again!'\n else:\n flash('You were successfully logged in')\n return redirect(url_for('index'))\n\t\t\t\n return render_template('login.html', error = error)\n\nif __name__ == \"__main__\":\n app.run(debug = True)" }, { "code": null, "e": 35014, "s": 34941, "text": "After executing the above codes, you will see the screen as shown below." }, { "code": null, "e": 35082, "s": 35014, "text": "When you click on the link, you will be directed to the Login page." }, { "code": null, "e": 35115, "s": 35082, "text": "Enter the Username and password." }, { "code": null, "e": 35192, "s": 35115, "text": "Click Login. A message will be displayed “You were successfully logged in” ." }, { "code": null, "e": 35437, "s": 35192, "text": "Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to ‘multipart/form-data’, posting the file to a URL. The URL handler fetches file from request.files[] object and saves it to the desired location." }, { "code": null, "e": 35778, "s": 35437, "text": "Each uploaded file is first saved in a temporary location on the server, before it is actually saved to its ultimate location. Name of destination file can be hard-coded or can be obtained from filename property of request.files[file] object. However, it is recommended to obtain a secure version of it using the secure_filename() function." }, { "code": null, "e": 35914, "s": 35778, "text": "It is possible to define the path of default upload folder and maximum size of uploaded file in configuration settings of Flask object." }, { "code": null, "e": 36095, "s": 35914, "text": "The following code has ‘/upload’ URL rule that displays ‘upload.html’ from the templates folder, and ‘/upload-file’ URL rule that calls uploader() function handling upload process." }, { "code": null, "e": 36156, "s": 36095, "text": "‘upload.html’ has a file chooser button and a submit button." }, { "code": null, "e": 36400, "s": 36156, "text": "<html>\n <body>\n <form action = \"http://localhost:5000/uploader\" method = \"POST\" \n enctype = \"multipart/form-data\">\n <input type = \"file\" name = \"file\" />\n <input type = \"submit\"/>\n </form>\n </body>\n</html>" }, { "code": null, "e": 36440, "s": 36400, "text": "You will see the screen as shown below." }, { "code": null, "e": 36581, "s": 36440, "text": "Click Submit after choosing file. Form’s post method invokes ‘/upload_file’ URL. The underlying function uploader() does the save operation." }, { "code": null, "e": 36632, "s": 36581, "text": "Following is the Python code of Flask application." }, { "code": null, "e": 37099, "s": 36632, "text": "from flask import Flask, render_template, request\nfrom werkzeug import secure_filename\napp = Flask(__name__)\n\[email protected]('/upload')\ndef upload_file():\n return render_template('upload.html')\n\t\[email protected]('/uploader', methods = ['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n f = request.files['file']\n f.save(secure_filename(f.filename))\n return 'file uploaded successfully'\n\t\t\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 37568, "s": 37099, "text": "Flask is often referred to as a micro framework, because a core functionality includes WSGI and routing based on Werkzeug and template engine based on Jinja2. In addition, Flask framework has support for cookie and sessions as well as web helpers like JSON, static files etc. Obviously, this is not enough for the development of a full-fledged web application. This is where the Flask extensions come in picture. Flask extensions give extensibility to Flask framework." }, { "code": null, "e": 37846, "s": 37568, "text": "There are a large number of Flask extensions available. A Flask extension is a Python module, which adds specific type of support to the Flask application. Flask Extension Registry is a directory of extensions available. The required extension can be downloaded by pip utility." }, { "code": null, "e": 37923, "s": 37846, "text": "In this tutorial, we will discuss the following important Flask extensions −" }, { "code": null, "e": 37981, "s": 37923, "text": "Flask Mail − provides SMTP interface to Flask application" }, { "code": null, "e": 38039, "s": 37981, "text": "Flask Mail − provides SMTP interface to Flask application" }, { "code": null, "e": 38092, "s": 38039, "text": "Flask WTF − adds rendering and validation of WTForms" }, { "code": null, "e": 38145, "s": 38092, "text": "Flask WTF − adds rendering and validation of WTForms" }, { "code": null, "e": 38209, "s": 38145, "text": "Flask SQLAlchemy − adds SQLAlchemy support to Flask application" }, { "code": null, "e": 38273, "s": 38209, "text": "Flask SQLAlchemy − adds SQLAlchemy support to Flask application" }, { "code": null, "e": 38379, "s": 38273, "text": "Flask Sijax − Interface for Sijax - Python/jQuery library that makes AJAX easy to use in web applications" }, { "code": null, "e": 38485, "s": 38379, "text": "Flask Sijax − Interface for Sijax - Python/jQuery library that makes AJAX easy to use in web applications" }, { "code": null, "e": 38710, "s": 38485, "text": "Each type of extension usually provides extensive documentation about its usage. Since an extension is a Python module, it needs to be imported for it to be used. Flask extensions are generally named as flask-foo. To import," }, { "code": null, "e": 38751, "s": 38710, "text": "from flask_foo import [class, function]\n" }, { "code": null, "e": 38819, "s": 38751, "text": "For versions of Flask later than 0.7, you can also use the syntax −" }, { "code": null, "e": 38846, "s": 38819, "text": "from flask.ext import foo\n" }, { "code": null, "e": 38958, "s": 38846, "text": "For this usage, a compatibility module needs to be activated. It can be installed by running flaskext_compat.py" }, { "code": null, "e": 39034, "s": 38958, "text": "import flaskext_compat\nflaskext_compat.activate()\nfrom flask.ext import foo" }, { "code": null, "e": 39224, "s": 39034, "text": "A web based application is often required to have a feature of sending mail to the users/clients. Flask-Mail extension makes it very easy to set up a simple interface with any email server." }, { "code": null, "e": 39305, "s": 39224, "text": "At first, Flask-Mail extension should be installed with the help of pip utility." }, { "code": null, "e": 39329, "s": 39305, "text": "pip install Flask-Mail\n" }, { "code": null, "e": 39427, "s": 39329, "text": "Then Flask-Mail needs to be configured by setting values of the following application parameters." }, { "code": null, "e": 39439, "s": 39427, "text": "MAIL_SERVER" }, { "code": null, "e": 39471, "s": 39439, "text": "Name/IP address of email server" }, { "code": null, "e": 39481, "s": 39471, "text": "MAIL_PORT" }, { "code": null, "e": 39508, "s": 39481, "text": "Port number of server used" }, { "code": null, "e": 39521, "s": 39508, "text": "MAIL_USE_TLS" }, { "code": null, "e": 39572, "s": 39521, "text": "Enable/disable Transport Security Layer encryption" }, { "code": null, "e": 39585, "s": 39572, "text": "MAIL_USE_SSL" }, { "code": null, "e": 39632, "s": 39585, "text": "Enable/disable Secure Sockets Layer encryption" }, { "code": null, "e": 39643, "s": 39632, "text": "MAIL_DEBUG" }, { "code": null, "e": 39702, "s": 39643, "text": "Debug support. Default is Flask application’s debug status" }, { "code": null, "e": 39716, "s": 39702, "text": "MAIL_USERNAME" }, { "code": null, "e": 39736, "s": 39716, "text": "User name of sender" }, { "code": null, "e": 39750, "s": 39736, "text": "MAIL_PASSWORD" }, { "code": null, "e": 39769, "s": 39750, "text": "password of sender" }, { "code": null, "e": 39789, "s": 39769, "text": "MAIL_DEFAULT_SENDER" }, { "code": null, "e": 39809, "s": 39789, "text": "sets default sender" }, { "code": null, "e": 39825, "s": 39809, "text": "MAIL_MAX_EMAILS" }, { "code": null, "e": 39855, "s": 39825, "text": "Sets maximum mails to be sent" }, { "code": null, "e": 39874, "s": 39855, "text": "MAIL_SUPPRESS_SEND" }, { "code": null, "e": 39920, "s": 39874, "text": "Sending suppressed if app.testing set to true" }, { "code": null, "e": 39943, "s": 39920, "text": "MAIL_ASCII_ATTACHMENTS" }, { "code": null, "e": 39997, "s": 39943, "text": "If set to true, attached filenames converted to ASCII" }, { "code": null, "e": 40076, "s": 39997, "text": "The flask-mail module contains definitions of the following important classes." }, { "code": null, "e": 40166, "s": 40076, "text": "It manages email-messaging requirements. The class constructor takes the following form −" }, { "code": null, "e": 40195, "s": 40166, "text": "flask-mail.Mail(app = None)\n" }, { "code": null, "e": 40262, "s": 40195, "text": "The Constructor takes the Flask application object as a parameter." }, { "code": null, "e": 40269, "s": 40262, "text": "send()" }, { "code": null, "e": 40308, "s": 40269, "text": "Sends contents of Message class object" }, { "code": null, "e": 40318, "s": 40308, "text": "connect()" }, { "code": null, "e": 40350, "s": 40318, "text": "Opens connection with mail host" }, { "code": null, "e": 40365, "s": 40350, "text": "send_message()" }, { "code": null, "e": 40386, "s": 40365, "text": "Sends message object" }, { "code": null, "e": 40471, "s": 40386, "text": "It encapsulates an email message. Message class constructor has several parameters −" }, { "code": null, "e": 40613, "s": 40471, "text": "flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, \n reply-to, date, charset, extra_headers, mail_options, rcpt_options)\n" }, { "code": null, "e": 40700, "s": 40613, "text": "attach() − adds an attachment to message. This method takes the following parameters −" }, { "code": null, "e": 40734, "s": 40700, "text": "filename − name of file to attach" }, { "code": null, "e": 40768, "s": 40734, "text": "filename − name of file to attach" }, { "code": null, "e": 40801, "s": 40768, "text": "content_type − MIME type of file" }, { "code": null, "e": 40834, "s": 40801, "text": "content_type − MIME type of file" }, { "code": null, "e": 40855, "s": 40834, "text": "data − raw file data" }, { "code": null, "e": 40876, "s": 40855, "text": "data − raw file data" }, { "code": null, "e": 40919, "s": 40876, "text": "disposition − content disposition, if any." }, { "code": null, "e": 40962, "s": 40919, "text": "disposition − content disposition, if any." }, { "code": null, "e": 41014, "s": 40962, "text": "add_recipient() − adds another recipient to message" }, { "code": null, "e": 41131, "s": 41014, "text": "In the following example, SMTP server of Google’s gmail service is used as MAIL_SERVER for Flask-Mail configuration." }, { "code": null, "e": 41206, "s": 41131, "text": "Step 1 − Import Mail and Message class from flask-mail module in the code." }, { "code": null, "e": 41244, "s": 41206, "text": "from flask_mail import Mail, Message\n" }, { "code": null, "e": 41310, "s": 41244, "text": "Step 2 − Then Flask-Mail is configured as per following settings." }, { "code": null, "e": 41540, "s": 41310, "text": "app.config['MAIL_SERVER']='smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = '[email protected]'\napp.config['MAIL_PASSWORD'] = '*****'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\n" }, { "code": null, "e": 41583, "s": 41540, "text": "Step 3 − Create an instance of Mail class." }, { "code": null, "e": 41601, "s": 41583, "text": "mail = Mail(app)\n" }, { "code": null, "e": 41681, "s": 41601, "text": "Step 4 − Set up a Message object in a Python function mapped by URL rule (‘/’)." }, { "code": null, "e": 41871, "s": 41681, "text": "@app.route(\"/\")\ndef index():\n msg = Message('Hello', sender = '[email protected]', recipients = ['[email protected]'])\n msg.body = \"This is the email body\"\n mail.send(msg)\n return \"Sent\"" }, { "code": null, "e": 41987, "s": 41871, "text": "Step 5 − The entire code is given below. Run the following script in Python Shell and visit http://localhost:5000/." }, { "code": null, "e": 42594, "s": 41987, "text": "from flask import Flask\nfrom flask_mail import Mail, Message\n\napp =Flask(__name__)\nmail=Mail(app)\n\napp.config['MAIL_SERVER']='smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = '[email protected]'\napp.config['MAIL_PASSWORD'] = '*****'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\nmail = Mail(app)\n\[email protected](\"/\")\ndef index():\n msg = Message('Hello', sender = '[email protected]', recipients = ['[email protected]'])\n msg.body = \"Hello Flask message sent from Flask-Mail\"\n mail.send(msg)\n return \"Sent\"\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 42808, "s": 42594, "text": "Note that the built-insecurity features in Gmail service may block this login attempt. You may have to decrease the security level. Please log in to your Gmail account and visit this link to decrease the security." }, { "code": null, "e": 43053, "s": 42808, "text": "One of the essential aspects of a web application is to present a user interface for the user. HTML provides a <form> tag, which is used to design an interface. A Form’s elements such as text input, radio, select etc. can be used appropriately." }, { "code": null, "e": 43181, "s": 43053, "text": "Data entered by a user is submitted in the form of Http request message to the server side script by either GET or POST method." }, { "code": null, "e": 43367, "s": 43181, "text": "The Server side script has to recreate the form elements from http request data. So in effect, form elements have to be defined twice – once in HTML and again in the server side script." }, { "code": null, "e": 43553, "s": 43367, "text": "The Server side script has to recreate the form elements from http request data. So in effect, form elements have to be defined twice – once in HTML and again in the server side script." }, { "code": null, "e": 43734, "s": 43553, "text": "Another disadvantage of using HTML form is that it is difficult (if not impossible) to render the form elements dynamically. HTML itself provides no way to validate a user’s input." }, { "code": null, "e": 43915, "s": 43734, "text": "Another disadvantage of using HTML form is that it is difficult (if not impossible) to render the form elements dynamically. HTML itself provides no way to validate a user’s input." }, { "code": null, "e": 44076, "s": 43915, "text": "This is where WTForms, a flexible form, rendering and validation library comes handy. Flask-WTF extension provides a simple interface with this WTForms library." }, { "code": null, "e": 44242, "s": 44076, "text": "Using Flask-WTF, we can define the form fields in our Python script and render them using an HTML template. It is also possible to apply validation to the WTF field." }, { "code": null, "e": 44296, "s": 44242, "text": "Let us see how this dynamic generation of HTML works." }, { "code": null, "e": 44346, "s": 44296, "text": "First, Flask-WTF extension needs to be installed." }, { "code": null, "e": 44369, "s": 44346, "text": "pip install flask-WTF\n" }, { "code": null, "e": 44471, "s": 44369, "text": "The installed package contains a Form class, which has to be used as a parent for user- defined form." }, { "code": null, "e": 44576, "s": 44471, "text": "WTforms package contains definitions of various form fields. Some Standard form fields are listed below." }, { "code": null, "e": 44586, "s": 44576, "text": "TextField" }, { "code": null, "e": 44637, "s": 44586, "text": "Represents <input type = 'text'> HTML form element" }, { "code": null, "e": 44650, "s": 44637, "text": "BooleanField" }, { "code": null, "e": 44705, "s": 44650, "text": "Represents <input type = 'checkbox'> HTML form element" }, { "code": null, "e": 44718, "s": 44705, "text": "DecimalField" }, { "code": null, "e": 44764, "s": 44718, "text": "Textfield for displaying number with decimals" }, { "code": null, "e": 44777, "s": 44764, "text": "IntegerField" }, { "code": null, "e": 44810, "s": 44777, "text": "TextField for displaying integer" }, { "code": null, "e": 44821, "s": 44810, "text": "RadioField" }, { "code": null, "e": 44873, "s": 44821, "text": "Represents <input type = 'radio'> HTML form element" }, { "code": null, "e": 44885, "s": 44873, "text": "SelectField" }, { "code": null, "e": 44916, "s": 44885, "text": "Represents select form element" }, { "code": null, "e": 44930, "s": 44916, "text": "TextAreaField" }, { "code": null, "e": 44970, "s": 44930, "text": "Represents <testarea> html form element" }, { "code": null, "e": 44984, "s": 44970, "text": "PasswordField" }, { "code": null, "e": 45039, "s": 44984, "text": "Represents <input type = 'password'> HTML form element" }, { "code": null, "e": 45051, "s": 45039, "text": "SubmitField" }, { "code": null, "e": 45099, "s": 45051, "text": "Represents <input type = 'submit'> form element" }, { "code": null, "e": 45170, "s": 45099, "text": "For example, a form containing a text field can be designed as below −" }, { "code": null, "e": 45292, "s": 45170, "text": "from flask_wtf import Form\nfrom wtforms import TextField\n\nclass ContactForm(Form):\n name = TextField(\"Name Of Student\")" }, { "code": null, "e": 45435, "s": 45292, "text": "In addition to the ‘name’ field, a hidden field for CSRF token is created automatically. This is to prevent Cross Site Request Forgery attack." }, { "code": null, "e": 45514, "s": 45435, "text": "When rendered, this will result into an equivalent HTML script as shown below." }, { "code": null, "e": 45687, "s": 45514, "text": "<input id = \"csrf_token\" name = \"csrf_token\" type = \"hidden\" />\n<label for = \"name\">Name Of Student</label><br>\n<input id = \"name\" name = \"name\" type = \"text\" value = \"\" />" }, { "code": null, "e": 45787, "s": 45687, "text": "A user-defined form class is used in a Flask application and the form is rendered using a template." }, { "code": null, "e": 46086, "s": 45787, "text": "from flask import Flask, render_template\nfrom forms import ContactForm\napp = Flask(__name__)\napp.secret_key = 'development key'\n\[email protected]('/contact')\ndef contact():\n form = ContactForm()\n return render_template('contact.html', form = form)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 46232, "s": 46086, "text": "WTForms package also contains validator class. It is useful in applying validation to form fields. Following list shows commonly used validators." }, { "code": null, "e": 46245, "s": 46232, "text": "DataRequired" }, { "code": null, "e": 46281, "s": 46245, "text": "Checks whether input field is empty" }, { "code": null, "e": 46287, "s": 46281, "text": "Email" }, { "code": null, "e": 46349, "s": 46287, "text": "Checks whether text in the field follows email ID conventions" }, { "code": null, "e": 46359, "s": 46349, "text": "IPAddress" }, { "code": null, "e": 46395, "s": 46359, "text": "Validates IP address in input field" }, { "code": null, "e": 46402, "s": 46395, "text": "Length" }, { "code": null, "e": 46464, "s": 46402, "text": "Verifies if length of string in input field is in given range" }, { "code": null, "e": 46476, "s": 46464, "text": "NumberRange" }, { "code": null, "e": 46529, "s": 46476, "text": "Validates a number in input field within given range" }, { "code": null, "e": 46533, "s": 46529, "text": "URL" }, { "code": null, "e": 46570, "s": 46533, "text": "Validates URL entered in input field" }, { "code": null, "e": 46656, "s": 46570, "text": "We shall now apply ‘DataRequired’ validation rule for the name field in contact form." }, { "code": null, "e": 46742, "s": 46656, "text": "name = TextField(\"Name Of Student\",[validators.Required(\"Please enter your name.\")])\n" }, { "code": null, "e": 46967, "s": 46742, "text": "The validate() function of form object validates the form data and throws the validation errors if validation fails. The Error messages are sent to the template. In the HTML template, error messages are rendered dynamically." }, { "code": null, "e": 47036, "s": 46967, "text": "{% for message in form.name.errors %}\n {{ message }}\n{% endfor %}\n" }, { "code": null, "e": 47151, "s": 47036, "text": "The following example demonstrates the concepts given above. The design of Contact form is given below (forms.py)." }, { "code": null, "e": 47869, "s": 47151, "text": "from flask_wtf import Form\nfrom wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField,\n SelectField\n\nfrom wtforms import validators, ValidationError\n\nclass ContactForm(Form):\n name = TextField(\"Name Of Student\",[validators.Required(\"Please enter \n your name.\")])\n Gender = RadioField('Gender', choices = [('M','Male'),('F','Female')])\n Address = TextAreaField(\"Address\")\n \n email = TextField(\"Email\",[validators.Required(\"Please enter your email address.\"),\n validators.Email(\"Please enter your email address.\")])\n \n Age = IntegerField(\"age\")\n language = SelectField('Languages', choices = [('cpp', 'C++'), \n ('py', 'Python')])\n submit = SubmitField(\"Send\")" }, { "code": null, "e": 47922, "s": 47869, "text": "Validators are applied to the Name and Email fields." }, { "code": null, "e": 47984, "s": 47922, "text": "Given below is the Flask application script (formexample.py)." }, { "code": null, "e": 48603, "s": 47984, "text": "from flask import Flask, render_template, request, flash\nfrom forms import ContactForm\napp = Flask(__name__)\napp.secret_key = 'development key'\n\[email protected]('/contact', methods = ['GET', 'POST'])\ndef contact():\n form = ContactForm()\n \n if request.method == 'POST':\n if form.validate() == False:\n flash('All fields are required.')\n return render_template('contact.html', form = form)\n else:\n return render_template('success.html')\n elif request.method == 'GET':\n return render_template('contact.html', form = form)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 48661, "s": 48603, "text": "The Script of the template (contact.html) is as follows −" }, { "code": null, "e": 49936, "s": 48661, "text": "<!doctype html>\n<html>\n <body>\n <h2 style = \"text-align: center;\">Contact Form</h2>\n\t\t\n {% for message in form.name.errors %}\n <div>{{ message }}</div>\n {% endfor %}\n \n {% for message in form.email.errors %}\n <div>{{ message }}</div>\n {% endfor %}\n \n <form action = \"http://localhost:5000/contact\" method = post>\n <fieldset>\n <legend>Contact Form</legend>\n {{ form.hidden_tag() }}\n \n <div style = font-size:20px; font-weight:bold; margin-left:150px;>\n {{ form.name.label }}<br>\n {{ form.name }}\n <br>\n \n {{ form.Gender.label }} {{ form.Gender }}\n {{ form.Address.label }}<br>\n {{ form.Address }}\n <br>\n \n {{ form.email.label }}<br>\n {{ form.email }}\n <br>\n \n {{ form.Age.label }}<br>\n {{ form.Age }}\n <br>\n \n {{ form.language.label }}<br>\n {{ form.language }}\n <br>\n {{ form.submit }}\n </div>\n \n </fieldset>\n </form>\n </body>\n</html>" }, { "code": null, "e": 50067, "s": 49936, "text": "Run formexample.py in Python shell and visit URL http://localhost:5000/contact. The Contact form will be displayed as shown below." }, { "code": null, "e": 50123, "s": 50067, "text": "If there are any errors, the page will look like this −" }, { "code": null, "e": 50180, "s": 50123, "text": "If there are no errors, ‘success.html’ will be rendered." }, { "code": null, "e": 50438, "s": 50180, "text": "Python has an in-built support for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, please refer to this link. In this section we shall see how a Flask application interacts with SQLite." }, { "code": null, "e": 50514, "s": 50438, "text": "Create an SQLite database ‘database.db’ and create a students’ table in it." }, { "code": null, "e": 50738, "s": 50514, "text": "import sqlite3\n\nconn = sqlite3.connect('database.db')\nprint \"Opened database successfully\";\n\nconn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')\nprint \"Table created successfully\";\nconn.close()" }, { "code": null, "e": 50786, "s": 50738, "text": "Our Flask application has three View functions." }, { "code": null, "e": 50914, "s": 50786, "text": "First new_student() function is bound to the URL rule (‘/addnew’). It renders an HTML file containing student information form." }, { "code": null, "e": 50999, "s": 50914, "text": "@app.route('/enternew')\ndef new_student():\n return render_template('student.html')" }, { "code": null, "e": 51050, "s": 50999, "text": "The HTML script for ‘student.html’ is as follows −" }, { "code": null, "e": 51566, "s": 51050, "text": "<html>\n <body>\n <form action = \"{{ url_for('addrec') }}\" method = \"POST\">\n <h3>Student Information</h3>\n Name<br>\n <input type = \"text\" name = \"nm\" /></br>\n \n Address<br>\n <textarea name = \"add\" ></textarea><br>\n \n City<br>\n <input type = \"text\" name = \"city\" /><br>\n \n PINCODE<br>\n <input type = \"text\" name = \"pin\" /><br>\n <input type = \"submit\" value = \"submit\" /><br>\n </form>\n </body>\n</html>" }, { "code": null, "e": 51661, "s": 51566, "text": "As it can be seen, form data is posted to the ‘/addrec’ URL which binds the addrec() function." }, { "code": null, "e": 51848, "s": 51661, "text": "This addrec() function retrieves the form’s data by POST method and inserts in students table. Message corresponding to success or error in insert operation is rendered to ‘result.html’." }, { "code": null, "e": 52571, "s": 51848, "text": "@app.route('/addrec',methods = ['POST', 'GET'])\ndef addrec():\n if request.method == 'POST':\n try:\n nm = request.form['nm']\n addr = request.form['add']\n city = request.form['city']\n pin = request.form['pin']\n \n with sql.connect(\"database.db\") as con:\n cur = con.cursor()\n cur.execute(\"INSERT INTO students (name,addr,city,pin) \n VALUES (?,?,?,?)\",(nm,addr,city,pin) )\n \n con.commit()\n msg = \"Record successfully added\"\n except:\n con.rollback()\n msg = \"error in insert operation\"\n \n finally:\n return render_template(\"result.html\",msg = msg)\n con.close()" }, { "code": null, "e": 52687, "s": 52571, "text": "The HTML script of result.html contains an escaping statement {{msg}} that displays the result of Insert operation." }, { "code": null, "e": 52830, "s": 52687, "text": "<!doctype html>\n<html>\n <body>\n result of addition : {{ msg }}\n <h2><a href = \"\\\">go back to home page</a></h2>\n </body>\n</html>" }, { "code": null, "e": 53044, "s": 52830, "text": "The application contains another list() function represented by ‘/list’ URL. It populates ‘rows’ as a MultiDict object containing all records in the students table. This object is passed to the list.html template." }, { "code": null, "e": 53290, "s": 53044, "text": "@app.route('/list')\ndef list():\n con = sql.connect(\"database.db\")\n con.row_factory = sql.Row\n \n cur = con.cursor()\n cur.execute(\"select * from students\")\n \n rows = cur.fetchall(); \n return render_template(\"list.html\",rows = rows)" }, { "code": null, "e": 53391, "s": 53290, "text": "This list.html is a template, which iterates over the row set and renders the data in an HTML table." }, { "code": null, "e": 53940, "s": 53391, "text": "<!doctype html>\n<html>\n <body>\n <table border = 1>\n <thead>\n <td>Name</td>\n <td>Address>/td<\n <td>city</td>\n <td>Pincode</td>\n </thead>\n \n {% for row in rows %}\n <tr>\n <td>{{row[\"name\"]}}</td>\n <td>{{row[\"addr\"]}}</td>\n <td> {{ row[\"city\"]}}</td>\n <td>{{row['pin']}}</td>\t\n </tr>\n {% endfor %}\n </table>\n \n <a href = \"/\">Go back to home page</a>\n </body>\n</html>" }, { "code": null, "e": 54038, "s": 53940, "text": "Finally, the ‘/’ URL rule renders a ‘home.html’ which acts as the entry point of the application." }, { "code": null, "e": 54105, "s": 54038, "text": "@app.route('/')\ndef home():\n return render_template('home.html')" }, { "code": null, "e": 54160, "s": 54105, "text": "Here is the complete code of Flask-SQLite application." }, { "code": null, "e": 55444, "s": 54160, "text": "from flask import Flask, render_template, request\nimport sqlite3 as sql\napp = Flask(__name__)\n\[email protected]('/')\ndef home():\n return render_template('home.html')\n\[email protected]('/enternew')\ndef new_student():\n return render_template('student.html')\n\[email protected]('/addrec',methods = ['POST', 'GET'])\ndef addrec():\n if request.method == 'POST':\n try:\n nm = request.form['nm']\n addr = request.form['add']\n city = request.form['city']\n pin = request.form['pin']\n \n with sql.connect(\"database.db\") as con:\n cur = con.cursor()\n \n cur.execute(\"INSERT INTO students (name,addr,city,pin) \n VALUES (?,?,?,?)\",(nm,addr,city,pin) )\n \n con.commit()\n msg = \"Record successfully added\"\n except:\n con.rollback()\n msg = \"error in insert operation\"\n \n finally:\n return render_template(\"result.html\",msg = msg)\n con.close()\n\[email protected]('/list')\ndef list():\n con = sql.connect(\"database.db\")\n con.row_factory = sql.Row\n \n cur = con.cursor()\n cur.execute(\"select * from students\")\n \n rows = cur.fetchall();\n return render_template(\"list.html\",rows = rows)\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 55605, "s": 55444, "text": "Run this script from Python shell and as the development server starts running. Visit http://localhost:5000/ in browser which displays a simple menu like this −" }, { "code": null, "e": 55671, "s": 55605, "text": "Click ‘Add New Record’ link to open the Student Information Form." }, { "code": null, "e": 55773, "s": 55671, "text": "Fill the form fields and submit it. The underlying function inserts the record in the students table." }, { "code": null, "e": 55879, "s": 55773, "text": "Go back to the home page and click ‘Show List’ link. The table showing the sample data will be displayed." }, { "code": null, "e": 56209, "s": 55879, "text": "Using raw SQL in Flask web applications to perform CRUD operations on database can be tedious. Instead, SQLAlchemy, a Python toolkit is a powerful OR Mapper that gives application developers the full power and flexibility of SQL. Flask-SQLAlchemy is the Flask extension that adds support for SQLAlchemy to your Flask application." }, { "code": null, "e": 56248, "s": 56209, "text": "What is ORM (Object Relation Mapping)?" }, { "code": null, "e": 56574, "s": 56248, "text": "Most programming language platforms are object oriented. Data in RDBMS servers on the other hand is stored as tables. Object relation mapping is a technique of mapping object parameters to the underlying RDBMS table structure. An ORM API provides methods to perform CRUD operations without having to write raw SQL statements." }, { "code": null, "e": 56687, "s": 56574, "text": "In this section, we are going to study the ORM techniques of Flask-SQLAlchemy and build a small web application." }, { "code": null, "e": 56732, "s": 56687, "text": "Step 1 − Install Flask-SQLAlchemy extension." }, { "code": null, "e": 56762, "s": 56732, "text": "pip install flask-sqlalchemy\n" }, { "code": null, "e": 56825, "s": 56762, "text": "Step 2 − You need to import SQLAlchemy class from this module." }, { "code": null, "e": 56866, "s": 56825, "text": "from flask_sqlalchemy import SQLAlchemy\n" }, { "code": null, "e": 56954, "s": 56866, "text": "Step 3 − Now create a Flask application object and set URI for the database to be used." }, { "code": null, "e": 57045, "s": 56954, "text": "app = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'" }, { "code": null, "e": 57331, "s": 57045, "text": "Step 4 − Then create an object of SQLAlchemy class with application object as the parameter. This object contains helper functions for ORM operations. It also provides a parent Model class using which user defined models are declared. In the snippet below, a students model is created." }, { "code": null, "e": 57706, "s": 57331, "text": "db = SQLAlchemy(app)\nclass students(db.Model):\n id = db.Column('student_id', db.Integer, primary_key = True)\n name = db.Column(db.String(100))\n city = db.Column(db.String(50)) \n addr = db.Column(db.String(200))\n pin = db.Column(db.String(10))\n\ndef __init__(self, name, city, addr,pin):\n self.name = name\n self.city = city\n self.addr = addr\n self.pin = pin" }, { "code": null, "e": 57787, "s": 57706, "text": "Step 5 − To create / use database mentioned in URI, run the create_all() method." }, { "code": null, "e": 57804, "s": 57787, "text": "db.create_all()\n" }, { "code": null, "e": 57887, "s": 57804, "text": "The Session object of SQLAlchemy manages all persistence operations of ORM object." }, { "code": null, "e": 57943, "s": 57887, "text": "The following session methods perform CRUD operations −" }, { "code": null, "e": 58009, "s": 57943, "text": "db.session.add(model object) − inserts a record into mapped table" }, { "code": null, "e": 58075, "s": 58009, "text": "db.session.add(model object) − inserts a record into mapped table" }, { "code": null, "e": 58135, "s": 58075, "text": "db.session.delete(model object) − deletes record from table" }, { "code": null, "e": 58195, "s": 58135, "text": "db.session.delete(model object) − deletes record from table" }, { "code": null, "e": 58281, "s": 58195, "text": "model.query.all() − retrieves all records from table (corresponding to SELECT query)." }, { "code": null, "e": 58367, "s": 58281, "text": "model.query.all() − retrieves all records from table (corresponding to SELECT query)." }, { "code": null, "e": 58561, "s": 58367, "text": "You can apply a filter to the retrieved record set by using the filter attribute. For instance, in order to retrieve records with city = ’Hyderabad’ in students table, use following statement −" }, { "code": null, "e": 58613, "s": 58561, "text": "Students.query.filter_by(city = ’Hyderabad’).all()\n" }, { "code": null, "e": 58722, "s": 58613, "text": "With this much of background, now we shall provide view functions for our application to add a student data." }, { "code": null, "e": 58951, "s": 58722, "text": "The entry point of the application is show_all() function bound to ‘/’ URL. The Record set of students table is sent as parameter to the HTML template. The Server side code in the template renders the records in HTML table form." }, { "code": null, "e": 59060, "s": 58951, "text": "@app.route('/')\ndef show_all():\n return render_template('show_all.html', students = students.query.all() )" }, { "code": null, "e": 59125, "s": 59060, "text": "The HTML script of the template (‘show_all.html’) is like this −" }, { "code": null, "e": 60081, "s": 59125, "text": "<!DOCTYPE html>\n<html lang = \"en\">\n <head></head>\n <body>\n <h3>\n <a href = \"{{ url_for('show_all') }}\">Comments - Flask \n SQLAlchemy example</a>\n </h3>\n \n <hr/>\n {%- for message in get_flashed_messages() %}\n {{ message }}\n {%- endfor %}\n\t\t\n <h3>Students (<a href = \"{{ url_for('new') }}\">Add Student\n </a>)</h3>\n \n <table>\n <thead>\n <tr>\n <th>Name</th>\n <th>City</th>\n <th>Address</th>\n <th>Pin</th>\n </tr>\n </thead>\n\n <tbody>\n {% for student in students %}\n <tr>\n <td>{{ student.name }}</td>\n <td>{{ student.city }}</td>\n <td>{{ student.addr }}</td>\n <td>{{ student.pin }}</td>\n </tr>\n {% endfor %}\n </tbody>\n </table>\n </body>\n</html>" }, { "code": null, "e": 60257, "s": 60081, "text": "The above page contains a hyperlink to ‘/new’ URL mapping new() function. When clicked, it opens a Student Information form. The data is posted to the same URL in POST method." }, { "code": null, "e": 61168, "s": 60257, "text": "<!DOCTYPE html>\n<html>\n <body>\n <h3>Students - Flask SQLAlchemy example</h3>\n <hr/>\n \n {%- for category, message in get_flashed_messages(with_categories = true) %}\n <div class = \"alert alert-danger\">\n {{ message }}\n </div>\n {%- endfor %}\n \n <form action = \"{{ request.path }}\" method = \"post\">\n <label for = \"name\">Name</label><br>\n <input type = \"text\" name = \"name\" placeholder = \"Name\" /><br>\n <label for = \"email\">City</label><br>\n <input type = \"text\" name = \"city\" placeholder = \"city\" /><br>\n <label for = \"addr\">addr</label><br>\n <textarea name = \"addr\" placeholder = \"addr\"></textarea><br>\n <label for = \"PIN\">City</label><br>\n <input type = \"text\" name = \"pin\" placeholder = \"pin\" /><br>\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>" }, { "code": null, "e": 61319, "s": 61168, "text": "When the http method is detected as POST, the form data is added in the students table and the application returns to homepage showing the added data." }, { "code": null, "e": 61907, "s": 61319, "text": "@app.route('/new', methods = ['GET', 'POST'])\ndef new():\n if request.method == 'POST':\n if not request.form['name'] or not request.form['city'] or not request.form['addr']:\n flash('Please enter all the fields', 'error')\n else:\n student = students(request.form['name'], request.form['city'],\n request.form['addr'], request.form['pin'])\n \n db.session.add(student)\n db.session.commit()\n \n flash('Record was successfully added')\n return redirect(url_for('show_all'))\n return render_template('new.html')" }, { "code": null, "e": 61965, "s": 61907, "text": "Given below is the complete code of application (app.py)." }, { "code": null, "e": 63353, "s": 61965, "text": "from flask import Flask, request, flash, url_for, redirect, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'\napp.config['SECRET_KEY'] = \"random string\"\n\ndb = SQLAlchemy(app)\n\nclass students(db.Model):\n id = db.Column('student_id', db.Integer, primary_key = True)\n name = db.Column(db.String(100))\n city = db.Column(db.String(50))\n addr = db.Column(db.String(200)) \n pin = db.Column(db.String(10))\n\ndef __init__(self, name, city, addr,pin):\n self.name = name\n self.city = city\n self.addr = addr\n self.pin = pin\n\[email protected]('/')\ndef show_all():\n return render_template('show_all.html', students = students.query.all() )\n\[email protected]('/new', methods = ['GET', 'POST'])\ndef new():\n if request.method == 'POST':\n if not request.form['name'] or not request.form['city'] or not request.form['addr']:\n flash('Please enter all the fields', 'error')\n else:\n student = students(request.form['name'], request.form['city'],\n request.form['addr'], request.form['pin'])\n \n db.session.add(student)\n db.session.commit()\n flash('Record was successfully added')\n return redirect(url_for('show_all'))\n return render_template('new.html')\n\nif __name__ == '__main__':\n db.create_all()\n app.run(debug = True)" }, { "code": null, "e": 63435, "s": 63353, "text": "Run the script from Python shell and enter http://localhost:5000/ in the browser." }, { "code": null, "e": 63498, "s": 63435, "text": "Click the ‘Add Student’ link to open Student information form." }, { "code": null, "e": 63573, "s": 63498, "text": "Fill the form and submit. The home page reappears with the submitted data." }, { "code": null, "e": 63611, "s": 63573, "text": "We can see the output as shown below." }, { "code": null, "e": 63779, "s": 63611, "text": "Sijax stands for ‘Simple Ajax’ and it is a Python/jQuery library designed to help you easily bring Ajax to your application. It uses jQuery.ajax to make AJAX requests." }, { "code": null, "e": 63816, "s": 63779, "text": "Installation of Flask-Sijax is easy." }, { "code": null, "e": 63841, "s": 63816, "text": "pip install flask-sijax\n" }, { "code": null, "e": 64030, "s": 63841, "text": "SIJAX_STATIC_PATH − the static path where you want the Sijax javascript files to be mirrored. The default location is static/js/sijax. In this folder, sijax.js and json2.js files are kept." }, { "code": null, "e": 64219, "s": 64030, "text": "SIJAX_STATIC_PATH − the static path where you want the Sijax javascript files to be mirrored. The default location is static/js/sijax. In this folder, sijax.js and json2.js files are kept." }, { "code": null, "e": 64282, "s": 64219, "text": "SIJAX_JSON_URI − the URI to load the json2.js static file from" }, { "code": null, "e": 64345, "s": 64282, "text": "SIJAX_JSON_URI − the URI to load the json2.js static file from" }, { "code": null, "e": 64524, "s": 64345, "text": "Sijax uses JSON to pass the data between the browser and the server. This means that the browsers need either to support JSON natively or get JSON support from the json2.js file." }, { "code": null, "e": 64685, "s": 64524, "text": "Functions registered that way cannot provide Sijax functionality, because they cannot be accessed using a POST method by default (and Sijax uses POST requests)." }, { "code": null, "e": 64884, "s": 64685, "text": "To make a View function capable of handling Sijax requests, make it accessible via POST using @app.route('/url', methods = ['GET', 'POST']) or use the @flask_sijax.route helper decorator like this −" }, { "code": null, "e": 64919, "s": 64884, "text": "@flask_sijax.route(app, '/hello')\n" }, { "code": null, "e": 65148, "s": 64919, "text": "Every Sijax handler function (like this one) receives at least one parameter automatically, much like Python passes ‘self’ to the object methods. The ‘obj_response’ parameter is the function's way of talking back to the browser." }, { "code": null, "e": 65209, "s": 65148, "text": "def say_hi(obj_response):\n obj_response.alert('Hi there!')" }, { "code": null, "e": 65270, "s": 65209, "text": "When Sijax request is detected, Sijax handles it like this −" }, { "code": null, "e": 65350, "s": 65270, "text": "g.sijax.register_callback('say_hi', say_hi)\n return g.sijax.process_request()" }, { "code": null, "e": 65402, "s": 65350, "text": "A minimal Sijax application code looks as follows −" }, { "code": null, "e": 66128, "s": 65402, "text": "import os\nfrom flask import Flask, g\nfrom flask_sijax import sijax\n\npath = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')\napp = Flask(__name__)\n\napp.config['SIJAX_STATIC_PATH'] = path\napp.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js'\nflask_sijax.Sijax(app)\n\[email protected]('/')\ndef index():\n return 'Index'\n\t\n@flask_sijax.route(app, '/hello')\ndef hello():\n def say_hi(obj_response):\n obj_response.alert('Hi there!')\n if g.sijax.is_sijax_request:\n # Sijax request detected - let Sijax handle it\n g.sijax.register_callback('say_hi', say_hi)\n return g.sijax.process_request()\n return _render_template('sijaxexample.html')\n\nif __name__ == '__main__':\n app.run(debug = True)" }, { "code": null, "e": 66317, "s": 66128, "text": "When a Sijax requests (a special jQuery.ajax() request) to the server, this request is detected on the server by g.sijax.is_sijax_request(), in which case you let Sijax handle the request." }, { "code": null, "e": 66422, "s": 66317, "text": "All the functions registered using g.sijax.register_callback() are exposed for calling from the browser." }, { "code": null, "e": 66568, "s": 66422, "text": "Calling g.sijax.process_request() tells Sijax to execute the appropriate (previously registered) function and return the response to the browser." }, { "code": null, "e": 66803, "s": 66568, "text": "A Flask application on the development server is accessible only on the computer on which the development environment is set up. This is a default behavior, because in debugging mode, a user can execute arbitrary code on the computer." }, { "code": null, "e": 66951, "s": 66803, "text": "If debug is disabled, the development server on local computer can be made available to the users on network by setting the host name as ‘0.0.0.0’." }, { "code": null, "e": 66978, "s": 66951, "text": "app.run(host = ’0.0.0.0’)\n" }, { "code": null, "e": 67036, "s": 66978, "text": "Thereby, your operating system listens to all public IPs." }, { "code": null, "e": 67285, "s": 67036, "text": "To switch over from a development environment to a full-fledged production environment, an application needs to be deployed on a real web server. Depending upon what you have, there are different options available to deploy a Flask web application." }, { "code": null, "e": 67432, "s": 67285, "text": "For small application, you can consider deploying it on any of the following hosted platforms, all of which offer free plan for small application." }, { "code": null, "e": 67439, "s": 67432, "text": "Heroku" }, { "code": null, "e": 67448, "s": 67439, "text": "dotcloud" }, { "code": null, "e": 67459, "s": 67448, "text": "webfaction" }, { "code": null, "e": 67711, "s": 67459, "text": "Flask application can be deployed on these cloud platforms. In addition, it is possible to deploy Flask app on Google cloud platform. Localtunnel service allows you to share your application on localhost without messing with DNS and firewall settings." }, { "code": null, "e": 67847, "s": 67711, "text": "If you are inclined to use a dedicated web server in place of above mentioned shared platforms, following options are there to explore." }, { "code": null, "e": 67977, "s": 67847, "text": "mod_wsgi is an Apache module that provides a WSGI compliant interface for hosting Python based web applications on Apache server." }, { "code": null, "e": 68040, "s": 67977, "text": "To install an official release direct from PyPi, you can run −" }, { "code": null, "e": 68062, "s": 68040, "text": "pip install mod_wsgi\n" }, { "code": null, "e": 68174, "s": 68062, "text": "To verify that the installation was successful, run the mod_wsgi-express script with the start-server command −" }, { "code": null, "e": 68205, "s": 68174, "text": "mod_wsgi-express start-server\n" }, { "code": null, "e": 68333, "s": 68205, "text": "This will start up Apache/mod_wsgi on port 8000. You can then verify that the installation worked by pointing your browser at −" }, { "code": null, "e": 68357, "s": 68333, "text": "http://localhost:8000/\n" }, { "code": null, "e": 68562, "s": 68357, "text": "There should be a yourapplication.wsgi file. This file contains the code mod_wsgi, which executes on startup to get the application object. For most applications, the following file should be sufficient −" }, { "code": null, "e": 68610, "s": 68562, "text": "from yourapplication import app as application\n" }, { "code": null, "e": 68708, "s": 68610, "text": "Make sure that yourapplication and all the libraries that are in use are on the python load path." }, { "code": null, "e": 68769, "s": 68708, "text": "You need to tell mod_wsgi, the location of your application." }, { "code": null, "e": 68959, "s": 68769, "text": "<VirtualHost *>\n ServerName example.com\n WSGIScriptAlias / C:\\yourdir\\yourapp.wsgi\n\n <Directory C:\\yourdir>\n Order deny,allow\n Allow from all\n </Directory>\n\n</VirtualHost>" }, { "code": null, "e": 69056, "s": 68959, "text": "There are many popular servers written in Python that contains WSGI applications and serve HTTP." }, { "code": null, "e": 69065, "s": 69056, "text": "Gunicorn" }, { "code": null, "e": 69073, "s": 69065, "text": "Tornado" }, { "code": null, "e": 69080, "s": 69073, "text": "Gevent" }, { "code": null, "e": 69092, "s": 69080, "text": "Twisted Web" }, { "code": null, "e": 69203, "s": 69092, "text": "FastCGI is another deployment option for Flask application on web servers like nginix, lighttpd, and Cherokee." }, { "code": null, "e": 69291, "s": 69203, "text": "First, you need to create the FastCGI server file. Let us call it yourapplication.fcgi." }, { "code": null, "e": 69416, "s": 69291, "text": "from flup.server.fcgi import WSGIServer\nfrom yourapplication import app\n\nif __name__ == '__main__':\n WSGIServer(app).run()" }, { "code": null, "e": 69608, "s": 69416, "text": "nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work, you need to pass the path to the socket to the WSGIServer." }, { "code": null, "e": 69675, "s": 69608, "text": "WSGIServer(application, bindAddress = '/path/to/fcgi.sock').run()\n" }, { "code": null, "e": 69910, "s": 69675, "text": "For a basic Apache deployment, your .fcgi file will appear in your application URL e.g. example.com/yourapplication.fcgi/hello/. There are few ways to configure your application so that yourapplication.fcgi does not appear in the URL." }, { "code": null, "e": 70015, "s": 69910, "text": "<VirtualHost *>\n ServerName example.com\n ScriptAlias / /path/to/yourapplication.fcgi/\n</VirtualHost>" }, { "code": null, "e": 70065, "s": 70015, "text": "Basic configuration of lighttpd looks like this −" }, { "code": null, "e": 70439, "s": 70065, "text": "fastcgi.server = (\"/yourapplication.fcgi\" => ((\n \"socket\" => \"/tmp/yourapplication-fcgi.sock\",\n \"bin-path\" => \"/var/www/yourapplication/yourapplication.fcgi\",\n \"check-local\" => \"disable\",\n \"max-procs\" => 1\n)))\n\nalias.url = (\n \"/static/\" => \"/path/to/your/static\"\n)\n\nurl.rewrite-once = (\n \"^(/static($|/.*))$\" => \"$1\",\n \"^(/.*)$\" => \"/yourapplication.fcgi$1\"\n)" }, { "code": null, "e": 70560, "s": 70439, "text": "Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication." }, { "code": null, "e": 70593, "s": 70560, "text": "\n 22 Lectures \n 6 hours \n" }, { "code": null, "e": 70609, "s": 70593, "text": " Malhar Lathkar" }, { "code": null, "e": 70644, "s": 70609, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 70655, "s": 70644, "text": " Jack Chan" }, { "code": null, "e": 70688, "s": 70655, "text": "\n 16 Lectures \n 4 hours \n" }, { "code": null, "e": 70704, "s": 70688, "text": " Malhar Lathkar" }, { "code": null, "e": 70737, "s": 70704, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 70754, "s": 70737, "text": " Srikanth Guskra" }, { "code": null, "e": 70789, "s": 70754, "text": "\n 88 Lectures \n 3.5 hours \n" }, { "code": null, "e": 70804, "s": 70789, "text": " Jorge Escobar" }, { "code": null, "e": 70838, "s": 70804, "text": "\n 80 Lectures \n 12 hours \n" }, { "code": null, "e": 70861, "s": 70838, "text": " Stone River ELearning" }, { "code": null, "e": 70868, "s": 70861, "text": " Print" }, { "code": null, "e": 70879, "s": 70868, "text": " Add Notes" } ]
Auto Grow a Textarea with JavaScript in CSS
Using JavaScript, we can set our Textarea element to automatically grow with its content The following examples illustrate how we can achieve the above scenario. Live Demo <!DOCTYPE html> <html> <head> <style> * { margin: 3%; color: navy; font-size: 1.2em; } #ta { padding: 2%; resize: none; width: 330px; min-height: 80px; overflow: hidden; box-sizing: border-box; } </style> </head> <body> <form> <label for="ta">Cool TextArea</label> <textarea id="ta"></textarea> </form> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#ta").on('input', function() { var scroll_height = $("#ta").get(0).scrollHeight; $("#ta").css('height', scroll_height + 'px'); }); </script> </body> </html> This will produce the following result − Live Demo <!DOCTYPE html> <html> <head> <style> div { margin: 3%; overflow-y: scroll; } #ta { padding: 2%; resize: none; width: 333px; min-height: 90px; overflow: hidden; box-sizing: border-box; font-size: 1.5em; } </style> </head> <body> <div> <textarea id="ta"></textarea> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#ta").on('input', function() { var scroll_height = $("#ta").get(0).scrollHeight; $("#ta").css('height', scroll_height + 'px'); }); </script> </body> </html> This will produce the following result −
[ { "code": null, "e": 1151, "s": 1062, "text": "Using JavaScript, we can set our Textarea element to automatically grow with its content" }, { "code": null, "e": 1224, "s": 1151, "text": "The following examples illustrate how we can achieve the above scenario." }, { "code": null, "e": 1235, "s": 1224, "text": " Live Demo" }, { "code": null, "e": 1808, "s": 1235, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n* {\n margin: 3%;\n color: navy;\n font-size: 1.2em;\n}\n#ta {\n padding: 2%;\n resize: none;\n width: 330px;\n min-height: 80px;\n overflow: hidden;\n box-sizing: border-box;\n}\n</style>\n</head>\n<body>\n<form>\n<label for=\"ta\">Cool TextArea</label>\n<textarea id=\"ta\"></textarea>\n</form>\n<script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"></script>\n<script>\n$(\"#ta\").on('input', function() {\n var scroll_height = $(\"#ta\").get(0).scrollHeight;\n $(\"#ta\").css('height', scroll_height + 'px');\n});\n</script>\n</body>\n</html>" }, { "code": null, "e": 1849, "s": 1808, "text": "This will produce the following result −" }, { "code": null, "e": 1860, "s": 1849, "text": " Live Demo" }, { "code": null, "e": 2402, "s": 1860, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n margin: 3%;\n overflow-y: scroll;\n}\n#ta {\n padding: 2%;\n resize: none;\n width: 333px;\n min-height: 90px;\n overflow: hidden;\n box-sizing: border-box;\n font-size: 1.5em;\n}\n</style>\n</head>\n<body>\n<div>\n<textarea id=\"ta\"></textarea>\n</div>\n<script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"></script>\n<script>\n$(\"#ta\").on('input', function() {\n var scroll_height = $(\"#ta\").get(0).scrollHeight;\n $(\"#ta\").css('height', scroll_height + 'px');\n});\n</script>\n</body>\n</html>" }, { "code": null, "e": 2443, "s": 2402, "text": "This will produce the following result −" } ]
Pairs with specific difference | Practice | GeeksforGeeks
Given an array of integers, arr[] and a number, K.You can pair two numbers of the array if the difference between them is strictly less than K. The task is to find the maximum possible sum of such disjoint pairs (i.e., each element of the array can be used at most once). The Sum of P pairs is the sum of all 2P elements of pairs. Example 1: Input : arr[] = {3, 5, 10, 15, 17, 12, 9} K = 4 Output : 62 Explanation : Then disjoint pairs with difference less than K are, (3, 5), (10, 12), (15, 17) max sum which we can get is 3 + 5 + 10 + 12 + 15 + 17 = 62 Note that an alternate way to form disjoint pairs is,(3, 5), (9, 12), (15, 17) but this pairing produces less sum. Example 2: Input : arr[] = {5, 15, 10, 300} K = 12 Output : 25 Your Task: You don't need to read, input, or print anything. Your task is to complete the function maxSumPairWithDifferenceLessThanK() which takes the array arr[], its size N, and an integer K as inputs and returns the maximum possible sum of disjoint pairs. Expected Time Complexity: O(N. log(N)) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 105 0 ≤ K ≤ 105 1 ≤ arr[i] ≤ 104 0 2021aspire041 day ago class Solution{ int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { Arrays.sort(arr); int i=N-1; int sum=0; while(i>=1) { if((arr[i]-arr[i-1])<K) { sum=sum+arr[i]+arr[i-1]; i=i-2; } else i--; } return sum; }}; 0 milindprajapatmst192 weeks ago class Solution{ public: int maxSumPairWithDifferenceLessThanK(int arr[], int n, int k) { sort(arr, arr + n, [](int& x, int & y) { return x > y; }); int _sum = 0, index = 1; while (index < n) { if (arr[index - 1] - arr[index] < k) { _sum += arr[index - 1] + arr[index]; index++; } index++; } return _sum; } }; 0 hsnagb201 month ago Solution with Space Complexity=O(1) and Time Complexity=O(N log N) class Solution{ public: int maxSumPairWithDifferenceLessThanK(int arr[], int n, int k){ sort(arr,arr+n); int sum=0; for(int i=n-1;i>0;i--){ if(abs(arr[i]-arr[i-1])<k){ sum=sum+arr[i]+arr[i-1]; i--; } } return sum; }}; +1 bhargav_412 months ago Java Solution class Solution { public static void swap(int[] arr,int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void reverse(int[] arr){ int i=0,j=arr.length-1; while(i<j){ swap(arr,i,j); i++; j--; } } public static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { Arrays.sort(arr); reverse(arr); int sum = 0; int i=0; while(i<N){ if(i==N-1) break; int pairDifference = arr[i]-arr[i+1]; if(pairDifference<K){ sum += arr[i] + arr[i+1]; i+=2; }else i++; } return sum; } } 0 uttarandas5012 months ago int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { // Your code goes here sort(arr, arr+N, greater<int>()); int i, sum=0; for(i=0; i<N-1; i++){ if(arr[i]-arr[i+1] < K){sum += (arr[i]+arr[i+1]); i++;} } return sum; } 0 ritikkhandelwal083 months ago Java Solution!!! Execution time: 0.1 / 2.5 class Solution { public static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K){ Arrays.sort(arr); int sum=0; for(int i=N-1; i>0;){ if(arr[i]-arr[i-1] < K){ sum+=arr[i]+arr[i-1]; i=i-2; } else{ i--; } } return sum; } } +1 decostarsharma1133 months ago WORKING SOLUTION WITH O(1) SPACE COMPLEXITY class Solution { public static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { // Your code goes here Arrays.sort(arr); int i = N - 1 ; int sum = 0 ; while( i >= 1) { if( arr[i] - arr[i-1] < K ) { sum = sum + arr[i] + arr[i-1]; i = i - 2 ; }else { i--; } } return sum ; } } 0 ilihaspatel443 months ago int maxSumPairWithDifferenceLessThanK(int arr[], int N, int k) { sort(arr,arr+N); int sum=0; for(int j=N-1;j>0;){ if(arr[j]-arr[j-1]<k ){ sum+=arr[j-1]+arr[j]; // cout<<arr[j]<<" "<<arr[j-1]<<"|| "; j=j-2; } else{ j--; } } return sum; } 0 swarnavo094 months ago C++ Code int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { sort(arr, arr+N); int sum = 0; int i = N-1; while(i>0){ if((arr[i]-arr[i-1])<K) { sum += arr[i] + arr[i-1]; i = i-2; } else i--; } return sum; // Your code goes here } 0 ankitkushawaha10004 months ago We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 569, "s": 238, "text": "Given an array of integers, arr[] and a number, K.You can pair two numbers of the array if the difference between them is strictly less than K. The task is to find the maximum possible sum of such disjoint pairs (i.e., each element of the array can be used at most once). The Sum of P pairs is the sum of all 2P elements of pairs." }, { "code": null, "e": 582, "s": 571, "text": "Example 1:" }, { "code": null, "e": 915, "s": 582, "text": "Input : \narr[] = {3, 5, 10, 15, 17, 12, 9}\nK = 4\nOutput : \n62\nExplanation :\nThen disjoint pairs with difference less\nthan K are, (3, 5), (10, 12), (15, 17)\nmax sum which we can get is \n3 + 5 + 10 + 12 + 15 + 17 = 62\nNote that an alternate way to form \ndisjoint pairs is,(3, 5), (9, 12), (15, 17)\nbut this pairing produces less sum." }, { "code": null, "e": 928, "s": 917, "text": "Example 2:" }, { "code": null, "e": 984, "s": 928, "text": "Input : \narr[] = {5, 15, 10, 300}\nK = 12\nOutput : \n25\n" }, { "code": null, "e": 1247, "s": 986, "text": "Your Task: \nYou don't need to read, input, or print anything. Your task is to complete the function maxSumPairWithDifferenceLessThanK() which takes the array arr[], its size N, and an integer K as inputs and returns the maximum possible sum of disjoint pairs." }, { "code": null, "e": 1319, "s": 1249, "text": "Expected Time Complexity: O(N. log(N))\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1375, "s": 1321, "text": "Constraints:\n1 ≤ N ≤ 105\n0 ≤ K ≤ 105\n1 ≤ arr[i] ≤ 104" }, { "code": null, "e": 1377, "s": 1375, "text": "0" }, { "code": null, "e": 1399, "s": 1377, "text": "2021aspire041 day ago" }, { "code": null, "e": 1732, "s": 1399, "text": "class Solution{ int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { Arrays.sort(arr); int i=N-1; int sum=0; while(i>=1) { if((arr[i]-arr[i-1])<K) { sum=sum+arr[i]+arr[i-1]; i=i-2; } else i--; } return sum; }};" }, { "code": null, "e": 1734, "s": 1732, "text": "0" }, { "code": null, "e": 1765, "s": 1734, "text": "milindprajapatmst192 weeks ago" }, { "code": null, "e": 2190, "s": 1765, "text": "class Solution{\npublic:\n int maxSumPairWithDifferenceLessThanK(int arr[], int n, int k) {\n sort(arr, arr + n, [](int& x, int & y) { return x > y; });\n int _sum = 0, index = 1;\n while (index < n) {\n if (arr[index - 1] - arr[index] < k) {\n _sum += arr[index - 1] + arr[index];\n index++;\n }\n index++;\n }\n return _sum;\n }\n};" }, { "code": null, "e": 2192, "s": 2190, "text": "0" }, { "code": null, "e": 2212, "s": 2192, "text": "hsnagb201 month ago" }, { "code": null, "e": 2279, "s": 2212, "text": "Solution with Space Complexity=O(1) and Time Complexity=O(N log N)" }, { "code": null, "e": 2581, "s": 2279, "text": "class Solution{ public: int maxSumPairWithDifferenceLessThanK(int arr[], int n, int k){ sort(arr,arr+n); int sum=0; for(int i=n-1;i>0;i--){ if(abs(arr[i]-arr[i-1])<k){ sum=sum+arr[i]+arr[i-1]; i--; } } return sum; }};" }, { "code": null, "e": 2584, "s": 2581, "text": "+1" }, { "code": null, "e": 2607, "s": 2584, "text": "bhargav_412 months ago" }, { "code": null, "e": 2622, "s": 2607, "text": "Java Solution " }, { "code": null, "e": 3375, "s": 2624, "text": "class Solution { \n public static void swap(int[] arr,int i, int j){\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n public static void reverse(int[] arr){\n int i=0,j=arr.length-1;\n while(i<j){\n swap(arr,i,j);\n i++;\n j--;\n }\n }\n public static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) \n {\n Arrays.sort(arr);\n reverse(arr);\n int sum = 0;\n int i=0;\n while(i<N){\n if(i==N-1) break;\n int pairDifference = arr[i]-arr[i+1];\n if(pairDifference<K){\n sum += arr[i] + arr[i+1];\n i+=2;\n }else i++;\n }\n return sum;\n }\n \n}" }, { "code": null, "e": 3377, "s": 3375, "text": "0" }, { "code": null, "e": 3403, "s": 3377, "text": "uttarandas5012 months ago" }, { "code": null, "e": 3713, "s": 3403, "text": "int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K)\n {\n // Your code goes here \n sort(arr, arr+N, greater<int>());\n int i, sum=0;\n \n for(i=0; i<N-1; i++){\n if(arr[i]-arr[i+1] < K){sum += (arr[i]+arr[i+1]); i++;}\n }\n return sum;\n }" }, { "code": null, "e": 3715, "s": 3713, "text": "0" }, { "code": null, "e": 3745, "s": 3715, "text": "ritikkhandelwal083 months ago" }, { "code": null, "e": 3762, "s": 3745, "text": "Java Solution!!!" }, { "code": null, "e": 3788, "s": 3762, "text": "Execution time: 0.1 / 2.5" }, { "code": null, "e": 4168, "s": 3790, "text": "class Solution { \n public static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K){\n Arrays.sort(arr);\n int sum=0;\n for(int i=N-1; i>0;){\n if(arr[i]-arr[i-1] < K){\n sum+=arr[i]+arr[i-1];\n i=i-2;\n }\n else{\n i--;\n }\n }\n return sum;\n }\n}" }, { "code": null, "e": 4171, "s": 4168, "text": "+1" }, { "code": null, "e": 4201, "s": 4171, "text": "decostarsharma1133 months ago" }, { "code": null, "e": 4246, "s": 4201, "text": "WORKING SOLUTION WITH O(1) SPACE COMPLEXITY " }, { "code": null, "e": 4696, "s": 4246, "text": "class Solution { public static int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { // Your code goes here Arrays.sort(arr); int i = N - 1 ; int sum = 0 ; while( i >= 1) { if( arr[i] - arr[i-1] < K ) { sum = sum + arr[i] + arr[i-1]; i = i - 2 ; }else { i--; } } return sum ; } }" }, { "code": null, "e": 4698, "s": 4696, "text": "0" }, { "code": null, "e": 4724, "s": 4698, "text": "ilihaspatel443 months ago" }, { "code": null, "e": 5133, "s": 4724, "text": "int maxSumPairWithDifferenceLessThanK(int arr[], int N, int k) { sort(arr,arr+N); int sum=0; for(int j=N-1;j>0;){ if(arr[j]-arr[j-1]<k ){ sum+=arr[j-1]+arr[j]; // cout<<arr[j]<<\" \"<<arr[j-1]<<\"|| \"; j=j-2; } else{ j--; } } return sum; }" }, { "code": null, "e": 5135, "s": 5133, "text": "0" }, { "code": null, "e": 5158, "s": 5135, "text": "swarnavo094 months ago" }, { "code": null, "e": 5167, "s": 5158, "text": "C++ Code" }, { "code": null, "e": 5531, "s": 5167, "text": "int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K) { sort(arr, arr+N); int sum = 0; int i = N-1; while(i>0){ if((arr[i]-arr[i-1])<K) { sum += arr[i] + arr[i-1]; i = i-2; } else i--; } return sum; // Your code goes here }" }, { "code": null, "e": 5533, "s": 5531, "text": "0" }, { "code": null, "e": 5564, "s": 5533, "text": "ankitkushawaha10004 months ago" }, { "code": null, "e": 5710, "s": 5564, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5746, "s": 5710, "text": " Login to access your submissions. " }, { "code": null, "e": 5756, "s": 5746, "text": "\nProblem\n" }, { "code": null, "e": 5766, "s": 5756, "text": "\nContest\n" }, { "code": null, "e": 5829, "s": 5766, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5977, "s": 5829, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6185, "s": 5977, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6291, "s": 6185, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Dart - Recursion - GeeksforGeeks
12 Mar, 2021 Recursion in any programming language means a function making a call to itself. It is used to solve large complex problems by breaking them into smaller subproblems. Dart also implements recursion similarly. In a recursive function, the function calls itself repeatedly until a base condition is reached. The function basically has two parts. Recursive: The recursive part is called again and again with a smaller subproblem. Base: The base condition is checked every time a function call is made. If the function is in a base condition it is used to provide a solution. Recursion uses a stack to store the values/ result of the subproblems to be later returned to the main problem. For an in-depth review of recursion visit: https://www.geeksforgeeks.org/recursion/ Syntax: void gfgRec() { // Base code.... gfgRec(); // Some code... } void main() { gfgRec(); } Example: We will be using a program for the nth Fibonacci number to demonstrate recursion in dart – Dart int Fib(int n){ if(n<=1) //Base Condition return n; return Fib(n-1)+Fib(n-2);} void main() { print(Fib(6));} Output: 8 Explanation: From the figure, we can see that the call to the function with n = 6 as a parameter, in turn, calls itself with smaller values 5 and 4. They themselves call the function with the smaller values until it reaches the base condition. When the base condition is met the function start returning the values. So the final result comes out to be 8 which is the sum of the call to 5 and 4. In the case of Recursion, the problem needs to get smaller with every new function call as the problem has to get terminated to return a result. This condition is called as Termination condition in Recursion. In case the problem does not terminate it can lead to an infinite loop and as we can see that these function call uses stack memory to store the temporary values they may use a lot of memory. If the base condition is not defined or is unable to reach then the function can cause a stack overflow. Some advantages and disadvantages of using recursion The problem solution using recursion is very concise and short. They are readily used with problems related to trees and graphs. Reduces the time complexity of problems. Reduces unnecessary function calling. The problem uses a lot of space. Logic can be complex to understand. When stuck it is hard to debug. Now we will be using another example to get a better understanding of its implementation in dart. Example: We will be writing a program to find the factorial of a number using recursion. Dart int Fact(int n){ if(n<=1) //Base Condition return 1; return n*Fact(n-1);} void main() { print(Fact(8));} Output: 40320 Explanation: From the figure, we can infer that the Fact function calls itself until the base condition is reached i.e. we returned the function with a multiplication of value ‘n’ with the value of a function with value ‘n-1’ until the value of n becomes equals to 1. At last, we return the value of the desired function. Dart Methods Picked Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget What is widgets in Flutter? Android Studio Setup for Flutter Development Flutter - BorderRadius Widget Format Dates in Flutter Flutter - Positioned Widget Flutter - Dialogs
[ { "code": null, "e": 24010, "s": 23982, "text": "\n12 Mar, 2021" }, { "code": null, "e": 24218, "s": 24010, "text": "Recursion in any programming language means a function making a call to itself. It is used to solve large complex problems by breaking them into smaller subproblems. Dart also implements recursion similarly." }, { "code": null, "e": 24353, "s": 24218, "text": "In a recursive function, the function calls itself repeatedly until a base condition is reached. The function basically has two parts." }, { "code": null, "e": 24436, "s": 24353, "text": "Recursive: The recursive part is called again and again with a smaller subproblem." }, { "code": null, "e": 24581, "s": 24436, "text": "Base: The base condition is checked every time a function call is made. If the function is in a base condition it is used to provide a solution." }, { "code": null, "e": 24694, "s": 24581, "text": "Recursion uses a stack to store the values/ result of the subproblems to be later returned to the main problem. " }, { "code": null, "e": 24778, "s": 24694, "text": "For an in-depth review of recursion visit: https://www.geeksforgeeks.org/recursion/" }, { "code": null, "e": 24786, "s": 24778, "text": "Syntax:" }, { "code": null, "e": 24893, "s": 24786, "text": "void gfgRec()\n{\n // Base code....\n\n gfgRec();\n\n // Some code...\n}\n\n\nvoid main()\n{\n gfgRec();\n}" }, { "code": null, "e": 24902, "s": 24893, "text": "Example:" }, { "code": null, "e": 24993, "s": 24902, "text": "We will be using a program for the nth Fibonacci number to demonstrate recursion in dart –" }, { "code": null, "e": 24998, "s": 24993, "text": "Dart" }, { "code": "int Fib(int n){ if(n<=1) //Base Condition return n; return Fib(n-1)+Fib(n-2);} void main() { print(Fib(6));}", "e": 25116, "s": 24998, "text": null }, { "code": null, "e": 25124, "s": 25116, "text": "Output:" }, { "code": null, "e": 25126, "s": 25124, "text": "8" }, { "code": null, "e": 25139, "s": 25126, "text": "Explanation:" }, { "code": null, "e": 25521, "s": 25139, "text": "From the figure, we can see that the call to the function with n = 6 as a parameter, in turn, calls itself with smaller values 5 and 4. They themselves call the function with the smaller values until it reaches the base condition. When the base condition is met the function start returning the values. So the final result comes out to be 8 which is the sum of the call to 5 and 4." }, { "code": null, "e": 26027, "s": 25521, "text": "In the case of Recursion, the problem needs to get smaller with every new function call as the problem has to get terminated to return a result. This condition is called as Termination condition in Recursion. In case the problem does not terminate it can lead to an infinite loop and as we can see that these function call uses stack memory to store the temporary values they may use a lot of memory. If the base condition is not defined or is unable to reach then the function can cause a stack overflow." }, { "code": null, "e": 26080, "s": 26027, "text": "Some advantages and disadvantages of using recursion" }, { "code": null, "e": 26144, "s": 26080, "text": "The problem solution using recursion is very concise and short." }, { "code": null, "e": 26209, "s": 26144, "text": "They are readily used with problems related to trees and graphs." }, { "code": null, "e": 26250, "s": 26209, "text": "Reduces the time complexity of problems." }, { "code": null, "e": 26288, "s": 26250, "text": "Reduces unnecessary function calling." }, { "code": null, "e": 26321, "s": 26288, "text": "The problem uses a lot of space." }, { "code": null, "e": 26357, "s": 26321, "text": "Logic can be complex to understand." }, { "code": null, "e": 26389, "s": 26357, "text": "When stuck it is hard to debug." }, { "code": null, "e": 26488, "s": 26389, "text": "Now we will be using another example to get a better understanding of its implementation in dart. " }, { "code": null, "e": 26497, "s": 26488, "text": "Example:" }, { "code": null, "e": 26577, "s": 26497, "text": "We will be writing a program to find the factorial of a number using recursion." }, { "code": null, "e": 26582, "s": 26577, "text": "Dart" }, { "code": "int Fact(int n){ if(n<=1) //Base Condition return 1; return n*Fact(n-1);} void main() { print(Fact(8));}", "e": 26696, "s": 26582, "text": null }, { "code": null, "e": 26704, "s": 26696, "text": "Output:" }, { "code": null, "e": 26710, "s": 26704, "text": "40320" }, { "code": null, "e": 26723, "s": 26710, "text": "Explanation:" }, { "code": null, "e": 27032, "s": 26723, "text": "From the figure, we can infer that the Fact function calls itself until the base condition is reached i.e. we returned the function with a multiplication of value ‘n’ with the value of a function with value ‘n-1’ until the value of n becomes equals to 1. At last, we return the value of the desired function." }, { "code": null, "e": 27045, "s": 27032, "text": "Dart Methods" }, { "code": null, "e": 27052, "s": 27045, "text": "Picked" }, { "code": null, "e": 27057, "s": 27052, "text": "Dart" }, { "code": null, "e": 27155, "s": 27057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27194, "s": 27155, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27220, "s": 27194, "text": "ListView Class in Flutter" }, { "code": null, "e": 27246, "s": 27220, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27269, "s": 27246, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27297, "s": 27269, "text": "What is widgets in Flutter?" }, { "code": null, "e": 27342, "s": 27297, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 27372, "s": 27342, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 27396, "s": 27372, "text": "Format Dates in Flutter" }, { "code": null, "e": 27424, "s": 27396, "text": "Flutter - Positioned Widget" } ]
Rust - Functions
Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Defining a function A function definition specifies what and how a specific task would be done. Calling or invoking a Function A function must be called so as to execute it. Returning Functions Functions may also return value along with control, back to the caller. Parameterized Function Parameters are a mechanism to pass values to functions. A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the fn keyword. The syntax for defining a standard function is given below fn function_name(param1,param2..paramN) { // function body } A function declaration can optionally contain parameters/arguments. Parameters are used to pass values to functions. //Defining a function fn fn_hello(){ println!("hello from function fn_hello "); } A function must be called so as to execute it. This process is termed as function invocation. Values for parameters should be passed when a function is invoked. The function that invokes another function is called the caller function. function_name(val1,val2,valN) fn main(){ //calling a function fn_hello(); } Here, the main() is the caller function. The following example defines a function fn_hello(). The function prints a message to the console. The main() function invokes the fn_hello() function. fn main(){ //calling a function fn_hello(); } //Defining a function fn fn_hello(){ println!("hello from function fn_hello "); } hello from function fn_hello Functions may also return a value along with control, back to the caller. Such functions are called returning functions. Either of the following syntax can be used to define a function with return type. // Syntax1 fn function_name() -> return_type { //statements return value; } //Syntax2 fn function_name() -> return_type { value //no semicolon means this value is returned } fn main(){ println!("pi value is {}",get_pi()); } fn get_pi()->f64 { 22.0/7.0 } pi value is 3.142857142857143 Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined. Parameters can be passed to a function using one of the following techniques − When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method have no effect on the argument. The following example declares a variable no, which is initially 5. The variable is passed as parameter (by value) to the mutate_no_to_zero()functionnction, which changes the value to zero. After the function call when control returns back to main method the value will be the same. fn main(){ let no:i32 = 5; mutate_no_to_zero(no); println!("The value of no is:{}",no); } fn mutate_no_to_zero(mut param_no: i32) { param_no = param_no*0; println!("param_no value is :{}",param_no); } Output param_no value is :0 The value of no is:5 When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. Parameter values can be passed by reference by prefixing the variable name with an & . In the example given below, we have a variable no, which is initially 5. A reference to the variable no is passed to the mutate_no_to_zero() function. The function operates on the original variable. After the function call, when control returns back to main method, the value of the original variable will be the zero. fn main() { let mut no:i32 = 5; mutate_no_to_zero(&mut no); println!("The value of no is:{}",no); } fn mutate_no_to_zero(param_no:&mut i32){ *param_no = 0; //de reference } The * operator is used to access value stored in the memory location that the variable param_no points to. This is also known as dereferencing. The output will be − The value of no is 0. The main() function passes a string object to the display() function. fn main(){ let name:String = String::from("TutorialsPoint"); display(name); //cannot access name after display } fn display(param_name:String){ println!("param_name value is :{}",param_name); } param_name value is :TutorialsPoint 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2087, "text": "Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code." }, { "code": null, "e": 2607, "s": 2447, "text": "A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function." }, { "code": null, "e": 2627, "s": 2607, "text": "Defining a function" }, { "code": null, "e": 2703, "s": 2627, "text": "A function definition specifies what and how a specific task would be done." }, { "code": null, "e": 2734, "s": 2703, "text": "Calling or invoking a Function" }, { "code": null, "e": 2781, "s": 2734, "text": "A function must be called so as to execute it." }, { "code": null, "e": 2801, "s": 2781, "text": "Returning Functions" }, { "code": null, "e": 2873, "s": 2801, "text": "Functions may also return value along with control, back to the caller." }, { "code": null, "e": 2896, "s": 2873, "text": "Parameterized Function" }, { "code": null, "e": 2952, "s": 2896, "text": "Parameters are a mechanism to pass values to functions." }, { "code": null, "e": 3316, "s": 2952, "text": "A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the fn keyword. The syntax for defining a standard function is given below" }, { "code": null, "e": 3381, "s": 3316, "text": "fn function_name(param1,param2..paramN) {\n // function body\n}\n" }, { "code": null, "e": 3498, "s": 3381, "text": "A function declaration can optionally contain parameters/arguments. Parameters are used to pass values to functions." }, { "code": null, "e": 3583, "s": 3498, "text": "//Defining a function\nfn fn_hello(){\n println!(\"hello from function fn_hello \");\n}" }, { "code": null, "e": 3818, "s": 3583, "text": "A function must be called so as to execute it. This process is termed as function invocation. Values for parameters should be passed when a function is invoked. The function that invokes another function is called the caller function." }, { "code": null, "e": 3849, "s": 3818, "text": "function_name(val1,val2,valN)\n" }, { "code": null, "e": 3901, "s": 3849, "text": "fn main(){\n //calling a function\n fn_hello();\n}" }, { "code": null, "e": 3942, "s": 3901, "text": "Here, the main() is the caller function." }, { "code": null, "e": 4094, "s": 3942, "text": "The following example defines a function fn_hello(). The function prints a message to the console. The main() function invokes the fn_hello() function." }, { "code": null, "e": 4231, "s": 4094, "text": "fn main(){\n //calling a function\n fn_hello();\n}\n//Defining a function\nfn fn_hello(){\n println!(\"hello from function fn_hello \");\n}" }, { "code": null, "e": 4261, "s": 4231, "text": "hello from function fn_hello\n" }, { "code": null, "e": 4382, "s": 4261, "text": "Functions may also return a value along with control, back to the caller. Such functions are called returning functions." }, { "code": null, "e": 4464, "s": 4382, "text": "Either of the following syntax can be used to define a function with return type." }, { "code": null, "e": 4547, "s": 4464, "text": "// Syntax1\nfn function_name() -> return_type {\n //statements\n return value;\n}\n" }, { "code": null, "e": 4649, "s": 4547, "text": "//Syntax2\nfn function_name() -> return_type {\n value //no semicolon means this value is returned\n}\n" }, { "code": null, "e": 4735, "s": 4649, "text": "fn main(){\n println!(\"pi value is {}\",get_pi());\n}\nfn get_pi()->f64 {\n 22.0/7.0\n}" }, { "code": null, "e": 4766, "s": 4735, "text": "pi value is 3.142857142857143\n" }, { "code": null, "e": 5061, "s": 4766, "text": "Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined." }, { "code": null, "e": 5140, "s": 5061, "text": "Parameters can be passed to a function using one of the following techniques −" }, { "code": null, "e": 5383, "s": 5140, "text": "When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method have no effect on the argument." }, { "code": null, "e": 5666, "s": 5383, "text": "The following example declares a variable no, which is initially 5. The variable is passed as parameter (by value) to the mutate_no_to_zero()functionnction, which changes the value to zero. After the function call when control returns back to main method the value will be the same." }, { "code": null, "e": 5883, "s": 5666, "text": "fn main(){\n let no:i32 = 5;\n mutate_no_to_zero(no);\n println!(\"The value of no is:{}\",no);\n}\n\nfn mutate_no_to_zero(mut param_no: i32) {\n param_no = param_no*0;\n println!(\"param_no value is :{}\",param_no);\n}" }, { "code": null, "e": 5890, "s": 5883, "text": "Output" }, { "code": null, "e": 5933, "s": 5890, "text": "param_no value is :0\nThe value of no is:5\n" }, { "code": null, "e": 6263, "s": 5933, "text": "When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. Parameter values can be passed by reference by prefixing the variable name with an & . " }, { "code": null, "e": 6582, "s": 6263, "text": "In the example given below, we have a variable no, which is initially 5. A reference to the variable no is passed to the mutate_no_to_zero() function. The function operates on the original variable. After the function call, when control returns back to main method, the value of the original variable will be the zero." }, { "code": null, "e": 6767, "s": 6582, "text": "fn main() {\n let mut no:i32 = 5;\n mutate_no_to_zero(&mut no);\n println!(\"The value of no is:{}\",no);\n}\nfn mutate_no_to_zero(param_no:&mut i32){\n *param_no = 0; //de reference\n}" }, { "code": null, "e": 6911, "s": 6767, "text": "The * operator is used to access value stored in the memory location that the variable param_no points to. This is also known as dereferencing." }, { "code": null, "e": 6932, "s": 6911, "text": "The output will be −" }, { "code": null, "e": 6955, "s": 6932, "text": "The value of no is 0.\n" }, { "code": null, "e": 7025, "s": 6955, "text": "The main() function passes a string object to the display() function." }, { "code": null, "e": 7232, "s": 7025, "text": "fn main(){\n let name:String = String::from(\"TutorialsPoint\");\n display(name); \n //cannot access name after display\n}\nfn display(param_name:String){\n println!(\"param_name value is :{}\",param_name);\n}" }, { "code": null, "e": 7269, "s": 7232, "text": "param_name value is :TutorialsPoint\n" }, { "code": null, "e": 7304, "s": 7269, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7327, "s": 7304, "text": " Stone River ELearning" }, { "code": null, "e": 7359, "s": 7327, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 7370, "s": 7359, "text": " Ken Burke" }, { "code": null, "e": 7377, "s": 7370, "text": " Print" }, { "code": null, "e": 7388, "s": 7377, "text": " Add Notes" } ]
Forward and Inverse Fourier Transform of an Image in MATLAB - GeeksforGeeks
28 Jan, 2022 In this article, we shall apply Fourier Transform on images. Fourier Transform is a mathematical technique that helps to transform Time Domain function x(t) to Frequency Domain function X(ω). In this article, we will see how to find Fourier Transform in MATLAB. Linearity: The addition of two functions corresponding to the addition of the two frequency spectrum is called linearity. If we multiply a function by a constant, the Fourier transform of the resultant function is multiplied by the same constant. The Fourier transform of the sum of two or more functions is the sum of the Fourier transforms of the functions. Scaling: Scaling is the method that is used to change the range of the independent variables or features of data. If we stretch a function by the factor in the time domain then squeeze the Fourier transform by the same factor in the frequency domain. Differentiation: Differentiating function with respect to time yields to the constant multiple of the initial function. Convolution: It includes the multiplication of two functions. The Fourier transform of a convolution of two functions is the point-wise product of their respective Fourier transforms. Frequency Shift and Time Shift: Frequency is shifted according to the coordinates. There is a duality between the time and frequency domains and frequency shift affects the time shift. The time variable shift also affects the frequency function. The time-shifting property concludes that a linear displacement in time corresponds to a linear phase factor in the frequency domain. The image chosen for the experiment in this article is a famous cameraman image. Figure: Input image Equation for DFT: Equation for IDFT: Steps: Read the image. Apply forward Fourier transformation. Display log and shift FT images. Function Used: imread( ) inbuilt function is used to image. fft2( ) inbuilt function is used to apply forward fourier transform on 2D signal. ifft2( ) inbuilt function is used to apply inverse Fourier transform on 2D signal. fftshift( ) inbuilt function is used to shift corners to center in FT image. log( ) inbuilt function is used to evaluate logarithm of FT complex signal. imtool( ) inbuilt function is used to display the image. Example: Matlab % MATLAB code for Forward and % Inverse Fourier Transform % FORWARD FOURIER TRANSFORMk=imread("cameraman.jpg"); % Apply fourier transformation.f=fft2(k); % Take magnitude of FT.f1=abs(f); % Take log of magnitude of FT.f2=log(abs(f)); % Shift FT from corners to central part.f3=log(abs(fftshift(f))); % Display all three FT images.imtool(f1,[]); imtool(f2,[]);imtool(f3,[]); % Remove some frequency from FT.f(1:20, 20:40)=0;imtool(log(abs(f)),[]); Output: Figure 1:Absolute of the fourier transformed image Figure 2: Log of the absolute of FT of image Figure 3:Centered spectrum of FT image Figure 4: Some frequencies blocked in FT image Code Explanation: k=imread(“cameraman.jpg”); This line reads the image. f=fft2(k); This line computes fourier transformation. f1=abs(f); This takes magnitude of FT. f2=log(abs(f)); This line takes log of magnitude of FT. f3=log(abs(fftshift(f))); This line shifts FT from corners to central part. f(1:20, 20:40)=0; This line remove frequencies from FT. Example: Matlab % MATLAB code for INVERSE FOURIER TRANSFORM% apply inverse FT on FTransformed image.% we get original image in this step.j=ifft2(f); % Take log of original image.j1=log(abs(j)); % Shift corners to center.j2=fftshift(j); % Again shift to get original image.j3=fftshift(j2); % Remove some frequency from FT image.f(1:20, 20:40)=0; % Apply inverse FT.j4=ifft2(f); % Display all 4 images.imtool(j,[]);imtool(j1,[]); imtool(j2,[]);imtool(j3,[]);%j and j3 are same.imtool(abs(j4),[]); Output: Figure 1:Original Input Image was obtained by taking the Inverse FT of the FT image Figure 2: log of absolute Inverse Fourier Transformed Image Figure 3: Corners shifted to center Figure 4: Inverse FT after removing some frequencies from Freq Domain Code Explanation: j=ifft2(f); This line computes inverse FT of FT image. f(1:20, 20:40)=0; This line removes some frequency from FT image. j4=ifft2(f); This line computes inverse FT after removing some frequencies. imtool(abs(j4),[]); This line displays modified image which contains some ringing artefacts. Properties: There is no one-to-one correspondence between the cameraman image and the Fourier transform image. The cameraman image represents the intensities in the spatial domain. Fourier transformed image represents frequency in the frequency domain. Lower frequency represents the smooth part of the image while higher frequency represents the shape components like edges of an image. If the low-frequency part is removed from the frequency domain image then the spatial domain image will get blurred. If the anyone frequency value is removed (made 0) in the frequency domain image, that particular frequency will be removed (subtracted) from every intensity value in the spatial domain image. surinderdawra388 MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? Boundary Extraction of image using MATLAB Laplacian of Gaussian Filter in MATLAB How to Solve Histogram Equalization Numerical Problem in MATLAB? MRI Image Segmentation in MATLAB How to Remove Salt and Pepper Noise from Image Using MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB How to Normalize a Histogram in MATLAB? How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? Classes and Object in MATLAB
[ { "code": null, "e": 24672, "s": 24644, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24934, "s": 24672, "text": "In this article, we shall apply Fourier Transform on images. Fourier Transform is a mathematical technique that helps to transform Time Domain function x(t) to Frequency Domain function X(ω). In this article, we will see how to find Fourier Transform in MATLAB." }, { "code": null, "e": 25294, "s": 24934, "text": "Linearity: The addition of two functions corresponding to the addition of the two frequency spectrum is called linearity. If we multiply a function by a constant, the Fourier transform of the resultant function is multiplied by the same constant. The Fourier transform of the sum of two or more functions is the sum of the Fourier transforms of the functions." }, { "code": null, "e": 25545, "s": 25294, "text": "Scaling: Scaling is the method that is used to change the range of the independent variables or features of data. If we stretch a function by the factor in the time domain then squeeze the Fourier transform by the same factor in the frequency domain." }, { "code": null, "e": 25665, "s": 25545, "text": "Differentiation: Differentiating function with respect to time yields to the constant multiple of the initial function." }, { "code": null, "e": 25849, "s": 25665, "text": "Convolution: It includes the multiplication of two functions. The Fourier transform of a convolution of two functions is the point-wise product of their respective Fourier transforms." }, { "code": null, "e": 26229, "s": 25849, "text": "Frequency Shift and Time Shift: Frequency is shifted according to the coordinates. There is a duality between the time and frequency domains and frequency shift affects the time shift. The time variable shift also affects the frequency function. The time-shifting property concludes that a linear displacement in time corresponds to a linear phase factor in the frequency domain." }, { "code": null, "e": 26310, "s": 26229, "text": "The image chosen for the experiment in this article is a famous cameraman image." }, { "code": null, "e": 26330, "s": 26310, "text": "Figure: Input image" }, { "code": null, "e": 26349, "s": 26330, "text": "Equation for DFT: " }, { "code": null, "e": 26369, "s": 26349, "text": "Equation for IDFT: " }, { "code": null, "e": 26376, "s": 26369, "text": "Steps:" }, { "code": null, "e": 26392, "s": 26376, "text": "Read the image." }, { "code": null, "e": 26430, "s": 26392, "text": "Apply forward Fourier transformation." }, { "code": null, "e": 26463, "s": 26430, "text": "Display log and shift FT images." }, { "code": null, "e": 26478, "s": 26463, "text": "Function Used:" }, { "code": null, "e": 26523, "s": 26478, "text": "imread( ) inbuilt function is used to image." }, { "code": null, "e": 26605, "s": 26523, "text": "fft2( ) inbuilt function is used to apply forward fourier transform on 2D signal." }, { "code": null, "e": 26688, "s": 26605, "text": "ifft2( ) inbuilt function is used to apply inverse Fourier transform on 2D signal." }, { "code": null, "e": 26765, "s": 26688, "text": "fftshift( ) inbuilt function is used to shift corners to center in FT image." }, { "code": null, "e": 26841, "s": 26765, "text": "log( ) inbuilt function is used to evaluate logarithm of FT complex signal." }, { "code": null, "e": 26898, "s": 26841, "text": "imtool( ) inbuilt function is used to display the image." }, { "code": null, "e": 26907, "s": 26898, "text": "Example:" }, { "code": null, "e": 26914, "s": 26907, "text": "Matlab" }, { "code": "% MATLAB code for Forward and % Inverse Fourier Transform % FORWARD FOURIER TRANSFORMk=imread(\"cameraman.jpg\"); % Apply fourier transformation.f=fft2(k); % Take magnitude of FT.f1=abs(f); % Take log of magnitude of FT.f2=log(abs(f)); % Shift FT from corners to central part.f3=log(abs(fftshift(f))); % Display all three FT images.imtool(f1,[]); imtool(f2,[]);imtool(f3,[]); % Remove some frequency from FT.f(1:20, 20:40)=0;imtool(log(abs(f)),[]);", "e": 27368, "s": 26914, "text": null }, { "code": null, "e": 27376, "s": 27368, "text": "Output:" }, { "code": null, "e": 27429, "s": 27378, "text": "Figure 1:Absolute of the fourier transformed image" }, { "code": null, "e": 27474, "s": 27429, "text": "Figure 2: Log of the absolute of FT of image" }, { "code": null, "e": 27514, "s": 27474, "text": " Figure 3:Centered spectrum of FT image" }, { "code": null, "e": 27561, "s": 27514, "text": "Figure 4: Some frequencies blocked in FT image" }, { "code": null, "e": 27579, "s": 27561, "text": "Code Explanation:" }, { "code": null, "e": 27633, "s": 27579, "text": "k=imread(“cameraman.jpg”); This line reads the image." }, { "code": null, "e": 27687, "s": 27633, "text": "f=fft2(k); This line computes fourier transformation." }, { "code": null, "e": 27726, "s": 27687, "text": "f1=abs(f); This takes magnitude of FT." }, { "code": null, "e": 27782, "s": 27726, "text": "f2=log(abs(f)); This line takes log of magnitude of FT." }, { "code": null, "e": 27858, "s": 27782, "text": "f3=log(abs(fftshift(f))); This line shifts FT from corners to central part." }, { "code": null, "e": 27914, "s": 27858, "text": "f(1:20, 20:40)=0; This line remove frequencies from FT." }, { "code": null, "e": 27923, "s": 27914, "text": "Example:" }, { "code": null, "e": 27930, "s": 27923, "text": "Matlab" }, { "code": "% MATLAB code for INVERSE FOURIER TRANSFORM% apply inverse FT on FTransformed image.% we get original image in this step.j=ifft2(f); % Take log of original image.j1=log(abs(j)); % Shift corners to center.j2=fftshift(j); % Again shift to get original image.j3=fftshift(j2); % Remove some frequency from FT image.f(1:20, 20:40)=0; % Apply inverse FT.j4=ifft2(f); % Display all 4 images.imtool(j,[]);imtool(j1,[]); imtool(j2,[]);imtool(j3,[]);%j and j3 are same.imtool(abs(j4),[]);", "e": 28415, "s": 27930, "text": null }, { "code": null, "e": 28423, "s": 28415, "text": "Output:" }, { "code": null, "e": 28509, "s": 28425, "text": "Figure 1:Original Input Image was obtained by taking the Inverse FT of the FT image" }, { "code": null, "e": 28571, "s": 28511, "text": "Figure 2: log of absolute Inverse Fourier Transformed Image" }, { "code": null, "e": 28609, "s": 28573, "text": "Figure 3: Corners shifted to center" }, { "code": null, "e": 28679, "s": 28609, "text": "Figure 4: Inverse FT after removing some frequencies from Freq Domain" }, { "code": null, "e": 28698, "s": 28679, "text": "Code Explanation: " }, { "code": null, "e": 28753, "s": 28698, "text": "j=ifft2(f); This line computes inverse FT of FT image." }, { "code": null, "e": 28819, "s": 28753, "text": "f(1:20, 20:40)=0; This line removes some frequency from FT image." }, { "code": null, "e": 28895, "s": 28819, "text": "j4=ifft2(f); This line computes inverse FT after removing some frequencies." }, { "code": null, "e": 28988, "s": 28895, "text": "imtool(abs(j4),[]); This line displays modified image which contains some ringing artefacts." }, { "code": null, "e": 29000, "s": 28988, "text": "Properties:" }, { "code": null, "e": 29099, "s": 29000, "text": "There is no one-to-one correspondence between the cameraman image and the Fourier transform image." }, { "code": null, "e": 29169, "s": 29099, "text": "The cameraman image represents the intensities in the spatial domain." }, { "code": null, "e": 29241, "s": 29169, "text": "Fourier transformed image represents frequency in the frequency domain." }, { "code": null, "e": 29376, "s": 29241, "text": "Lower frequency represents the smooth part of the image while higher frequency represents the shape components like edges of an image." }, { "code": null, "e": 29493, "s": 29376, "text": "If the low-frequency part is removed from the frequency domain image then the spatial domain image will get blurred." }, { "code": null, "e": 29685, "s": 29493, "text": "If the anyone frequency value is removed (made 0) in the frequency domain image, that particular frequency will be removed (subtracted) from every intensity value in the spatial domain image." }, { "code": null, "e": 29704, "s": 29687, "text": "surinderdawra388" }, { "code": null, "e": 29728, "s": 29704, "text": "MATLAB image-processing" }, { "code": null, "e": 29735, "s": 29728, "text": "MATLAB" }, { "code": null, "e": 29833, "s": 29735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29906, "s": 29833, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 29948, "s": 29906, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 29987, "s": 29948, "text": "Laplacian of Gaussian Filter in MATLAB" }, { "code": null, "e": 30052, "s": 29987, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 30085, "s": 30052, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 30146, "s": 30085, "text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?" }, { "code": null, "e": 30211, "s": 30146, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 30251, "s": 30211, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 30330, "s": 30251, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" } ]
Neo4j - Substring Function
It takes a string as an input and two indexes: one is the start of the index and another is the end of the index and returns a substring from Start Index to End Index-1. All CQL Functions should use "( )" brackets. Following is the syntax of the function SUBSTRING() in Neo4j. LOWER (<input-string>) Following is a sample Cypher query which demonstrates the usage of the function SUBSTRING() in Neo4j. Here, we are trying get the substring of the names of all the players. MATCH (n:player) RETURN SUBSTRING(n.name,0,5), n.YOB, n.POB To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2554, "s": 2339, "text": "It takes a string as an input and two indexes: one is the start of the index and another is the end of the index and returns a substring from Start Index to End Index-1. All CQL Functions should use \"( )\" brackets." }, { "code": null, "e": 2616, "s": 2554, "text": "Following is the syntax of the function SUBSTRING() in Neo4j." }, { "code": null, "e": 2641, "s": 2616, "text": "LOWER (<input-string>) \n" }, { "code": null, "e": 2814, "s": 2641, "text": "Following is a sample Cypher query which demonstrates the usage of the function SUBSTRING() in Neo4j. Here, we are trying get the substring of the names of all the players." }, { "code": null, "e": 2876, "s": 2814, "text": "MATCH (n:player) \nRETURN SUBSTRING(n.name,0,5), n.YOB, n.POB" }, { "code": null, "e": 2936, "s": 2876, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 3114, "s": 2936, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 3267, "s": 3114, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 3316, "s": 3267, "text": "On executing, you will get the following result." }, { "code": null, "e": 3323, "s": 3316, "text": " Print" }, { "code": null, "e": 3334, "s": 3323, "text": " Add Notes" } ]
A static initialization block in Java
Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program. A program that demonstrates a static initialization block in Java is given as follows: Live Demo public class Demo { static int[] numArray = new int[10]; static { System.out.println("Running static initialization block."); for (int i = 0; i < numArray.length; i++) { numArray[i] = (int) (100.0 * Math.random()); } } void printArray() { System.out.println("The initialized values are:"); for (int i = 0; i < numArray.length; i++) { System.out.print(numArray[i] + " "); } System.out.println(); } public static void main(String[] args) { Demo obj1 = new Demo(); System.out.println("For obj1:"); obj1.printArray(); Demo obj2 = new Demo(); System.out.println("\nFor obj2:"); obj2.printArray(); } } Running static initialization block. For obj1: The initialized values are: 40 75 88 51 44 50 34 79 22 21 For obj2: The initialized values are: 40 75 88 51 44 50 34 79 22 21
[ { "code": null, "e": 1399, "s": 1062, "text": "Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program." }, { "code": null, "e": 1486, "s": 1399, "text": "A program that demonstrates a static initialization block in Java is given as follows:" }, { "code": null, "e": 1497, "s": 1486, "text": " Live Demo" }, { "code": null, "e": 2210, "s": 1497, "text": "public class Demo {\n static int[] numArray = new int[10];\n static {\n System.out.println(\"Running static initialization block.\");\n for (int i = 0; i < numArray.length; i++) {\n numArray[i] = (int) (100.0 * Math.random());\n }\n }\n void printArray() {\n System.out.println(\"The initialized values are:\");\n for (int i = 0; i < numArray.length; i++) {\n System.out.print(numArray[i] + \" \");\n }\n System.out.println();\n }\n public static void main(String[] args) {\n Demo obj1 = new Demo();\n System.out.println(\"For obj1:\");\n obj1.printArray();\n Demo obj2 = new Demo();\n System.out.println(\"\\nFor obj2:\");\n obj2.printArray();\n }\n}" }, { "code": null, "e": 2384, "s": 2210, "text": "Running static initialization block.\nFor obj1:\nThe initialized values are:\n40 75 88 51 44 50 34 79 22 21\n\nFor obj2:\nThe initialized values are:\n40 75 88 51 44 50 34 79 22 21" } ]
Find the node with minimum value in a Binary Search Tree using recursion - GeeksforGeeks
23 Jun, 2021 Given a Binary Search Tree, the task is to find the node with minimum value. Examples: Input: Output: 4 Approach: Just traverse the node from root to left recursively until left is NULL. The node whose left is NULL is the node with the minimum value. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Give a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */struct node* insert(struct node* node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treeint minValue(struct node* node){ if (node->left == NULL) return node->data; return minValue(node->left);} // Driver codeint main(){ // Create the BST struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); cout << minValue(root); return 0;} // Java Implementation of the above approach class GFG{ /* A binary tree node has data, pointer to left childand a pointer to right child */static class Node{ int data; Node left; Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */static Node insert(Node node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treestatic int minValue(Node node){ if (node.left == null) return node.data; return minValue(node.left);} // Driver codepublic static void main(String args[]){ // Create the BST Node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); System.out.println(minValue(root)); }} // This code has been contributed by 29AjayKumar # Python3 Implementation of# the above approachclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates # a new node with the given data# and null left and right pointers.def insert(node, data): if node is None : return Node(data) else: if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) return node # Function to return the minimum node# in the given binary search treedef minValue(node): if node.left == None: return node.data return minValue(node.left) # Driver codeif __name__ == "__main__" : # Create the BST root = None root = insert(root, 4) insert(root, 2) insert(root, 1) insert(root, 3) insert(root, 6) insert(root, 5) print(minValue(root)) # This code is contributed by vinayak // C# Implementation of the above approachusing System; class GFG{ /* A binary tree node has data, pointer to left childand a pointer to right child */public class Node{ public int data; public Node left; public Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */static Node insert(Node node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treestatic int minValue(Node node){ if (node.left == null) return node.data; return minValue(node.left);} // Driver codepublic static void Main(String []args){ // Create the BST Node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); Console.WriteLine(minValue(root)); }} // This code contributed by Rajput-Ji <script> // Javascript implementation of the above approach // A binary tree node has data, pointer to// left child and a pointer to right childclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Helper function that allocates a new node// with the given data and null left and right// pointers.function newNode(data){ var node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Give a binary search tree and a number,// inserts a new node with the given number in// the correct place in the tree. Returns the new// root pointer which the caller should then use// (the standard trick to avoid using reference// parameters).function insert(node, data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treefunction minValue(node){ if (node.left == null) return node.data; return minValue(node.left);} // Driver code // Create the BSTvar root = null;root = insert(root, 4);insert(root, 2);insert(root, 1);insert(root, 3);insert(root, 6);insert(root, 5); document.write(minValue(root)); // This code is contributed by noob2000 </script> 1 Time Complexity: O(n), worst case happens for left skewed trees. 29AjayKumar Rajput-Ji itsvinayak noob2000 Traversal Binary Search Tree Tree Traversal Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. set vs unordered_set in C++ STL Construct BST from given preorder traversal | Set 2 Red Black Tree vs AVL Tree Print BST keys in the given range Find the node with maximum value in a Binary Search Tree Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 26580, "s": 26552, "text": "\n23 Jun, 2021" }, { "code": null, "e": 26657, "s": 26580, "text": "Given a Binary Search Tree, the task is to find the node with minimum value." }, { "code": null, "e": 26668, "s": 26657, "text": "Examples: " }, { "code": null, "e": 26677, "s": 26668, "text": "Input: " }, { "code": null, "e": 26690, "s": 26677, "text": "Output: 4 " }, { "code": null, "e": 26837, "s": 26690, "text": "Approach: Just traverse the node from root to left recursively until left is NULL. The node whose left is NULL is the node with the minimum value." }, { "code": null, "e": 26889, "s": 26837, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26893, "s": 26889, "text": "C++" }, { "code": null, "e": 26898, "s": 26893, "text": "Java" }, { "code": null, "e": 26906, "s": 26898, "text": "Python3" }, { "code": null, "e": 26909, "s": 26906, "text": "C#" }, { "code": null, "e": 26920, "s": 26909, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Give a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */struct node* insert(struct node* node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treeint minValue(struct node* node){ if (node->left == NULL) return node->data; return minValue(node->left);} // Driver codeint main(){ // Create the BST struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); cout << minValue(root); return 0;}", "e": 28594, "s": 26920, "text": null }, { "code": "// Java Implementation of the above approach class GFG{ /* A binary tree node has data, pointer to left childand a pointer to right child */static class Node{ int data; Node left; Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */static Node insert(Node node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treestatic int minValue(Node node){ if (node.left == null) return node.data; return minValue(node.left);} // Driver codepublic static void main(String args[]){ // Create the BST Node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); System.out.println(minValue(root)); }} // This code has been contributed by 29AjayKumar", "e": 30213, "s": 28594, "text": null }, { "code": "# Python3 Implementation of# the above approachclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Helper function that allocates # a new node with the given data# and null left and right pointers.def insert(node, data): if node is None : return Node(data) else: if data <= node.data: node.left = insert(node.left, data) else: node.right = insert(node.right, data) return node # Function to return the minimum node# in the given binary search treedef minValue(node): if node.left == None: return node.data return minValue(node.left) # Driver codeif __name__ == \"__main__\" : # Create the BST root = None root = insert(root, 4) insert(root, 2) insert(root, 1) insert(root, 3) insert(root, 6) insert(root, 5) print(minValue(root)) # This code is contributed by vinayak", "e": 31146, "s": 30213, "text": null }, { "code": "// C# Implementation of the above approachusing System; class GFG{ /* A binary tree node has data, pointer to left childand a pointer to right child */public class Node{ public int data; public Node left; public Node right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} /* Give a binary search tree and a number,inserts a new node with the given number inthe correct place in the tree. Returns the newroot pointer which the caller should then use(the standard trick to avoid using referenceparameters). */static Node insert(Node node, int data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treestatic int minValue(Node node){ if (node.left == null) return node.data; return minValue(node.left);} // Driver codepublic static void Main(String []args){ // Create the BST Node root = null; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); Console.WriteLine(minValue(root)); }} // This code contributed by Rajput-Ji", "e": 32789, "s": 31146, "text": null }, { "code": "<script> // Javascript implementation of the above approach // A binary tree node has data, pointer to// left child and a pointer to right childclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Helper function that allocates a new node// with the given data and null left and right// pointers.function newNode(data){ var node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Give a binary search tree and a number,// inserts a new node with the given number in// the correct place in the tree. Returns the new// root pointer which the caller should then use// (the standard trick to avoid using reference// parameters).function insert(node, data){ /* 1. If the tree is empty, return a new, single node */ if (node == null) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node.data) node.left = insert(node.left, data); else node.right = insert(node.right, data); /* return the (unchanged) node pointer */ return node; }} // Function to return the minimum node// in the given binary search treefunction minValue(node){ if (node.left == null) return node.data; return minValue(node.left);} // Driver code // Create the BSTvar root = null;root = insert(root, 4);insert(root, 2);insert(root, 1);insert(root, 3);insert(root, 6);insert(root, 5); document.write(minValue(root)); // This code is contributed by noob2000 </script>", "e": 34391, "s": 32789, "text": null }, { "code": null, "e": 34393, "s": 34391, "text": "1" }, { "code": null, "e": 34461, "s": 34395, "text": "Time Complexity: O(n), worst case happens for left skewed trees. " }, { "code": null, "e": 34473, "s": 34461, "text": "29AjayKumar" }, { "code": null, "e": 34483, "s": 34473, "text": "Rajput-Ji" }, { "code": null, "e": 34494, "s": 34483, "text": "itsvinayak" }, { "code": null, "e": 34503, "s": 34494, "text": "noob2000" }, { "code": null, "e": 34513, "s": 34503, "text": "Traversal" }, { "code": null, "e": 34532, "s": 34513, "text": "Binary Search Tree" }, { "code": null, "e": 34537, "s": 34532, "text": "Tree" }, { "code": null, "e": 34547, "s": 34537, "text": "Traversal" }, { "code": null, "e": 34566, "s": 34547, "text": "Binary Search Tree" }, { "code": null, "e": 34571, "s": 34566, "text": "Tree" }, { "code": null, "e": 34669, "s": 34571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34701, "s": 34669, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 34753, "s": 34701, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 34780, "s": 34753, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 34814, "s": 34780, "text": "Print BST keys in the given range" }, { "code": null, "e": 34871, "s": 34814, "text": "Find the node with maximum value in a Binary Search Tree" }, { "code": null, "e": 34921, "s": 34871, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 34956, "s": 34921, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 34990, "s": 34956, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 35033, "s": 34990, "text": "Binary Tree | Set 3 (Types of Binary Tree)" } ]
PyQt5 – How to add Separator in Status Bar ? - GeeksforGeeks
22 Apr, 2020 In this article we will see how to add separator in status bar. separator are basically just vertical lines which are used to distinguish items. Below is the difference between the statusbar with separator and without separator. The main concept is that we will add a widget between two labels which will be a vertical line which will act as a separator. Code : from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys # creating VLine classclass VLine(QFrame): # a simple Vertical line def __init__(self): super(VLine, self).__init__() self.setFrameShape(self.VLine|self.Sunken) class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage("This is status bar") # setting border and padding with different sizes self.statusBar().setStyleSheet("border :3px solid black;") # creating a label widget self.label_1 = QLabel("Label 1") # setting up the border self.label_1.setStyleSheet("border :2px solid blue;") # creating a label widget self.label_2 = QLabel("Label 2") # setting up the border self.label_2.setStyleSheet("border :2px solid blue;") # adding label to status bar self.statusBar().addPermanentWidget(self.label_1) # adding VLine object self.statusBar().addPermanentWidget(VLine()) # adding label self.statusBar().addPermanentWidget(self.label_2) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24354, "s": 24326, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24499, "s": 24354, "text": "In this article we will see how to add separator in status bar. separator are basically just vertical lines which are used to distinguish items." }, { "code": null, "e": 24583, "s": 24499, "text": "Below is the difference between the statusbar with separator and without separator." }, { "code": null, "e": 24709, "s": 24583, "text": "The main concept is that we will add a widget between two labels which will be a vertical line which will act as a separator." }, { "code": null, "e": 24716, "s": 24709, "text": "Code :" }, { "code": "from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys # creating VLine classclass VLine(QFrame): # a simple Vertical line def __init__(self): super(VLine, self).__init__() self.setFrameShape(self.VLine|self.Sunken) class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage(\"This is status bar\") # setting border and padding with different sizes self.statusBar().setStyleSheet(\"border :3px solid black;\") # creating a label widget self.label_1 = QLabel(\"Label 1\") # setting up the border self.label_1.setStyleSheet(\"border :2px solid blue;\") # creating a label widget self.label_2 = QLabel(\"Label 2\") # setting up the border self.label_2.setStyleSheet(\"border :2px solid blue;\") # adding label to status bar self.statusBar().addPermanentWidget(self.label_1) # adding VLine object self.statusBar().addPermanentWidget(VLine()) # adding label self.statusBar().addPermanentWidget(self.label_2) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26233, "s": 24716, "text": null }, { "code": null, "e": 26242, "s": 26233, "text": "Output :" }, { "code": null, "e": 26253, "s": 26242, "text": "Python-gui" }, { "code": null, "e": 26265, "s": 26253, "text": "Python-PyQt" }, { "code": null, "e": 26272, "s": 26265, "text": "Python" }, { "code": null, "e": 26370, "s": 26272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26379, "s": 26370, "text": "Comments" }, { "code": null, "e": 26392, "s": 26379, "text": "Old Comments" }, { "code": null, "e": 26410, "s": 26392, "text": "Python Dictionary" }, { "code": null, "e": 26445, "s": 26410, "text": "Read a file line by line in Python" }, { "code": null, "e": 26467, "s": 26445, "text": "Enumerate() in Python" }, { "code": null, "e": 26499, "s": 26467, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26529, "s": 26499, "text": "Iterate over a list in Python" }, { "code": null, "e": 26571, "s": 26529, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26597, "s": 26571, "text": "Python String | replace()" }, { "code": null, "e": 26640, "s": 26597, "text": "Python program to convert a list to string" }, { "code": null, "e": 26684, "s": 26640, "text": "Reading and Writing to text files in Python" } ]
set find() function in C++ STL - GeeksforGeeks
24 Dec, 2021 The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set. Syntax: set_name.find(element) Parameters: The function accepts one mandatory parameter element which specifies the element to be searched in the set container. Return Value: The function returns an iterator which points to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.Below program illustrates the above function. CPP // CPP program to demonstrate the// set::find() function#include <bits/stdc++.h>using namespace std;int main(){ // Initialize set set<int> s; s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(3); // iterator pointing to // position where 3 is auto pos = s.find(3); // prints the set elements cout << "The set elements after 3 are: "; for (auto it = pos; it != s.end(); it++) cout << *it << " "; return 0;} The set elements after 3 are: 3 4 5 Time Complexity: The time complexity of set_name.find( key ) is O( log N ). As the elements are stored in a sorted manner by default. vpsh98 adarshlondhe19 sushanthgupta devhati83 CPP-Functions cpp-set STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Virtual Function in C++ Bitwise Operators in C/C++ Constructors in C++ Operator Overloading in C++ Templates in C++ with Examples Socket Programming in C/C++ Polymorphism in C++ Object Oriented Programming in C++
[ { "code": null, "e": 25860, "s": 25832, "text": "\n24 Dec, 2021" }, { "code": null, "e": 26100, "s": 25860, "text": "The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set." }, { "code": null, "e": 26111, "s": 26100, "text": "Syntax: " }, { "code": null, "e": 26137, "s": 26111, "text": " \nset_name.find(element) " }, { "code": null, "e": 26539, "s": 26137, "text": "Parameters: The function accepts one mandatory parameter element which specifies the element to be searched in the set container. Return Value: The function returns an iterator which points to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.Below program illustrates the above function. " }, { "code": null, "e": 26543, "s": 26539, "text": "CPP" }, { "code": "// CPP program to demonstrate the// set::find() function#include <bits/stdc++.h>using namespace std;int main(){ // Initialize set set<int> s; s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(3); // iterator pointing to // position where 3 is auto pos = s.find(3); // prints the set elements cout << \"The set elements after 3 are: \"; for (auto it = pos; it != s.end(); it++) cout << *it << \" \"; return 0;}", "e": 27014, "s": 26543, "text": null }, { "code": null, "e": 27050, "s": 27014, "text": "The set elements after 3 are: 3 4 5" }, { "code": null, "e": 27186, "s": 27052, "text": "Time Complexity: The time complexity of set_name.find( key ) is O( log N ). As the elements are stored in a sorted manner by default." }, { "code": null, "e": 27193, "s": 27186, "text": "vpsh98" }, { "code": null, "e": 27208, "s": 27193, "text": "adarshlondhe19" }, { "code": null, "e": 27222, "s": 27208, "text": "sushanthgupta" }, { "code": null, "e": 27232, "s": 27222, "text": "devhati83" }, { "code": null, "e": 27246, "s": 27232, "text": "CPP-Functions" }, { "code": null, "e": 27254, "s": 27246, "text": "cpp-set" }, { "code": null, "e": 27258, "s": 27254, "text": "STL" }, { "code": null, "e": 27262, "s": 27258, "text": "C++" }, { "code": null, "e": 27266, "s": 27262, "text": "STL" }, { "code": null, "e": 27270, "s": 27266, "text": "CPP" }, { "code": null, "e": 27368, "s": 27270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27387, "s": 27368, "text": "Inheritance in C++" }, { "code": null, "e": 27411, "s": 27387, "text": "C++ Classes and Objects" }, { "code": null, "e": 27435, "s": 27411, "text": "Virtual Function in C++" }, { "code": null, "e": 27462, "s": 27435, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27482, "s": 27462, "text": "Constructors in C++" }, { "code": null, "e": 27510, "s": 27482, "text": "Operator Overloading in C++" }, { "code": null, "e": 27541, "s": 27510, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27569, "s": 27541, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27589, "s": 27569, "text": "Polymorphism in C++" } ]
CSS | * Selector - GeeksforGeeks
10 Jul, 2021 The * selector in CSS is used to select all the elements in a HTML document. It also selects all elements which are inside under another element. It is also called universal selector. Syntax: * { // CSS property } Example 1: HTML <!DOCTYPE html><html> <head> <title>* Selector</title> <!-- CSS property of * selector --> <style> * { color:green; text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>*(Universal) Selector</h2> <div> <p>GFG</p> <p>Geeks</p> </div> <p>It is a computer science portal for geeks.</p> </body></html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <title>* selector</title> <!-- CSS property for * selector --> <style> * { background: green; font-weight:bold; margin-left:70px; color:white; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>*(Universal) Selector</h2> <ul> <li>Data Structure</li> <li>Computer Network</li> <li>Operating System</li> </ul> <ol> <li>Java</li> <li>Ruby</li> <li>Pascal</li> </ol> </body></html> Output: Supported Browsers: The browser supported by *(universal) selector are listed below: Apple Safari 3.1 Google Chrome 4.0 Firefox 3.0 Opera 9.6 Internet Explorer 7.0 saurabh1990aror CSS-Selectors Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 27966, "s": 27938, "text": "\n10 Jul, 2021" }, { "code": null, "e": 28150, "s": 27966, "text": "The * selector in CSS is used to select all the elements in a HTML document. It also selects all elements which are inside under another element. It is also called universal selector." }, { "code": null, "e": 28159, "s": 28150, "text": "Syntax: " }, { "code": null, "e": 28186, "s": 28159, "text": "* {\n // CSS property\n} " }, { "code": null, "e": 28198, "s": 28186, "text": "Example 1: " }, { "code": null, "e": 28203, "s": 28198, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>* Selector</title> <!-- CSS property of * selector --> <style> * { color:green; text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>*(Universal) Selector</h2> <div> <p>GFG</p> <p>Geeks</p> </div> <p>It is a computer science portal for geeks.</p> </body></html> ", "e": 28728, "s": 28203, "text": null }, { "code": null, "e": 28737, "s": 28728, "text": "Output: " }, { "code": null, "e": 28749, "s": 28737, "text": "Example 2: " }, { "code": null, "e": 28754, "s": 28749, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>* selector</title> <!-- CSS property for * selector --> <style> * { background: green; font-weight:bold; margin-left:70px; color:white; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>*(Universal) Selector</h2> <ul> <li>Data Structure</li> <li>Computer Network</li> <li>Operating System</li> </ul> <ol> <li>Java</li> <li>Ruby</li> <li>Pascal</li> </ol> </body></html> ", "e": 29467, "s": 28754, "text": null }, { "code": null, "e": 29476, "s": 29467, "text": "Output: " }, { "code": null, "e": 29562, "s": 29476, "text": "Supported Browsers: The browser supported by *(universal) selector are listed below: " }, { "code": null, "e": 29579, "s": 29562, "text": "Apple Safari 3.1" }, { "code": null, "e": 29597, "s": 29579, "text": "Google Chrome 4.0" }, { "code": null, "e": 29609, "s": 29597, "text": "Firefox 3.0" }, { "code": null, "e": 29619, "s": 29609, "text": "Opera 9.6" }, { "code": null, "e": 29641, "s": 29619, "text": "Internet Explorer 7.0" }, { "code": null, "e": 29659, "s": 29643, "text": "saurabh1990aror" }, { "code": null, "e": 29673, "s": 29659, "text": "CSS-Selectors" }, { "code": null, "e": 29680, "s": 29673, "text": "Picked" }, { "code": null, "e": 29684, "s": 29680, "text": "CSS" }, { "code": null, "e": 29701, "s": 29684, "text": "Web Technologies" }, { "code": null, "e": 29799, "s": 29701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29808, "s": 29799, "text": "Comments" }, { "code": null, "e": 29821, "s": 29808, "text": "Old Comments" }, { "code": null, "e": 29883, "s": 29821, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29933, "s": 29883, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29991, "s": 29933, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 30039, "s": 29991, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30076, "s": 30039, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30118, "s": 30076, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30151, "s": 30118, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30213, "s": 30151, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30256, "s": 30213, "text": "How to fetch data from an API in ReactJS ?" } ]
Find position of a Matched Pattern in a String in R Programming – grep() Function - GeeksforGeeks
12 Apr, 2021 grep() function in R Language is used to search for matches of a pattern within each element of the given string. Syntax: grep(pattern, x, ignore.case=TRUE/FALSE, value=TRUE/FALSE)Parameters: pattern: Specified pattern which is going to be matched with given elements of the string. x: Specified string vector. ignore.case: If its value is TRUE, it ignores case. value: If its value is TRUE, it return the matching elements vector, else return the indices vector. Example 1: Python3 # R program to illustrate# grep function # Creating string vectorx <- c("GFG", "gfg", "Geeks", "GEEKS") # Calling grep() functiongrep("gfg", x)grep("Geeks", x)grep("gfg", x, ignore.case = FALSE)grep("Geeks", x, ignore.case = TRUE) Output : [1] 2 [1] 3 [1] 2 [1] 3 4 Example 2: Python3 # R program to illustrate# grep function # Creating string vectorx <- c("GFG", "gfg", "Geeks", "GEEKS") # Calling grep() functiongrep("gfg", x, ignore.case = TRUE, value = TRUE)grep("G", x, ignore.case = TRUE, value = TRUE)grep("Geeks", x, ignore.case = FALSE, value = FALSE)grep("GEEKS", x, ignore.case = FALSE, value = FALSE) Output: [1] "GFG" "gfg" [1] "GFG" "gfg" "Geeks" "GEEKS" [1] 3 [1] 4 arorakashish0911 R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n12 Apr, 2021" }, { "code": null, "e": 24966, "s": 24851, "text": "grep() function in R Language is used to search for matches of a pattern within each element of the given string. " }, { "code": null, "e": 25318, "s": 24966, "text": "Syntax: grep(pattern, x, ignore.case=TRUE/FALSE, value=TRUE/FALSE)Parameters: pattern: Specified pattern which is going to be matched with given elements of the string. x: Specified string vector. ignore.case: If its value is TRUE, it ignores case. value: If its value is TRUE, it return the matching elements vector, else return the indices vector. " }, { "code": null, "e": 25331, "s": 25318, "text": "Example 1: " }, { "code": null, "e": 25339, "s": 25331, "text": "Python3" }, { "code": "# R program to illustrate# grep function # Creating string vectorx <- c(\"GFG\", \"gfg\", \"Geeks\", \"GEEKS\") # Calling grep() functiongrep(\"gfg\", x)grep(\"Geeks\", x)grep(\"gfg\", x, ignore.case = FALSE)grep(\"Geeks\", x, ignore.case = TRUE)", "e": 25570, "s": 25339, "text": null }, { "code": null, "e": 25581, "s": 25570, "text": "Output : " }, { "code": null, "e": 25607, "s": 25581, "text": "[1] 2\n[1] 3\n[1] 2\n[1] 3 4" }, { "code": null, "e": 25620, "s": 25607, "text": "Example 2: " }, { "code": null, "e": 25628, "s": 25620, "text": "Python3" }, { "code": "# R program to illustrate# grep function # Creating string vectorx <- c(\"GFG\", \"gfg\", \"Geeks\", \"GEEKS\") # Calling grep() functiongrep(\"gfg\", x, ignore.case = TRUE, value = TRUE)grep(\"G\", x, ignore.case = TRUE, value = TRUE)grep(\"Geeks\", x, ignore.case = FALSE, value = FALSE)grep(\"GEEKS\", x, ignore.case = FALSE, value = FALSE) ", "e": 25966, "s": 25628, "text": null }, { "code": null, "e": 25976, "s": 25966, "text": "Output: " }, { "code": null, "e": 26040, "s": 25976, "text": "[1] \"GFG\" \"gfg\"\n[1] \"GFG\" \"gfg\" \"Geeks\" \"GEEKS\"\n[1] 3\n[1] 4" }, { "code": null, "e": 26059, "s": 26042, "text": "arorakashish0911" }, { "code": null, "e": 26078, "s": 26059, "text": "R String-Functions" }, { "code": null, "e": 26089, "s": 26078, "text": "R Language" }, { "code": null, "e": 26187, "s": 26089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26196, "s": 26187, "text": "Comments" }, { "code": null, "e": 26209, "s": 26196, "text": "Old Comments" }, { "code": null, "e": 26261, "s": 26209, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26299, "s": 26261, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26334, "s": 26299, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26392, "s": 26334, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26435, "s": 26392, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26484, "s": 26435, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26534, "s": 26484, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26551, "s": 26534, "text": "R - if statement" }, { "code": null, "e": 26588, "s": 26551, "text": "How to import an Excel File into R ?" } ]
Moving balls in Tkinter Canvas
Tkinter is a standard Python library which is used to create GUI-based applications. To create a simple moving ball application, we can use the Canvas widget which allows the user to add images, draw shapes, and animating objects. The application has the following components, A Canvas widget to draw the oval or ball in the window. A Canvas widget to draw the oval or ball in the window. To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom). To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom). To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration. To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration. Finally, execute the code to run the application. Finally, execute the code to run the application. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") # Make the window size fixed win.resizable(False,False) # Create a canvas widget canvas=Canvas(win, width=700, height=350) canvas.pack() # Create an oval or ball in the canvas widget ball=canvas.create_oval(10,10,50,50, fill="green3") # Move the ball xspeed=yspeed=3 def move_ball(): global xspeed, yspeed canvas.move(ball, xspeed, yspeed) (leftpos, toppos, rightpos, bottompos)=canvas.coords(ball) if leftpos <=0 or rightpos>=700: xspeed=-xspeed if toppos <=0 or bottompos >=350: yspeed=-yspeed canvas.after(30,move_ball) canvas.after(30, move_ball) win.mainloop() Running the above code will display an application window that will have a movable ball in the canvas.
[ { "code": null, "e": 1339, "s": 1062, "text": "Tkinter is a standard Python library which is used to create GUI-based applications. To create a simple moving ball application, we can use the Canvas widget which allows the user to add images, draw shapes, and animating objects. The application has the following components," }, { "code": null, "e": 1395, "s": 1339, "text": "A Canvas widget to draw the oval or ball in the window." }, { "code": null, "e": 1451, "s": 1395, "text": "A Canvas widget to draw the oval or ball in the window." }, { "code": null, "e": 1672, "s": 1451, "text": "To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom)." }, { "code": null, "e": 1893, "s": 1672, "text": "To move the ball, we have to define a function move_ball(). In the function, you have to define the position of the ball that will constantly get updated when the ball hits the canvas wall (left, right, top, and bottom)." }, { "code": null, "e": 2050, "s": 1893, "text": "To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration." }, { "code": null, "e": 2207, "s": 2050, "text": "To update the ball position, we have to use canvas.after(duration, function()) which reflects the ball to change its position after a certain time duration." }, { "code": null, "e": 2257, "s": 2207, "text": "Finally, execute the code to run the application." }, { "code": null, "e": 2307, "s": 2257, "text": "Finally, execute the code to run the application." }, { "code": null, "e": 3079, "s": 2307, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Make the window size fixed\nwin.resizable(False,False)\n\n# Create a canvas widget\ncanvas=Canvas(win, width=700, height=350)\ncanvas.pack()\n\n# Create an oval or ball in the canvas widget\nball=canvas.create_oval(10,10,50,50, fill=\"green3\")\n\n# Move the ball\nxspeed=yspeed=3\n\ndef move_ball():\n global xspeed, yspeed\n\n canvas.move(ball, xspeed, yspeed)\n (leftpos, toppos, rightpos, bottompos)=canvas.coords(ball)\n if leftpos <=0 or rightpos>=700:\n xspeed=-xspeed\n\n if toppos <=0 or bottompos >=350:\n yspeed=-yspeed\n\n canvas.after(30,move_ball)\n\ncanvas.after(30, move_ball)\n\nwin.mainloop()" }, { "code": null, "e": 3182, "s": 3079, "text": "Running the above code will display an application window that will have a movable ball in the canvas." } ]
Explicitly Defaulted and Deleted Functions in C++ 11 - GeeksforGeeks
06 Jun, 2021 What is a Defaulted Function? Explicitly defaulted function declaration is a new form of function declaration that is introduced into the C++11 standard which allows you to append the ‘=default;’ specifier to the end of a function declaration to declare that function as an explicitly defaulted function. This makes the compiler generate the default implementations for explicitly defaulted functions, which are more efficient than manually programmed function implementations. For example, whenever we declare a parameterized constructor, the compiler won’t create a default constructor. In such a case, we can use the default specifier in order to create a default one. The following code demonstrates how: CPP // C++ code to demonstrate the// use of defaulted functions#include <iostream>using namespace std; class A {public: // A user-defined // parameterized constructor A(int x) { cout << "This is a parameterized constructor"; } // Using the default specifier to instruct // the compiler to create the default // implementation of the constructor. A() = default;}; int main(){ // executes using defaulted constructor A a; // uses parameterized constructor A x(1); return 0;} Output: This is a parameterized constructor In the above case, we didn’t have to specify the body of the constructor A() because, by appending the specifier ‘=default’, the compiler will create a default implementation of this function.What are constrains with making functions defaulted? A defaulted function needs to be a special member function (default constructor, copy constructor, destructor etc), or has no default arguments. For example, the following code explains that non-special member functions can’t be defaulted: CPP // C++ code to demonstrate that// non-special member functions// can't be defaultedclass B {public: // Error, func is not a special member function. int func() = default; // Error, constructor B(int, int) is not // a special member function. B(int, int) = default; // Error, constructor B(int=0) // has a default argument. B(int = 0) = default;}; // driver programint main(){ return 0;} What are the advantages of ‘=default’ when we could simply leave an empty body of the function using ‘{}’? Even though the two may behave the same, there are still benefits of using default over leaving an empty body of the constructor. The following points explain how: Giving a user-defined constructor, even though it does nothing, makes the type not an aggregate and also not trivial. If you want your class to be an aggregate or a trivial type (or by transitivity, a POD type), then you need to use ‘= default’.Using ‘= default’ can also be used with copy constructor and destructors. An empty copy constructor, for example, will not do the same as a defaulted copy constructor (which will perform member-wise copy of its members). Using the ‘= default’ syntax uniformly for each of these special member functions makes code easier to read. Giving a user-defined constructor, even though it does nothing, makes the type not an aggregate and also not trivial. If you want your class to be an aggregate or a trivial type (or by transitivity, a POD type), then you need to use ‘= default’. Using ‘= default’ can also be used with copy constructor and destructors. An empty copy constructor, for example, will not do the same as a defaulted copy constructor (which will perform member-wise copy of its members). Using the ‘= default’ syntax uniformly for each of these special member functions makes code easier to read. Prior to C++ 11, the operator delete had only one purpose, to deallocate a memory that has been allocated dynamically. The C++ 11 standard introduced another use of this operator, which is: To disable the usage of a member function. This is done by appending the =delete; specifier to the end of that function declaration.Any member function whose usage has been disabled by using the ‘=delete’ specifier is known as an explicitly deleted function.Although not limited to them, but this is usually done to implicit functions. The following examples exhibit some of the tasks where this feature comes handy:Disabling copy constructors CPP // C++ program to disable the usage of// copy-constructor using delete operator#include <iostream>using namespace std; class A {public: A(int x): m(x) { } // Delete the copy constructor A(const A&) = delete; // Delete the copy assignment operator A& operator=(const A&) = delete; int m;}; int main(){ A a1(1), a2(2), a3(3); // Error, the usage of the copy // assignment operator is disabled a1 = a2; // Error, the usage of the // copy constructor is disabled a3 = A(a2); return 0;} Disabling undesirable argument conversion CPP // C++ program to disable undesirable argument// type conversion using delete operator#include <iostream>using namespace std; class A {public: A(int) {} // Declare the conversion constructor as a // deleted function. Without this step, // even though A(double) isn't defined, // the A(int) would accept any double value // for it's argumentand convert it to an int A(double) = delete;}; int main(){ A A1(1); // Error, conversion from // double to class A is disabled. A A2(100.1); return 0;} It is very important to note that A deleted function is implicitly inline. A deleted definition of a function must be the first declaration of the function. In other words, the following way is the correct way of declaring a function as deleted: class C { public: C(C& a) = delete; }; But the following way of trying to declare a function deleted will produce an error: CPP // Sample C++ code to demonstrate the// incorrect syntax of declaring a member// function as deletedclass C{public: C();}; // Error, the deleted definition // of function C must be the first// declaration of the function.C::C() = delete; What are the advantages of explicitly deleting functions? Deleting of special member functions provides a cleaner way of preventing the compiler from generating special member functions that we don’t want. (As demonstrated in ‘Disabling copy constructors’ example).Deleting of normal member function or non-member functions prevents problematic type promotions from causing an unintended function to be called (As demonstrated in ‘Disabling undesirable argument conversion’ example). Deleting of special member functions provides a cleaner way of preventing the compiler from generating special member functions that we don’t want. (As demonstrated in ‘Disabling copy constructors’ example). Deleting of normal member function or non-member functions prevents problematic type promotions from causing an unintended function to be called (As demonstrated in ‘Disabling undesirable argument conversion’ example). akshaysingh98088 cpp-advanced cpp-constructor C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Operator Overloading in C++ Socket Programming in C/C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples rand() and srand() in C/C++ getline (string) in C++ unordered_map in C++ STL Left Shift and Right Shift Operators in C/C++ C++ Data Types
[ { "code": null, "e": 24207, "s": 24179, "text": "\n06 Jun, 2021" }, { "code": null, "e": 24918, "s": 24207, "text": "What is a Defaulted Function? Explicitly defaulted function declaration is a new form of function declaration that is introduced into the C++11 standard which allows you to append the ‘=default;’ specifier to the end of a function declaration to declare that function as an explicitly defaulted function. This makes the compiler generate the default implementations for explicitly defaulted functions, which are more efficient than manually programmed function implementations. For example, whenever we declare a parameterized constructor, the compiler won’t create a default constructor. In such a case, we can use the default specifier in order to create a default one. The following code demonstrates how: " }, { "code": null, "e": 24922, "s": 24918, "text": "CPP" }, { "code": "// C++ code to demonstrate the// use of defaulted functions#include <iostream>using namespace std; class A {public: // A user-defined // parameterized constructor A(int x) { cout << \"This is a parameterized constructor\"; } // Using the default specifier to instruct // the compiler to create the default // implementation of the constructor. A() = default;}; int main(){ // executes using defaulted constructor A a; // uses parameterized constructor A x(1); return 0;}", "e": 25451, "s": 24922, "text": null }, { "code": null, "e": 25461, "s": 25451, "text": "Output: " }, { "code": null, "e": 25497, "s": 25461, "text": "This is a parameterized constructor" }, { "code": null, "e": 25984, "s": 25497, "text": "In the above case, we didn’t have to specify the body of the constructor A() because, by appending the specifier ‘=default’, the compiler will create a default implementation of this function.What are constrains with making functions defaulted? A defaulted function needs to be a special member function (default constructor, copy constructor, destructor etc), or has no default arguments. For example, the following code explains that non-special member functions can’t be defaulted: " }, { "code": null, "e": 25988, "s": 25984, "text": "CPP" }, { "code": "// C++ code to demonstrate that// non-special member functions// can't be defaultedclass B {public: // Error, func is not a special member function. int func() = default; // Error, constructor B(int, int) is not // a special member function. B(int, int) = default; // Error, constructor B(int=0) // has a default argument. B(int = 0) = default;}; // driver programint main(){ return 0;}", "e": 26409, "s": 25988, "text": null }, { "code": null, "e": 26682, "s": 26409, "text": "What are the advantages of ‘=default’ when we could simply leave an empty body of the function using ‘{}’? Even though the two may behave the same, there are still benefits of using default over leaving an empty body of the constructor. The following points explain how: " }, { "code": null, "e": 27257, "s": 26682, "text": "Giving a user-defined constructor, even though it does nothing, makes the type not an aggregate and also not trivial. If you want your class to be an aggregate or a trivial type (or by transitivity, a POD type), then you need to use ‘= default’.Using ‘= default’ can also be used with copy constructor and destructors. An empty copy constructor, for example, will not do the same as a defaulted copy constructor (which will perform member-wise copy of its members). Using the ‘= default’ syntax uniformly for each of these special member functions makes code easier to read." }, { "code": null, "e": 27503, "s": 27257, "text": "Giving a user-defined constructor, even though it does nothing, makes the type not an aggregate and also not trivial. If you want your class to be an aggregate or a trivial type (or by transitivity, a POD type), then you need to use ‘= default’." }, { "code": null, "e": 27833, "s": 27503, "text": "Using ‘= default’ can also be used with copy constructor and destructors. An empty copy constructor, for example, will not do the same as a defaulted copy constructor (which will perform member-wise copy of its members). Using the ‘= default’ syntax uniformly for each of these special member functions makes code easier to read." }, { "code": null, "e": 28470, "s": 27835, "text": "Prior to C++ 11, the operator delete had only one purpose, to deallocate a memory that has been allocated dynamically. The C++ 11 standard introduced another use of this operator, which is: To disable the usage of a member function. This is done by appending the =delete; specifier to the end of that function declaration.Any member function whose usage has been disabled by using the ‘=delete’ specifier is known as an explicitly deleted function.Although not limited to them, but this is usually done to implicit functions. The following examples exhibit some of the tasks where this feature comes handy:Disabling copy constructors " }, { "code": null, "e": 28474, "s": 28470, "text": "CPP" }, { "code": "// C++ program to disable the usage of// copy-constructor using delete operator#include <iostream>using namespace std; class A {public: A(int x): m(x) { } // Delete the copy constructor A(const A&) = delete; // Delete the copy assignment operator A& operator=(const A&) = delete; int m;}; int main(){ A a1(1), a2(2), a3(3); // Error, the usage of the copy // assignment operator is disabled a1 = a2; // Error, the usage of the // copy constructor is disabled a3 = A(a2); return 0;}", "e": 29024, "s": 28474, "text": null }, { "code": null, "e": 29068, "s": 29024, "text": "Disabling undesirable argument conversion " }, { "code": null, "e": 29072, "s": 29068, "text": "CPP" }, { "code": "// C++ program to disable undesirable argument// type conversion using delete operator#include <iostream>using namespace std; class A {public: A(int) {} // Declare the conversion constructor as a // deleted function. Without this step, // even though A(double) isn't defined, // the A(int) would accept any double value // for it's argumentand convert it to an int A(double) = delete;}; int main(){ A A1(1); // Error, conversion from // double to class A is disabled. A A2(100.1); return 0;}", "e": 29607, "s": 29072, "text": null }, { "code": null, "e": 29854, "s": 29607, "text": "It is very important to note that A deleted function is implicitly inline. A deleted definition of a function must be the first declaration of the function. In other words, the following way is the correct way of declaring a function as deleted: " }, { "code": null, "e": 29903, "s": 29854, "text": "class C \n{\npublic:\n C(C& a) = delete;\n};" }, { "code": null, "e": 29990, "s": 29903, "text": "But the following way of trying to declare a function deleted will produce an error: " }, { "code": null, "e": 29994, "s": 29990, "text": "CPP" }, { "code": "// Sample C++ code to demonstrate the// incorrect syntax of declaring a member// function as deletedclass C{public: C();}; // Error, the deleted definition // of function C must be the first// declaration of the function.C::C() = delete;", "e": 30235, "s": 29994, "text": null }, { "code": null, "e": 30295, "s": 30235, "text": "What are the advantages of explicitly deleting functions? " }, { "code": null, "e": 30721, "s": 30295, "text": "Deleting of special member functions provides a cleaner way of preventing the compiler from generating special member functions that we don’t want. (As demonstrated in ‘Disabling copy constructors’ example).Deleting of normal member function or non-member functions prevents problematic type promotions from causing an unintended function to be called (As demonstrated in ‘Disabling undesirable argument conversion’ example)." }, { "code": null, "e": 30929, "s": 30721, "text": "Deleting of special member functions provides a cleaner way of preventing the compiler from generating special member functions that we don’t want. (As demonstrated in ‘Disabling copy constructors’ example)." }, { "code": null, "e": 31148, "s": 30929, "text": "Deleting of normal member function or non-member functions prevents problematic type promotions from causing an unintended function to be called (As demonstrated in ‘Disabling undesirable argument conversion’ example)." }, { "code": null, "e": 31167, "s": 31150, "text": "akshaysingh98088" }, { "code": null, "e": 31180, "s": 31167, "text": "cpp-advanced" }, { "code": null, "e": 31196, "s": 31180, "text": "cpp-constructor" }, { "code": null, "e": 31200, "s": 31196, "text": "C++" }, { "code": null, "e": 31204, "s": 31200, "text": "CPP" }, { "code": null, "e": 31302, "s": 31204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31326, "s": 31302, "text": "C++ Classes and Objects" }, { "code": null, "e": 31354, "s": 31326, "text": "Operator Overloading in C++" }, { "code": null, "e": 31382, "s": 31354, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31417, "s": 31382, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 31448, "s": 31417, "text": "Templates in C++ with Examples" }, { "code": null, "e": 31476, "s": 31448, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 31500, "s": 31476, "text": "getline (string) in C++" }, { "code": null, "e": 31525, "s": 31500, "text": "unordered_map in C++ STL" }, { "code": null, "e": 31571, "s": 31525, "text": "Left Shift and Right Shift Operators in C/C++" } ]
Check sum of Covered and Uncovered nodes of Binary Tree - GeeksforGeeks
02 Mar, 2022 Given a binary tree, you need to check whether sum of all covered elements is equal to sum of all uncovered elements or not. In a binary tree, a node is called Uncovered if it appears either on left boundary or right boundary. Rest of the nodes are called covered. For example, consider below binary tree In above binary tree, Covered node: 6, 5, 7 Uncovered node: 9, 4, 3, 17, 22, 20 The output for this tree should be false as sum of covered and uncovered node is not same We strongly recommend you to minimize your browser and try this yourself first.For calculating sum of Uncovered nodes we will follow below steps: 1) Start from root, go to left and keep going until left child is available, if not go to right child and again follow same procedure until you reach a leaf node. 2) After step 1 sum of left boundary will be stored, now for right part again do the same procedure but now keep going to right until right child is available, if not then go to left child and follow same procedure until you reach a leaf node.After above 2 steps sum of all Uncovered node will be stored, we can subtract it from total sum and get sum of covered elements and check for equines of binary tree. C++ Java Python3 C# Javascript // C++ program to find sum of Covered and Uncovered node of// binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; /* To create a newNode of tree and return pointer */struct Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} /* Utility function to calculate sum of all node of tree */int sum(Node* t){ if (t == NULL) return 0; return t->key + sum(t->left) + sum(t->right);} /* Recursive function to calculate sum of left boundary elements */int uncoveredSumLeft(Node* t){ /* If leaf node, then just return its key value */ if (t->left == NULL && t->right == NULL) return t->key; /* If left is available then go left otherwise go right */ if (t->left != NULL) return t->key + uncoveredSumLeft(t->left); else return t->key + uncoveredSumLeft(t->right);} /* Recursive function to calculate sum of right boundary elements */int uncoveredSumRight(Node* t){ /* If leaf node, then just return its key value */ if (t->left == NULL && t->right == NULL) return t->key; /* If right is available then go right otherwise go left */ if (t->right != NULL) return t->key + uncoveredSumRight(t->right); else return t->key + uncoveredSumRight(t->left);} // Returns sum of uncovered elementsint uncoverSum(Node* t){ /* Initializing with 0 in case we don't have left or right boundary */ int lb = 0, rb = 0; if (t->left != NULL) lb = uncoveredSumLeft(t->left); if (t->right != NULL) rb = uncoveredSumRight(t->right); /* returning sum of root node, left boundary and right boundary*/ return t->key + lb + rb;} // Returns true if sum of covered and uncovered elements// is same.bool isSumSame(Node *root){ // Sum of uncovered elements int sumUC = uncoverSum(root); // Sum of all elements int sumT = sum(root); // Check if sum of covered and uncovered is same return (sumUC == (sumT - sumUC));} /* Helper function to print inorder traversal of binary tree */void inorder(Node* root){ if (root) { inorder(root->left); printf("%d ", root->key); inorder(root->right); }} // Driver program to test above functionsint main(){ // Making above given diagram's binary tree Node* root = newNode(8); root->left = newNode(3); root->left->left = newNode(1); root->left->right = newNode(6); root->left->right->left = newNode(4); root->left->right->right = newNode(7); root->right = newNode(10); root->right->right = newNode(14); root->right->right->left = newNode(13); if (isSumSame(root)) printf("Sum of covered and uncovered is same\n"); else printf("Sum of covered and uncovered is not same\n");} // Java program to find sum of covered and uncovered nodes// of a binary tree /* A binary tree node has key, pointer to left child and a pointer to right child */class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; /* Utility function to calculate sum of all node of tree */ int sum(Node t) { if (t == null) return 0; return t.key + sum(t.left) + sum(t.right); } /* Recursive function to calculate sum of left boundary elements */ int uncoveredSumLeft(Node t) { /* If left node, then just return its key value */ if (t.left == null && t.right == null) return t.key; /* If left is available then go left otherwise go right */ if (t.left != null) return t.key + uncoveredSumLeft(t.left); else return t.key + uncoveredSumLeft(t.right); } /* Recursive function to calculate sum of right boundary elements */ int uncoveredSumRight(Node t) { /* If left node, then just return its key value */ if (t.left == null && t.right == null) return t.key; /* If right is available then go right otherwise go left */ if (t.right != null) return t.key + uncoveredSumRight(t.right); else return t.key + uncoveredSumRight(t.left); } // Returns sum of uncovered elements int uncoverSum(Node t) { /* Initializing with 0 in case we don't have left or right boundary */ int lb = 0, rb = 0; if (t.left != null) lb = uncoveredSumLeft(t.left); if (t.right != null) rb = uncoveredSumRight(t.right); /* returning sum of root node, left boundary and right boundary*/ return t.key + lb + rb; } // Returns true if sum of covered and uncovered elements // is same. boolean isSumSame(Node root) { // Sum of uncovered elements int sumUC = uncoverSum(root); // Sum of all elements int sumT = sum(root); // Check if sum of covered and uncovered is same return (sumUC == (sumT - sumUC)); } /* Helper function to print inorder traversal of binary tree */ void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.key + " "); inorder(root.right); } } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); if (tree.isSumSame(tree.root)) System.out.println("Sum of covered and uncovered is same"); else System.out.println("Sum of covered and uncovered is not same"); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python3 program to find sum of Covered and# Uncovered node of binary tree # To create a newNode of tree and return pointerclass newNode: def __init__(self, key): self.key = key self.left = self.right = None # Utility function to calculate sum# of all node of treedef Sum(t): if (t == None): return 0 return t.key + Sum(t.left) + Sum(t.right) # Recursive function to calculate sum# of left boundary elementsdef uncoveredSumLeft(t): # If leaf node, then just return # its key value if (t.left == None and t.right == None): return t.key # If left is available then go # left otherwise go right if (t.left != None): return t.key + uncoveredSumLeft(t.left) else: return t.key + uncoveredSumLeft(t.right) # Recursive function to calculate sum of# right boundary elementsdef uncoveredSumRight(t): # If leaf node, then just return # its key value if (t.left == None and t.right == None): return t.key # If right is available then go right # otherwise go left if (t.right != None): return t.key + uncoveredSumRight(t.right) else: return t.key + uncoveredSumRight(t.left) # Returns sum of uncovered elementsdef uncoverSum(t): # Initializing with 0 in case we # don't have left or right boundary lb = 0 rb = 0 if (t.left != None): lb = uncoveredSumLeft(t.left) if (t.right != None): rb = uncoveredSumRight(t.right) # returning sum of root node, # left boundary and right boundary return t.key + lb + rb # Returns true if sum of covered and# uncovered elements is same.def isSumSame(root): # Sum of uncovered elements sumUC = uncoverSum(root) # Sum of all elements sumT = Sum(root) # Check if sum of covered and # uncovered is same return (sumUC == (sumT - sumUC)) # Helper function to print Inorder# traversal of binary treedef inorder(root): if (root): inorder(root.left) print(root.key, end = " ") inorder(root.right) # Driver Codeif __name__ == '__main__': # Making above given diagram's # binary tree root = newNode(8) root.left = newNode(3) root.left.left = newNode(1) root.left.right = newNode(6) root.left.right.left = newNode(4) root.left.right.right = newNode(7) root.right = newNode(10) root.right.right = newNode(14) root.right.right.left = newNode(13) if (isSumSame(root)): print("Sum of covered and uncovered is same") else: print("Sum of covered and uncovered is not same") # This code is contributed by PranchalK // C# program to find sum of covered// and uncovered nodes of a binary treeusing System; /* A binary tree node has key, pointerto left child and a pointer to right child */public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} class GFG{public Node root; /* Utility function to calculatesum of all node of tree */public virtual int sum(Node t){ if (t == null) { return 0; } return t.key + sum(t.left) + sum(t.right);} /* Recursive function to calculatesum of left boundary elements */public virtual int uncoveredSumLeft(Node t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If left is available then go left otherwise go right */ if (t.left != null) { return t.key + uncoveredSumLeft(t.left); } else { return t.key + uncoveredSumLeft(t.right); }} /* Recursive function to calculate sum of right boundary elements */public virtual int uncoveredSumRight(Node t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If right is available then go right otherwise go left */ if (t.right != null) { return t.key + uncoveredSumRight(t.right); } else { return t.key + uncoveredSumRight(t.left); }} // Returns sum of uncovered elementspublic virtual int uncoverSum(Node t){ /* Initializing with 0 in case we don't have left or right boundary */ int lb = 0, rb = 0; if (t.left != null) { lb = uncoveredSumLeft(t.left); } if (t.right != null) { rb = uncoveredSumRight(t.right); } /* returning sum of root node, left boundary and right boundary*/ return t.key + lb + rb;} // Returns true if sum of covered// and uncovered elements is same.public virtual bool isSumSame(Node root){ // Sum of uncovered elements int sumUC = uncoverSum(root); // Sum of all elements int sumT = sum(root); // Check if sum of covered and // uncovered is same return (sumUC == (sumT - sumUC));} /* Helper function to print inordertraversal of binary tree */public virtual void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + " "); inorder(root.right); }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); if (tree.isSumSame(tree.root)) { Console.WriteLine("Sum of covered and " + "uncovered is same"); } else { Console.WriteLine("Sum of covered and " + "uncovered is not same"); }}} // This code is contributed by Shrikant13 <script> // Javascript program to find sum of covered// and uncovered nodes of a binary tree /* A binary tree node has key, pointerto left child and a pointer to right child */class Node{ constructor(key) { this.key = key; this.left= null; this.right = null; }} var root = null; /* Utility function to calculatesum of all node of tree */function sum(t){ if (t == null) { return 0; } return t.key + sum(t.left) + sum(t.right);} /* Recursive function to calculatesum of left boundary elements */function uncoveredSumLeft(t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If left is available then go left otherwise go right */ if (t.left != null) { return t.key + uncoveredSumLeft(t.left); } else { return t.key + uncoveredSumLeft(t.right); }} /* Recursive function to calculate sum of right boundary elements */function uncoveredSumRight(t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If right is available then go right otherwise go left */ if (t.right != null) { return t.key + uncoveredSumRight(t.right); } else { return t.key + uncoveredSumRight(t.left); }} // Returns sum of uncovered elementsfunction uncoverSum(t){ /* Initializing with 0 in case we don't have left or right boundary */ var lb = 0, rb = 0; if (t.left != null) { lb = uncoveredSumLeft(t.left); } if (t.right != null) { rb = uncoveredSumRight(t.right); } /* returning sum of root node, left boundary and right boundary*/ return t.key + lb + rb;} // Returns true if sum of covered// and uncovered elements is same.function isSumSame(root){ // Sum of uncovered elements var sumUC = uncoverSum(root); // Sum of all elements var sumT = sum(root); // Check if sum of covered and // uncovered is same return (sumUC == (sumT - sumUC));} /* Helper function to print inordertraversal of binary tree */function inorder(root){ if (root != null) { inorder(root.left); document.write(root.key + " "); inorder(root.right); }} // Driver Code// Making above given diagram's binary treevar root = new Node(8);root.left = new Node(3);root.left.left = new Node(1);root.left.right = new Node(6);root.left.right.left = new Node(4);root.left.right.right = new Node(7);root.right = new Node(10);root.right.right = new Node(14);root.right.right.left = new Node(13);if (isSumSame(root)){ document.write("Sum of covered and " + "uncovered is same");}else{ document.write("Sum of covered and " + "uncovered is not same");} // This code is contributed by itsok </script> Output : Sum of covered and uncovered is not same YouTubeGeeksforGeeks502K subscribersCheck sum of Covered and Uncovered nodes of Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hRk4in1Rg_M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above MayankShorey shrikanth13 PranchalKatiyar Akanksha_Rai itsok simmytarika5 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 BFS vs DFS for Binary Tree
[ { "code": null, "e": 25326, "s": 25298, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25592, "s": 25326, "text": "Given a binary tree, you need to check whether sum of all covered elements is equal to sum of all uncovered elements or not. In a binary tree, a node is called Uncovered if it appears either on left boundary or right boundary. Rest of the nodes are called covered. " }, { "code": null, "e": 25632, "s": 25592, "text": "For example, consider below binary tree" }, { "code": null, "e": 25810, "s": 25632, "text": "In above binary tree,\nCovered node: 6, 5, 7\nUncovered node: 9, 4, 3, 17, 22, 20\n\nThe output for this tree should be false as \nsum of covered and uncovered node is not same" }, { "code": null, "e": 26119, "s": 25810, "text": "We strongly recommend you to minimize your browser and try this yourself first.For calculating sum of Uncovered nodes we will follow below steps: 1) Start from root, go to left and keep going until left child is available, if not go to right child and again follow same procedure until you reach a leaf node." }, { "code": null, "e": 26528, "s": 26119, "text": "2) After step 1 sum of left boundary will be stored, now for right part again do the same procedure but now keep going to right until right child is available, if not then go to left child and follow same procedure until you reach a leaf node.After above 2 steps sum of all Uncovered node will be stored, we can subtract it from total sum and get sum of covered elements and check for equines of binary tree." }, { "code": null, "e": 26532, "s": 26528, "text": "C++" }, { "code": null, "e": 26537, "s": 26532, "text": "Java" }, { "code": null, "e": 26545, "s": 26537, "text": "Python3" }, { "code": null, "e": 26548, "s": 26545, "text": "C#" }, { "code": null, "e": 26559, "s": 26548, "text": "Javascript" }, { "code": "// C++ program to find sum of Covered and Uncovered node of// binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; /* To create a newNode of tree and return pointer */struct Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} /* Utility function to calculate sum of all node of tree */int sum(Node* t){ if (t == NULL) return 0; return t->key + sum(t->left) + sum(t->right);} /* Recursive function to calculate sum of left boundary elements */int uncoveredSumLeft(Node* t){ /* If leaf node, then just return its key value */ if (t->left == NULL && t->right == NULL) return t->key; /* If left is available then go left otherwise go right */ if (t->left != NULL) return t->key + uncoveredSumLeft(t->left); else return t->key + uncoveredSumLeft(t->right);} /* Recursive function to calculate sum of right boundary elements */int uncoveredSumRight(Node* t){ /* If leaf node, then just return its key value */ if (t->left == NULL && t->right == NULL) return t->key; /* If right is available then go right otherwise go left */ if (t->right != NULL) return t->key + uncoveredSumRight(t->right); else return t->key + uncoveredSumRight(t->left);} // Returns sum of uncovered elementsint uncoverSum(Node* t){ /* Initializing with 0 in case we don't have left or right boundary */ int lb = 0, rb = 0; if (t->left != NULL) lb = uncoveredSumLeft(t->left); if (t->right != NULL) rb = uncoveredSumRight(t->right); /* returning sum of root node, left boundary and right boundary*/ return t->key + lb + rb;} // Returns true if sum of covered and uncovered elements// is same.bool isSumSame(Node *root){ // Sum of uncovered elements int sumUC = uncoverSum(root); // Sum of all elements int sumT = sum(root); // Check if sum of covered and uncovered is same return (sumUC == (sumT - sumUC));} /* Helper function to print inorder traversal of binary tree */void inorder(Node* root){ if (root) { inorder(root->left); printf(\"%d \", root->key); inorder(root->right); }} // Driver program to test above functionsint main(){ // Making above given diagram's binary tree Node* root = newNode(8); root->left = newNode(3); root->left->left = newNode(1); root->left->right = newNode(6); root->left->right->left = newNode(4); root->left->right->right = newNode(7); root->right = newNode(10); root->right->right = newNode(14); root->right->right->left = newNode(13); if (isSumSame(root)) printf(\"Sum of covered and uncovered is same\\n\"); else printf(\"Sum of covered and uncovered is not same\\n\");}", "e": 29500, "s": 26559, "text": null }, { "code": "// Java program to find sum of covered and uncovered nodes// of a binary tree /* A binary tree node has key, pointer to left child and a pointer to right child */class Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} class BinaryTree{ Node root; /* Utility function to calculate sum of all node of tree */ int sum(Node t) { if (t == null) return 0; return t.key + sum(t.left) + sum(t.right); } /* Recursive function to calculate sum of left boundary elements */ int uncoveredSumLeft(Node t) { /* If left node, then just return its key value */ if (t.left == null && t.right == null) return t.key; /* If left is available then go left otherwise go right */ if (t.left != null) return t.key + uncoveredSumLeft(t.left); else return t.key + uncoveredSumLeft(t.right); } /* Recursive function to calculate sum of right boundary elements */ int uncoveredSumRight(Node t) { /* If left node, then just return its key value */ if (t.left == null && t.right == null) return t.key; /* If right is available then go right otherwise go left */ if (t.right != null) return t.key + uncoveredSumRight(t.right); else return t.key + uncoveredSumRight(t.left); } // Returns sum of uncovered elements int uncoverSum(Node t) { /* Initializing with 0 in case we don't have left or right boundary */ int lb = 0, rb = 0; if (t.left != null) lb = uncoveredSumLeft(t.left); if (t.right != null) rb = uncoveredSumRight(t.right); /* returning sum of root node, left boundary and right boundary*/ return t.key + lb + rb; } // Returns true if sum of covered and uncovered elements // is same. boolean isSumSame(Node root) { // Sum of uncovered elements int sumUC = uncoverSum(root); // Sum of all elements int sumT = sum(root); // Check if sum of covered and uncovered is same return (sumUC == (sumT - sumUC)); } /* Helper function to print inorder traversal of binary tree */ void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.key + \" \"); inorder(root.right); } } // Driver program to test above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); if (tree.isSumSame(tree.root)) System.out.println(\"Sum of covered and uncovered is same\"); else System.out.println(\"Sum of covered and uncovered is not same\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 32858, "s": 29500, "text": null }, { "code": "# Python3 program to find sum of Covered and# Uncovered node of binary tree # To create a newNode of tree and return pointerclass newNode: def __init__(self, key): self.key = key self.left = self.right = None # Utility function to calculate sum# of all node of treedef Sum(t): if (t == None): return 0 return t.key + Sum(t.left) + Sum(t.right) # Recursive function to calculate sum# of left boundary elementsdef uncoveredSumLeft(t): # If leaf node, then just return # its key value if (t.left == None and t.right == None): return t.key # If left is available then go # left otherwise go right if (t.left != None): return t.key + uncoveredSumLeft(t.left) else: return t.key + uncoveredSumLeft(t.right) # Recursive function to calculate sum of# right boundary elementsdef uncoveredSumRight(t): # If leaf node, then just return # its key value if (t.left == None and t.right == None): return t.key # If right is available then go right # otherwise go left if (t.right != None): return t.key + uncoveredSumRight(t.right) else: return t.key + uncoveredSumRight(t.left) # Returns sum of uncovered elementsdef uncoverSum(t): # Initializing with 0 in case we # don't have left or right boundary lb = 0 rb = 0 if (t.left != None): lb = uncoveredSumLeft(t.left) if (t.right != None): rb = uncoveredSumRight(t.right) # returning sum of root node, # left boundary and right boundary return t.key + lb + rb # Returns true if sum of covered and# uncovered elements is same.def isSumSame(root): # Sum of uncovered elements sumUC = uncoverSum(root) # Sum of all elements sumT = Sum(root) # Check if sum of covered and # uncovered is same return (sumUC == (sumT - sumUC)) # Helper function to print Inorder# traversal of binary treedef inorder(root): if (root): inorder(root.left) print(root.key, end = \" \") inorder(root.right) # Driver Codeif __name__ == '__main__': # Making above given diagram's # binary tree root = newNode(8) root.left = newNode(3) root.left.left = newNode(1) root.left.right = newNode(6) root.left.right.left = newNode(4) root.left.right.right = newNode(7) root.right = newNode(10) root.right.right = newNode(14) root.right.right.left = newNode(13) if (isSumSame(root)): print(\"Sum of covered and uncovered is same\") else: print(\"Sum of covered and uncovered is not same\") # This code is contributed by PranchalK", "e": 35472, "s": 32858, "text": null }, { "code": "// C# program to find sum of covered// and uncovered nodes of a binary treeusing System; /* A binary tree node has key, pointerto left child and a pointer to right child */public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} class GFG{public Node root; /* Utility function to calculatesum of all node of tree */public virtual int sum(Node t){ if (t == null) { return 0; } return t.key + sum(t.left) + sum(t.right);} /* Recursive function to calculatesum of left boundary elements */public virtual int uncoveredSumLeft(Node t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If left is available then go left otherwise go right */ if (t.left != null) { return t.key + uncoveredSumLeft(t.left); } else { return t.key + uncoveredSumLeft(t.right); }} /* Recursive function to calculate sum of right boundary elements */public virtual int uncoveredSumRight(Node t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If right is available then go right otherwise go left */ if (t.right != null) { return t.key + uncoveredSumRight(t.right); } else { return t.key + uncoveredSumRight(t.left); }} // Returns sum of uncovered elementspublic virtual int uncoverSum(Node t){ /* Initializing with 0 in case we don't have left or right boundary */ int lb = 0, rb = 0; if (t.left != null) { lb = uncoveredSumLeft(t.left); } if (t.right != null) { rb = uncoveredSumRight(t.right); } /* returning sum of root node, left boundary and right boundary*/ return t.key + lb + rb;} // Returns true if sum of covered// and uncovered elements is same.public virtual bool isSumSame(Node root){ // Sum of uncovered elements int sumUC = uncoverSum(root); // Sum of all elements int sumT = sum(root); // Check if sum of covered and // uncovered is same return (sumUC == (sumT - sumUC));} /* Helper function to print inordertraversal of binary tree */public virtual void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + \" \"); inorder(root.right); }} // Driver Codepublic static void Main(string[] args){ GFG tree = new GFG(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); if (tree.isSumSame(tree.root)) { Console.WriteLine(\"Sum of covered and \" + \"uncovered is same\"); } else { Console.WriteLine(\"Sum of covered and \" + \"uncovered is not same\"); }}} // This code is contributed by Shrikant13", "e": 38711, "s": 35472, "text": null }, { "code": "<script> // Javascript program to find sum of covered// and uncovered nodes of a binary tree /* A binary tree node has key, pointerto left child and a pointer to right child */class Node{ constructor(key) { this.key = key; this.left= null; this.right = null; }} var root = null; /* Utility function to calculatesum of all node of tree */function sum(t){ if (t == null) { return 0; } return t.key + sum(t.left) + sum(t.right);} /* Recursive function to calculatesum of left boundary elements */function uncoveredSumLeft(t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If left is available then go left otherwise go right */ if (t.left != null) { return t.key + uncoveredSumLeft(t.left); } else { return t.key + uncoveredSumLeft(t.right); }} /* Recursive function to calculate sum of right boundary elements */function uncoveredSumRight(t){ /* If left node, then just return its key value */ if (t.left == null && t.right == null) { return t.key; } /* If right is available then go right otherwise go left */ if (t.right != null) { return t.key + uncoveredSumRight(t.right); } else { return t.key + uncoveredSumRight(t.left); }} // Returns sum of uncovered elementsfunction uncoverSum(t){ /* Initializing with 0 in case we don't have left or right boundary */ var lb = 0, rb = 0; if (t.left != null) { lb = uncoveredSumLeft(t.left); } if (t.right != null) { rb = uncoveredSumRight(t.right); } /* returning sum of root node, left boundary and right boundary*/ return t.key + lb + rb;} // Returns true if sum of covered// and uncovered elements is same.function isSumSame(root){ // Sum of uncovered elements var sumUC = uncoverSum(root); // Sum of all elements var sumT = sum(root); // Check if sum of covered and // uncovered is same return (sumUC == (sumT - sumUC));} /* Helper function to print inordertraversal of binary tree */function inorder(root){ if (root != null) { inorder(root.left); document.write(root.key + \" \"); inorder(root.right); }} // Driver Code// Making above given diagram's binary treevar root = new Node(8);root.left = new Node(3);root.left.left = new Node(1);root.left.right = new Node(6);root.left.right.left = new Node(4);root.left.right.right = new Node(7);root.right = new Node(10);root.right.right = new Node(14);root.right.right.left = new Node(13);if (isSumSame(root)){ document.write(\"Sum of covered and \" + \"uncovered is same\");}else{ document.write(\"Sum of covered and \" + \"uncovered is not same\");} // This code is contributed by itsok </script>", "e": 41633, "s": 38711, "text": null }, { "code": null, "e": 41643, "s": 41633, "text": "Output : " }, { "code": null, "e": 41686, "s": 41643, "text": "Sum of covered and uncovered is not same\n " }, { "code": null, "e": 42540, "s": 41686, "text": "YouTubeGeeksforGeeks502K subscribersCheck sum of Covered and Uncovered nodes of Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:00•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hRk4in1Rg_M\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 42714, "s": 42542, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 42729, "s": 42716, "text": "MayankShorey" }, { "code": null, "e": 42741, "s": 42729, "text": "shrikanth13" }, { "code": null, "e": 42757, "s": 42741, "text": "PranchalKatiyar" }, { "code": null, "e": 42770, "s": 42757, "text": "Akanksha_Rai" }, { "code": null, "e": 42776, "s": 42770, "text": "itsok" }, { "code": null, "e": 42789, "s": 42776, "text": "simmytarika5" }, { "code": null, "e": 42794, "s": 42789, "text": "Tree" }, { "code": null, "e": 42799, "s": 42794, "text": "Tree" }, { "code": null, "e": 42897, "s": 42799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42938, "s": 42897, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 42981, "s": 42938, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 43014, "s": 42981, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 43028, "s": 43014, "text": "Decision Tree" }, { "code": null, "e": 43078, "s": 43028, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 43161, "s": 43078, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 43219, "s": 43161, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 43255, "s": 43219, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 43303, "s": 43255, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
How to get input value search box and enter it in AngularJS component using Enter key ? - GeeksforGeeks
12 Mar, 2021 To implement a search component in AngularJS which calls the function whenever the user presses the enter key(keyCode = 13) and then does some relatable task from the user input. This can be achieved easily using the keyup event. Here for styling purpose, bootstrap and font awesome are being used. We need a basic input tag that will have a keyup event that calls an onSubmit($event) function and pass event as an argument. The $event gives us different types of property but we are going to take the help of keyCode which tells us which key is pressed by the user. We use the keyCode to check whether the user has pressed the Enter key whose code is 13. Once the Enter key is pressed you can perform the task that you want such as searching from a list or passing the search element to another component. For simplicity, We have created a small array that checks for the search element inside the array and outputs the results. Example: app.component.html <div class="container"> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <h3>Programming Languages</h3> <div class="searchBox"> <input (keyup)="onSubmit($event)" [(ngModel)]="searchValue" type="text" id="searchKey" class="form-control" placeholder="Search Box" /> </div> <div *ngIf="condition; then block1; else block2"> </div> <ng-template #block1> <i class="fa fa-spinner fa-spin" aria-hidden="true"> </i> Searching your results for <strong>{{prevText}}</strong> </ng-template> <ng-template #block2> <h6>{{res_cnt}} Search Result Found <span *ngFor="let lang of res_list"> <strong>{{lang}}, </strong></span> </h6> </ng-template> </div> </div></div> app.component.css .searchBox{ margin: 20px 0;} input{ width: 100%; padding: 10px; text-align: center;} app.component.ts import { Component } from '@angular/core';import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', template: './app.component.html', styles: ['./app.component.css']})export class AppComponent { searchValue: string = null; condition: boolean = null; prevText: string = ''; list_lang = ['java', 'c++', 'python', 'c', 'javascript']; res_list = []; res_cnt: number = 0; onSubmit($event){ if($event.keyCode === 13){ this.condition = true; this.prevText = this.searchValue; this.res_cnt = 0; this.res_list = []; setTimeout(() => { this.condition = false; for(let i=0; i<this.list_lang.length; i++){ if(this.list_lang[i] === this.prevText.toLowerCase() || this.list_lang[i].startsWith(this.prevText)){ this.res_cnt += 1; this.res_list.push(this.list_lang[i]); } } }, 3000); this.searchValue = null; } }} Output Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. AngularJS-Questions Picked Technical Scripter 2020 AngularJS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular 10 (blur) Event Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n12 Mar, 2021" }, { "code": null, "e": 25339, "s": 25109, "text": "To implement a search component in AngularJS which calls the function whenever the user presses the enter key(keyCode = 13) and then does some relatable task from the user input. This can be achieved easily using the keyup event." }, { "code": null, "e": 25408, "s": 25339, "text": "Here for styling purpose, bootstrap and font awesome are being used." }, { "code": null, "e": 26039, "s": 25408, "text": "We need a basic input tag that will have a keyup event that calls an onSubmit($event) function and pass event as an argument. The $event gives us different types of property but we are going to take the help of keyCode which tells us which key is pressed by the user. We use the keyCode to check whether the user has pressed the Enter key whose code is 13. Once the Enter key is pressed you can perform the task that you want such as searching from a list or passing the search element to another component. For simplicity, We have created a small array that checks for the search element inside the array and outputs the results." }, { "code": null, "e": 26048, "s": 26039, "text": "Example:" }, { "code": null, "e": 26067, "s": 26048, "text": "app.component.html" }, { "code": "<div class=\"container\"> <div class=\"row\"> <div class=\"col-md-4\"></div> <div class=\"col-md-4\"> <h3>Programming Languages</h3> <div class=\"searchBox\"> <input (keyup)=\"onSubmit($event)\" [(ngModel)]=\"searchValue\" type=\"text\" id=\"searchKey\" class=\"form-control\" placeholder=\"Search Box\" /> </div> <div *ngIf=\"condition; then block1; else block2\"> </div> <ng-template #block1> <i class=\"fa fa-spinner fa-spin\" aria-hidden=\"true\"> </i> Searching your results for <strong>{{prevText}}</strong> </ng-template> <ng-template #block2> <h6>{{res_cnt}} Search Result Found <span *ngFor=\"let lang of res_list\"> <strong>{{lang}}, </strong></span> </h6> </ng-template> </div> </div></div>", "e": 26894, "s": 26067, "text": null }, { "code": null, "e": 26912, "s": 26894, "text": "app.component.css" }, { "code": ".searchBox{ margin: 20px 0;} input{ width: 100%; padding: 10px; text-align: center;}", "e": 27009, "s": 26912, "text": null }, { "code": null, "e": 27026, "s": 27009, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', template: './app.component.html', styles: ['./app.component.css']})export class AppComponent { searchValue: string = null; condition: boolean = null; prevText: string = ''; list_lang = ['java', 'c++', 'python', 'c', 'javascript']; res_list = []; res_cnt: number = 0; onSubmit($event){ if($event.keyCode === 13){ this.condition = true; this.prevText = this.searchValue; this.res_cnt = 0; this.res_list = []; setTimeout(() => { this.condition = false; for(let i=0; i<this.list_lang.length; i++){ if(this.list_lang[i] === this.prevText.toLowerCase() || this.list_lang[i].startsWith(this.prevText)){ this.res_cnt += 1; this.res_list.push(this.list_lang[i]); } } }, 3000); this.searchValue = null; } }}", "e": 28011, "s": 27026, "text": null }, { "code": null, "e": 28018, "s": 28011, "text": "Output" }, { "code": null, "e": 28155, "s": 28018, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28175, "s": 28155, "text": "AngularJS-Questions" }, { "code": null, "e": 28182, "s": 28175, "text": "Picked" }, { "code": null, "e": 28206, "s": 28182, "text": "Technical Scripter 2020" }, { "code": null, "e": 28216, "s": 28206, "text": "AngularJS" }, { "code": null, "e": 28221, "s": 28216, "text": "HTML" }, { "code": null, "e": 28240, "s": 28221, "text": "Technical Scripter" }, { "code": null, "e": 28257, "s": 28240, "text": "Web Technologies" }, { "code": null, "e": 28262, "s": 28257, "text": "HTML" }, { "code": null, "e": 28360, "s": 28262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28404, "s": 28360, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28428, "s": 28404, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28463, "s": 28428, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28516, "s": 28463, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28565, "s": 28516, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 28615, "s": 28565, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28677, "s": 28615, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28737, "s": 28677, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28785, "s": 28737, "text": "How to update Node.js and NPM to next version ?" } ]
How to calculate power of three using C#?
For power of 3, se the power as 3 and apply a recursive code like the following snippet − if (p!=0) { return (n * power(n, p - 1)); } Let’s say the number is 5, then the iterations would be − power(5, 3 - 1)); // 25 power (5,2-1): // 5 The above would return5*25 i.e 125 as shown below − Live Demo using System; using System.IO; public class Demo { public static void Main(string[] args) { int n = 5; int p = 3; long res; res = power(n, p); Console.WriteLine(res); } static long power (int n, int p) { if (p!=0) { return (n * power(n, p - 1)); } return 1; } } 125
[ { "code": null, "e": 1152, "s": 1062, "text": "For power of 3, se the power as 3 and apply a recursive code like the following snippet −" }, { "code": null, "e": 1196, "s": 1152, "text": "if (p!=0) {\nreturn (n * power(n, p - 1));\n}" }, { "code": null, "e": 1254, "s": 1196, "text": "Let’s say the number is 5, then the iterations would be −" }, { "code": null, "e": 1298, "s": 1254, "text": "power(5, 3 - 1)); // 25\npower (5,2-1): // 5" }, { "code": null, "e": 1350, "s": 1298, "text": "The above would return5*25 i.e 125 as shown below −" }, { "code": null, "e": 1361, "s": 1350, "text": " Live Demo" }, { "code": null, "e": 1693, "s": 1361, "text": "using System;\nusing System.IO;\n\npublic class Demo {\n public static void Main(string[] args) {\n int n = 5;\n int p = 3;\n long res;\n res = power(n, p);\n Console.WriteLine(res);\n }\n static long power (int n, int p) {\n if (p!=0) {\n return (n * power(n, p - 1));\n }\n return 1;\n }\n}" }, { "code": null, "e": 1697, "s": 1693, "text": "125" } ]
Why would we call cin.clear() and cin.ignore() after reading input in C++?
In C++ the cin is used to take input from user. Sometimes for some reasons some error flags are set. In that time the cin does not take any input. Sometimes it takes some other characters. So if we clear the cin, then the error flags are reset. Then we can use getline(), get() etc. functions. The ignore() function is another stream input function. If we write the function like this cin.ignore(1000, ‘\n’) Then it will ignore next 1000 characters, otherwise ignore lines until ‘\n’ is found.
[ { "code": null, "e": 1356, "s": 1062, "text": "In C++ the cin is used to take input from user. Sometimes for some reasons some error flags are set. In that time the cin does not take any input. Sometimes it takes some other characters. So if we clear the cin, then the error flags are reset. Then we can use getline(), get() etc. functions." }, { "code": null, "e": 1447, "s": 1356, "text": "The ignore() function is another stream input function. If we write the function like this" }, { "code": null, "e": 1470, "s": 1447, "text": "cin.ignore(1000, ‘\\n’)" }, { "code": null, "e": 1556, "s": 1470, "text": "Then it will ignore next 1000 characters, otherwise ignore lines until ‘\\n’ is found." } ]
Reshape R dataframes wide to long | Towards Data Science
How do you reshape a dataframe from wide to long form in R? How does the melt() function reshape dataframes in R? This tutorial will walk you through reshaping dataframes using the melt function in R. If you’re reshaping dataframes or arrays in Python, check out my tutorials below. towardsdatascience.com towardsdatascience.com towardsdatascience.com Common terms for this wide-to-long transformation are melt, pivot-long, unpivot, gather, stack, and reshape. Many functions have been written to convert data from wide to long form, melt() from the data.table library is the best. See melt() documentation here. Why? Python’s pandas library also has the equivalent melt function/method that works the same way (see my pandas melt tutorial here) melt alone is often enough for all your wide-to-long transformations; you won’t have to learn pivot_longer or gather Other functions like gather and pivot_longer are often just wrapper functions for melt() or reshape()— these other functions simplify melt and often can’t deal with more complex transformations. melt is more powerful but isn’t any more complicated than the other functions. data.table package’s implementation of melt, which is extremely powerful—much more efficient and powerful than the reshape library’s melt function. From the documentation: The melt and dcast functions for data.tables are for reshaping wide-to-long and long-to-wide, respectively; the implementations are specifically designed with large in-memory data (e.g. 10Gb) in mind. Reminder: We’re using melt from the data.table library, not reshape library! Compare the documentation of the melt functions from the two libraries to the differences: ?data.table::melt and ?reshape::melt It’s easiest to understand what a wide dataframe is or looks like if we look at one and compare it with a long dataframe. And below is the corresponding dataframe (with the same information) but in the long form: Before we begin our melt tutorial, let’s recreate the wide dataframe above. df_wide <- data.table( student = c("Andy", "Bernie", "Cindey", "Deb"), school = c("Z", "Y", "Z", "Y"), english = c(10, 100, 1000, 10000), # eng grades math = c(20, 200, 2000, 20000), # math grades physics = c(30, 300, 3000, 30000) # physics grades)df_wide student school english math physics1: Andy Z 10 20 302: Bernie Y 100 200 3003: Cindey Z 1000 2000 30004: Deb Y 10000 20000 30000 Note that I like to use data.table instead of data.frame because data.table objects are much more powerful. If you data isn’t a data.table (check by running class(your_dataframe) in your console), I highly recommend you convert it to a data.table. class(df_wide) # data.table and data.frame[1] "data.table" "data.frame" Simply load the data.table library and use the setDT function from the data.table library to convert any data.frameto a data.table. setDT(df_wide) # no reassignment required! We melt by specifying the identifier columns via id.vars. The “leftover” non-identifier columns (english, math, physics) will be melted or stacked onto each other into one column. A new indicator column will be created (contains values english, math, physics) and we can rename this new column (cLaSs) via variable.name. We can also rename the column in which all the actual grades are contained (gRaDe) via value.name. df_long <- melt(data = df_wide, id.vars = c("student", "school"), variable.name = "cLaSs", value.name = "gRaDe")df_long student school cLaSs gRaDe 1: Andy Z english 10 2: Bernie Y english 100 3: Cindey Z english 1000 4: Deb Y english 10000 5: Andy Z math 20 6: Bernie Y math 200 7: Cindey Z math 2000 8: Deb Y math 20000 9: Andy Z physics 3010: Bernie Y physics 30011: Cindey Z physics 300012: Deb Y physics 30000 You can use measure.vars to specify which columns you want to melt or stack into column (here, we exclude physics column, so measure.vars = c("english", "math")). We also drop the school column from id.vars. df_long <- melt(data = df_wide, id.vars = "student", measure.vars = c("english", "math"), variable.name = "cLaSs", value.name = "gRaDe")df_long student cLaSs gRaDe1: Andy english 102: Bernie english 1003: Cindey english 10004: Deb english 100005: Andy math 206: Bernie math 2007: Cindey math 20008: Deb math 20000 Finally, let’s see what happens if we specify only the student column as the identifier column (id.vars = "student") but do not specify which columns you want to stack via measure.vars. As a result, all non-identifier columns (school, english, math, physics) will be stacked into one column. The resulting long dataframe looks wrong because now the cLaSs and gRaDe columns contain values that shouldn’t be there. The point here is to show you how melt works. df_long <- melt(data = df_wide, id.vars = "student", variable.name = "cLaSs", value.name = "gRaDe")df_long student cLaSs gRaDe 1: Andy school Z 2: Bernie school Y 3: Cindey school Z 4: Deb school Y 5: Andy english 10 6: Bernie english 100 7: Cindey english 1000 8: Deb english 10000 9: Andy math 2010: Bernie math 20011: Cindey math 200012: Deb math 2000013: Andy physics 3014: Bernie physics 30015: Cindey physics 300016: Deb physics 30000 This table looks wrong because the school column in df_wide doesn’t belong—school should be another identifier column (see Melt 1 above). The melt function also also returned a warning message that tells you your column (gRaDe) have values of different types (i.e., character and numeric). I hope now you have a better understanding of how melt performs wide-to-long transformations. I look forward to your thoughts and comments. If you find this post useful, follow me and visit my site for more data science tutorials and also my other articles: towardsdatascience.com towardsdatascience.com For more posts, subscribe to my mailing list.
[ { "code": null, "e": 373, "s": 172, "text": "How do you reshape a dataframe from wide to long form in R? How does the melt() function reshape dataframes in R? This tutorial will walk you through reshaping dataframes using the melt function in R." }, { "code": null, "e": 455, "s": 373, "text": "If you’re reshaping dataframes or arrays in Python, check out my tutorials below." }, { "code": null, "e": 478, "s": 455, "text": "towardsdatascience.com" }, { "code": null, "e": 501, "s": 478, "text": "towardsdatascience.com" }, { "code": null, "e": 524, "s": 501, "text": "towardsdatascience.com" }, { "code": null, "e": 790, "s": 524, "text": "Common terms for this wide-to-long transformation are melt, pivot-long, unpivot, gather, stack, and reshape. Many functions have been written to convert data from wide to long form, melt() from the data.table library is the best. See melt() documentation here. Why?" }, { "code": null, "e": 918, "s": 790, "text": "Python’s pandas library also has the equivalent melt function/method that works the same way (see my pandas melt tutorial here)" }, { "code": null, "e": 1035, "s": 918, "text": "melt alone is often enough for all your wide-to-long transformations; you won’t have to learn pivot_longer or gather" }, { "code": null, "e": 1230, "s": 1035, "text": "Other functions like gather and pivot_longer are often just wrapper functions for melt() or reshape()— these other functions simplify melt and often can’t deal with more complex transformations." }, { "code": null, "e": 1309, "s": 1230, "text": "melt is more powerful but isn’t any more complicated than the other functions." }, { "code": null, "e": 1481, "s": 1309, "text": "data.table package’s implementation of melt, which is extremely powerful—much more efficient and powerful than the reshape library’s melt function. From the documentation:" }, { "code": null, "e": 1682, "s": 1481, "text": "The melt and dcast functions for data.tables are for reshaping wide-to-long and long-to-wide, respectively; the implementations are specifically designed with large in-memory data (e.g. 10Gb) in mind." }, { "code": null, "e": 1887, "s": 1682, "text": "Reminder: We’re using melt from the data.table library, not reshape library! Compare the documentation of the melt functions from the two libraries to the differences: ?data.table::melt and ?reshape::melt" }, { "code": null, "e": 2009, "s": 1887, "text": "It’s easiest to understand what a wide dataframe is or looks like if we look at one and compare it with a long dataframe." }, { "code": null, "e": 2100, "s": 2009, "text": "And below is the corresponding dataframe (with the same information) but in the long form:" }, { "code": null, "e": 2176, "s": 2100, "text": "Before we begin our melt tutorial, let’s recreate the wide dataframe above." }, { "code": null, "e": 2638, "s": 2176, "text": "df_wide <- data.table( student = c(\"Andy\", \"Bernie\", \"Cindey\", \"Deb\"), school = c(\"Z\", \"Y\", \"Z\", \"Y\"), english = c(10, 100, 1000, 10000), # eng grades math = c(20, 200, 2000, 20000), # math grades physics = c(30, 300, 3000, 30000) # physics grades)df_wide student school english math physics1: Andy Z 10 20 302: Bernie Y 100 200 3003: Cindey Z 1000 2000 30004: Deb Y 10000 20000 30000" }, { "code": null, "e": 2886, "s": 2638, "text": "Note that I like to use data.table instead of data.frame because data.table objects are much more powerful. If you data isn’t a data.table (check by running class(your_dataframe) in your console), I highly recommend you convert it to a data.table." }, { "code": null, "e": 2958, "s": 2886, "text": "class(df_wide) # data.table and data.frame[1] \"data.table\" \"data.frame\"" }, { "code": null, "e": 3090, "s": 2958, "text": "Simply load the data.table library and use the setDT function from the data.table library to convert any data.frameto a data.table." }, { "code": null, "e": 3134, "s": 3090, "text": "setDT(df_wide) # no reassignment required! " }, { "code": null, "e": 3314, "s": 3134, "text": "We melt by specifying the identifier columns via id.vars. The “leftover” non-identifier columns (english, math, physics) will be melted or stacked onto each other into one column." }, { "code": null, "e": 3554, "s": 3314, "text": "A new indicator column will be created (contains values english, math, physics) and we can rename this new column (cLaSs) via variable.name. We can also rename the column in which all the actual grades are contained (gRaDe) via value.name." }, { "code": null, "e": 4136, "s": 3554, "text": "df_long <- melt(data = df_wide, id.vars = c(\"student\", \"school\"), variable.name = \"cLaSs\", value.name = \"gRaDe\")df_long student school cLaSs gRaDe 1: Andy Z english 10 2: Bernie Y english 100 3: Cindey Z english 1000 4: Deb Y english 10000 5: Andy Z math 20 6: Bernie Y math 200 7: Cindey Z math 2000 8: Deb Y math 20000 9: Andy Z physics 3010: Bernie Y physics 30011: Cindey Z physics 300012: Deb Y physics 30000" }, { "code": null, "e": 4344, "s": 4136, "text": "You can use measure.vars to specify which columns you want to melt or stack into column (here, we exclude physics column, so measure.vars = c(\"english\", \"math\")). We also drop the school column from id.vars." }, { "code": null, "e": 4765, "s": 4344, "text": "df_long <- melt(data = df_wide, id.vars = \"student\", measure.vars = c(\"english\", \"math\"), variable.name = \"cLaSs\", value.name = \"gRaDe\")df_long student cLaSs gRaDe1: Andy english 102: Bernie english 1003: Cindey english 10004: Deb english 100005: Andy math 206: Bernie math 2007: Cindey math 20008: Deb math 20000" }, { "code": null, "e": 5057, "s": 4765, "text": "Finally, let’s see what happens if we specify only the student column as the identifier column (id.vars = \"student\") but do not specify which columns you want to stack via measure.vars. As a result, all non-identifier columns (school, english, math, physics) will be stacked into one column." }, { "code": null, "e": 5224, "s": 5057, "text": "The resulting long dataframe looks wrong because now the cLaSs and gRaDe columns contain values that shouldn’t be there. The point here is to show you how melt works." }, { "code": null, "e": 5801, "s": 5224, "text": "df_long <- melt(data = df_wide, id.vars = \"student\", variable.name = \"cLaSs\", value.name = \"gRaDe\")df_long student cLaSs gRaDe 1: Andy school Z 2: Bernie school Y 3: Cindey school Z 4: Deb school Y 5: Andy english 10 6: Bernie english 100 7: Cindey english 1000 8: Deb english 10000 9: Andy math 2010: Bernie math 20011: Cindey math 200012: Deb math 2000013: Andy physics 3014: Bernie physics 30015: Cindey physics 300016: Deb physics 30000" }, { "code": null, "e": 6091, "s": 5801, "text": "This table looks wrong because the school column in df_wide doesn’t belong—school should be another identifier column (see Melt 1 above). The melt function also also returned a warning message that tells you your column (gRaDe) have values of different types (i.e., character and numeric)." }, { "code": null, "e": 6231, "s": 6091, "text": "I hope now you have a better understanding of how melt performs wide-to-long transformations. I look forward to your thoughts and comments." }, { "code": null, "e": 6349, "s": 6231, "text": "If you find this post useful, follow me and visit my site for more data science tutorials and also my other articles:" }, { "code": null, "e": 6372, "s": 6349, "text": "towardsdatascience.com" }, { "code": null, "e": 6395, "s": 6372, "text": "towardsdatascience.com" } ]
How to Auto-Adjust the Width of Excel Columns with Pandas ExcelWriter | Towards Data Science
One of the most frustrating things you possibly need to deal with is when generating an Excel file using Python, that contains numerous columns you are unable to read due to the short width of the columns. Ideally, you should deliver readable spreadsheets where all the columns are properly formatted so that they are readable. In this article, we are going to explore quick and easy ways one can use for Dynamically adjusting all column widths based on the length of the column name Adjusting a specific column by using its name Adjusting a specific column by using its index Finally, we will also discuss how to fix one common problem that might occur when calling set_column method (AttributeError: 'Worksheet' object has no attribute 'set_column'). First, let’s create a pandas DataFrame that will reference in our examples in order to demonstrate the actions we intend to discuss in this article. Now let’s try to write the pandas DataFrame we’ve just created to a csv file using ExcelWriter, as shown below (Note that if the below snippet fails with ModuleNotFoundError: No module named openpyxl all you need to do is to install the library by running pip install openpyxl): And the output spreadsheet should look similar to the one shown below. As you can see, columns with longer names are cropped and the table in general looks awful. The problem would be even bigger if you had to deal with many such columns. In the following sections we will explore a few possible ways one can use in order to automatically adjust the width of the columns so that the output table in a spreadsheet will be more readable. In order to automatically adjust the width of columns based on their length, we just need to iterate over the columns and set the column width accordingly, as shown below: Note: If the below snippet fails with the following AttributeError, head to the end of the article to see how you can quickly resolve this. AttributeError: 'Worksheet' object has no attribute 'set_column' Now the output pandas DataFrame in the Excel spreadsheet is way more readable and it definitely looks better. All columns are adjusted to the corresponding width that will make them fit into the space without being cropped. Now there is a chance you may wish to manually adjust the width only for a specific column (or subset of columns). You can do so, by referencing the column name as shown in the snippet below. For the sake of this example, let’s assume that we want to adjust the width of column this_is_a_long_column_name to 30: The output of the above snippet is shown below. As we can see, the width of the column this_is_a_long_column_name has been adjusted to 20, while the remaining columns’ width were adjusted to the default value which makes columns with longer width (such as the last one) to be cropped. Alternatively, you may wish to manually adjust the width of a specific column, by directly referencing its index. In the example shown below, we demonstrate this by adjusting the width of the last column. Again, we can see that in this case the last column has been adjusted to width=40, so that it is wide enough to fit the column name. In case any of the above operation fails with the error shown below AttributeError: 'Worksheet' object has no attribute 'set_column' all you need to do is install xlswriter pip install xlsxwriter In this article, we explore a few possible ways one can use to automatically adjust the columns’ width when writing a pandas DataFrame into Excel spreadsheets. We usually create spreadsheets so that we can generate pieces of information that look nice and are easy to read. Therefore, it is important to create spreadsheets that won’t require any manual effort from the reader to make them readable. You can achieve this with minimal code I’ve shared earlier that will definitely help you create high-quality excel files when attempting to create them out of pandas DataFrames.
[ { "code": null, "e": 375, "s": 47, "text": "One of the most frustrating things you possibly need to deal with is when generating an Excel file using Python, that contains numerous columns you are unable to read due to the short width of the columns. Ideally, you should deliver readable spreadsheets where all the columns are properly formatted so that they are readable." }, { "code": null, "e": 452, "s": 375, "text": "In this article, we are going to explore quick and easy ways one can use for" }, { "code": null, "e": 531, "s": 452, "text": "Dynamically adjusting all column widths based on the length of the column name" }, { "code": null, "e": 577, "s": 531, "text": "Adjusting a specific column by using its name" }, { "code": null, "e": 624, "s": 577, "text": "Adjusting a specific column by using its index" }, { "code": null, "e": 800, "s": 624, "text": "Finally, we will also discuss how to fix one common problem that might occur when calling set_column method (AttributeError: 'Worksheet' object has no attribute 'set_column')." }, { "code": null, "e": 949, "s": 800, "text": "First, let’s create a pandas DataFrame that will reference in our examples in order to demonstrate the actions we intend to discuss in this article." }, { "code": null, "e": 1228, "s": 949, "text": "Now let’s try to write the pandas DataFrame we’ve just created to a csv file using ExcelWriter, as shown below (Note that if the below snippet fails with ModuleNotFoundError: No module named openpyxl all you need to do is to install the library by running pip install openpyxl):" }, { "code": null, "e": 1467, "s": 1228, "text": "And the output spreadsheet should look similar to the one shown below. As you can see, columns with longer names are cropped and the table in general looks awful. The problem would be even bigger if you had to deal with many such columns." }, { "code": null, "e": 1664, "s": 1467, "text": "In the following sections we will explore a few possible ways one can use in order to automatically adjust the width of the columns so that the output table in a spreadsheet will be more readable." }, { "code": null, "e": 1836, "s": 1664, "text": "In order to automatically adjust the width of columns based on their length, we just need to iterate over the columns and set the column width accordingly, as shown below:" }, { "code": null, "e": 1976, "s": 1836, "text": "Note: If the below snippet fails with the following AttributeError, head to the end of the article to see how you can quickly resolve this." }, { "code": null, "e": 2041, "s": 1976, "text": "AttributeError: 'Worksheet' object has no attribute 'set_column'" }, { "code": null, "e": 2265, "s": 2041, "text": "Now the output pandas DataFrame in the Excel spreadsheet is way more readable and it definitely looks better. All columns are adjusted to the corresponding width that will make them fit into the space without being cropped." }, { "code": null, "e": 2577, "s": 2265, "text": "Now there is a chance you may wish to manually adjust the width only for a specific column (or subset of columns). You can do so, by referencing the column name as shown in the snippet below. For the sake of this example, let’s assume that we want to adjust the width of column this_is_a_long_column_name to 30:" }, { "code": null, "e": 2862, "s": 2577, "text": "The output of the above snippet is shown below. As we can see, the width of the column this_is_a_long_column_name has been adjusted to 20, while the remaining columns’ width were adjusted to the default value which makes columns with longer width (such as the last one) to be cropped." }, { "code": null, "e": 3067, "s": 2862, "text": "Alternatively, you may wish to manually adjust the width of a specific column, by directly referencing its index. In the example shown below, we demonstrate this by adjusting the width of the last column." }, { "code": null, "e": 3200, "s": 3067, "text": "Again, we can see that in this case the last column has been adjusted to width=40, so that it is wide enough to fit the column name." }, { "code": null, "e": 3268, "s": 3200, "text": "In case any of the above operation fails with the error shown below" }, { "code": null, "e": 3333, "s": 3268, "text": "AttributeError: 'Worksheet' object has no attribute 'set_column'" }, { "code": null, "e": 3373, "s": 3333, "text": "all you need to do is install xlswriter" }, { "code": null, "e": 3396, "s": 3373, "text": "pip install xlsxwriter" } ]
Understanding the t-distribution in R - GeeksforGeeks
24 Feb, 2021 The t-distribution is a type of probability distribution that arises while sampling a normally distributed population when the sample size is small and the standard deviation of the population is unknown. It is also called the Student’s t-distribution. It is approximately a bell curve, that is, it is approximately normally distributed but with a lower peak and more observations near the tail. This implies that it gives a higher probability to the tails than the standard normal distribution or z-distribution (mean is 0 and the standard deviation is 1). Degrees of Freedom is related to the sample size and shows the maximum number of logically independent values that can freely vary in the data sample. It is calculated as n – 1, where n is the total number of observations. For example, if you have 3 observations in a sample, 2 of which are 10,15 and the mean is revealed to be 15 then the third observation has to be 20. So the Degrees of Freedom, in this case, is 2 (only two observations can freely vary). Degrees of Freedom is important to a t-distribution as it characterizes the shape of the curve. That is, the variance in a t-distribution is estimated based on the degrees of freedom of the data set. As the degrees of freedom increase, the t-distribution will come closer to matching the standard normal distribution until they converge (almost identical). Therefore, the standard normal distribution can be used in place of the t-distribution with large sample sizes. A t-test is a statistical hypothesis test used to determine if there is a significant difference (differences are measured in means) between two groups and estimate the likelihood that this difference exists purely by chance (p-value). In a t-distribution, a test statistic called t-score or t-value is used to describe how far away an observation is from the mean. The t-score is used in t-tests, regression tests and to calculate confidence intervals. Functions used: To find the value of probability density function (pdf) of the Student’s t-distribution given a random variable x, use the dt() function in R. Syntax: dt(x, df) Parameters: x is the quantiles vector df is the degrees of freedom pt() function is used to get the cumulative distribution function (CDF) of a t-distribution Syntax: pt(q, df, lower.tail = TRUE) Parameter: q is the quantiles vector df is the degrees of freedom lower.tail – if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]. The qt() function is used to get the quantile function or inverse cumulative density function of a t-distribution. Syntax: qt(p, df, lower.tail = TRUE) Parameter: p is the vector of probabilities df is the degrees of freedom lower.tail – if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]. Set degrees of freedom To plot the density function for student’s t-distribution follow the given steps:First create a vector of quantiles in R.Next, use the dt function to find the values of a t-distribution given a random variable x and certain degrees of freedom.Using these values plot the density function for student’s t-distribution. First create a vector of quantiles in R. Next, use the dt function to find the values of a t-distribution given a random variable x and certain degrees of freedom. Using these values plot the density function for student’s t-distribution. Now, instead of the dt function, use the pt function to get the cumulative distribution function (CDF) of a t-distribution and the qt function to get the quantile function or inverse cumulative density function of a t-distribution. Put it simply, pt returns the area to the left of a given random variable q in the t-distribution and qt finds the t-score is of the pth quantile of the t-distribution. Example: To find a value of t-distribution at x=1, having certain degrees of freedom, say Df = 25, R # value of t-distribution pdf at # x = 0 with 25 degrees of freedomdt(x = 1, df = 25) Output: 0.237211 Example: Code below shows a comparison of probability density functions having different degrees of freedom. It is observed as mentioned before, larger the sample size (degrees of freedom increasing), the closer the plot is to a normal distribution (dotted line in figure). R # Generate a vector of 100 values between -6 and 6x <- seq(-6, 6, length = 100) # Degrees of freedomdf = c(1,4,10,30)colour = c("red", "orange", "green", "yellow","black") # Plot a normal distributionplot(x, dnorm(x), type = "l", lty = 2, xlab = "t-value", ylab = "Density", main = "Comparison of t-distributions", col = "black") # Add the t-distributions to the plotfor (i in 1:4){ lines(x, dt(x, df[i]), col = colour[i])} # Add a legendlegend("topright", c("df = 1", "df = 4", "df = 10", "df = 30", "normal"), col = colour, title = "t-distributions", lty = c(1,1,1,1,2)) Output: Example: Finding p-value and confidence interval with t-distribution R # area to the right of a t-statistic with # value of 2.1 and 14 degrees of freedompt(q = 2.1, df = 14, lower.tail = FALSE) Output: 0.02716657 Essentially we found the one-sided p-value, P(t>2.1) as 2.7%. Now suppose we want to construct a two-sided 95% confidence interval. To do so, find the t-score or t-value for 95% confidence using the qt function or the quantile distribution. Example: R # value in each tail is 2.5% as confidence is 95%# find 2.5th percentile of t-distribution with # 14 degrees of freedomqt(p = 0.025, df = 14, lower.tail = TRUE) Output: -2.144787 So, a t-value of 2.14 will be used as the critical value for a confidence interval of 95%. Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Replace Specific Characters in String in R R - if statement How to filter R dataframe by multiple conditions? How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 26597, "s": 26569, "text": "\n24 Feb, 2021" }, { "code": null, "e": 27156, "s": 26597, "text": "The t-distribution is a type of probability distribution that arises while sampling a normally distributed population when the sample size is small and the standard deviation of the population is unknown. It is also called the Student’s t-distribution. It is approximately a bell curve, that is, it is approximately normally distributed but with a lower peak and more observations near the tail. This implies that it gives a higher probability to the tails than the standard normal distribution or z-distribution (mean is 0 and the standard deviation is 1). " }, { "code": null, "e": 28085, "s": 27156, "text": "Degrees of Freedom is related to the sample size and shows the maximum number of logically independent values that can freely vary in the data sample. It is calculated as n – 1, where n is the total number of observations. For example, if you have 3 observations in a sample, 2 of which are 10,15 and the mean is revealed to be 15 then the third observation has to be 20. So the Degrees of Freedom, in this case, is 2 (only two observations can freely vary). Degrees of Freedom is important to a t-distribution as it characterizes the shape of the curve. That is, the variance in a t-distribution is estimated based on the degrees of freedom of the data set. As the degrees of freedom increase, the t-distribution will come closer to matching the standard normal distribution until they converge (almost identical). Therefore, the standard normal distribution can be used in place of the t-distribution with large sample sizes. " }, { "code": null, "e": 28540, "s": 28085, "text": "A t-test is a statistical hypothesis test used to determine if there is a significant difference (differences are measured in means) between two groups and estimate the likelihood that this difference exists purely by chance (p-value). In a t-distribution, a test statistic called t-score or t-value is used to describe how far away an observation is from the mean. The t-score is used in t-tests, regression tests and to calculate confidence intervals. " }, { "code": null, "e": 28556, "s": 28540, "text": "Functions used:" }, { "code": null, "e": 28699, "s": 28556, "text": "To find the value of probability density function (pdf) of the Student’s t-distribution given a random variable x, use the dt() function in R." }, { "code": null, "e": 28718, "s": 28699, "text": "Syntax: dt(x, df) " }, { "code": null, "e": 28730, "s": 28718, "text": "Parameters:" }, { "code": null, "e": 28756, "s": 28730, "text": "x is the quantiles vector" }, { "code": null, "e": 28785, "s": 28756, "text": "df is the degrees of freedom" }, { "code": null, "e": 28877, "s": 28785, "text": "pt() function is used to get the cumulative distribution function (CDF) of a t-distribution" }, { "code": null, "e": 28914, "s": 28877, "text": "Syntax: pt(q, df, lower.tail = TRUE)" }, { "code": null, "e": 28925, "s": 28914, "text": "Parameter:" }, { "code": null, "e": 28951, "s": 28925, "text": "q is the quantiles vector" }, { "code": null, "e": 28980, "s": 28951, "text": "df is the degrees of freedom" }, { "code": null, "e": 29061, "s": 28980, "text": "lower.tail – if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]." }, { "code": null, "e": 29176, "s": 29061, "text": "The qt() function is used to get the quantile function or inverse cumulative density function of a t-distribution." }, { "code": null, "e": 29213, "s": 29176, "text": "Syntax: qt(p, df, lower.tail = TRUE)" }, { "code": null, "e": 29224, "s": 29213, "text": "Parameter:" }, { "code": null, "e": 29257, "s": 29224, "text": "p is the vector of probabilities" }, { "code": null, "e": 29286, "s": 29257, "text": "df is the degrees of freedom" }, { "code": null, "e": 29367, "s": 29286, "text": "lower.tail – if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]." }, { "code": null, "e": 29390, "s": 29367, "text": "Set degrees of freedom" }, { "code": null, "e": 29708, "s": 29390, "text": "To plot the density function for student’s t-distribution follow the given steps:First create a vector of quantiles in R.Next, use the dt function to find the values of a t-distribution given a random variable x and certain degrees of freedom.Using these values plot the density function for student’s t-distribution." }, { "code": null, "e": 29749, "s": 29708, "text": "First create a vector of quantiles in R." }, { "code": null, "e": 29872, "s": 29749, "text": "Next, use the dt function to find the values of a t-distribution given a random variable x and certain degrees of freedom." }, { "code": null, "e": 29947, "s": 29872, "text": "Using these values plot the density function for student’s t-distribution." }, { "code": null, "e": 30348, "s": 29947, "text": "Now, instead of the dt function, use the pt function to get the cumulative distribution function (CDF) of a t-distribution and the qt function to get the quantile function or inverse cumulative density function of a t-distribution. Put it simply, pt returns the area to the left of a given random variable q in the t-distribution and qt finds the t-score is of the pth quantile of the t-distribution." }, { "code": null, "e": 30447, "s": 30348, "text": "Example: To find a value of t-distribution at x=1, having certain degrees of freedom, say Df = 25," }, { "code": null, "e": 30449, "s": 30447, "text": "R" }, { "code": "# value of t-distribution pdf at # x = 0 with 25 degrees of freedomdt(x = 1, df = 25)", "e": 30535, "s": 30449, "text": null }, { "code": null, "e": 30543, "s": 30535, "text": "Output:" }, { "code": null, "e": 30552, "s": 30543, "text": "0.237211" }, { "code": null, "e": 30561, "s": 30552, "text": "Example:" }, { "code": null, "e": 30826, "s": 30561, "text": "Code below shows a comparison of probability density functions having different degrees of freedom. It is observed as mentioned before, larger the sample size (degrees of freedom increasing), the closer the plot is to a normal distribution (dotted line in figure)." }, { "code": null, "e": 30828, "s": 30826, "text": "R" }, { "code": "# Generate a vector of 100 values between -6 and 6x <- seq(-6, 6, length = 100) # Degrees of freedomdf = c(1,4,10,30)colour = c(\"red\", \"orange\", \"green\", \"yellow\",\"black\") # Plot a normal distributionplot(x, dnorm(x), type = \"l\", lty = 2, xlab = \"t-value\", ylab = \"Density\", main = \"Comparison of t-distributions\", col = \"black\") # Add the t-distributions to the plotfor (i in 1:4){ lines(x, dt(x, df[i]), col = colour[i])} # Add a legendlegend(\"topright\", c(\"df = 1\", \"df = 4\", \"df = 10\", \"df = 30\", \"normal\"), col = colour, title = \"t-distributions\", lty = c(1,1,1,1,2))", "e": 31418, "s": 30828, "text": null }, { "code": null, "e": 31426, "s": 31418, "text": "Output:" }, { "code": null, "e": 31495, "s": 31426, "text": "Example: Finding p-value and confidence interval with t-distribution" }, { "code": null, "e": 31497, "s": 31495, "text": "R" }, { "code": "# area to the right of a t-statistic with # value of 2.1 and 14 degrees of freedompt(q = 2.1, df = 14, lower.tail = FALSE)", "e": 31620, "s": 31497, "text": null }, { "code": null, "e": 31628, "s": 31620, "text": "Output:" }, { "code": null, "e": 31639, "s": 31628, "text": "0.02716657" }, { "code": null, "e": 31880, "s": 31639, "text": "Essentially we found the one-sided p-value, P(t>2.1) as 2.7%. Now suppose we want to construct a two-sided 95% confidence interval. To do so, find the t-score or t-value for 95% confidence using the qt function or the quantile distribution." }, { "code": null, "e": 31889, "s": 31880, "text": "Example:" }, { "code": null, "e": 31891, "s": 31889, "text": "R" }, { "code": "# value in each tail is 2.5% as confidence is 95%# find 2.5th percentile of t-distribution with # 14 degrees of freedomqt(p = 0.025, df = 14, lower.tail = TRUE)", "e": 32052, "s": 31891, "text": null }, { "code": null, "e": 32060, "s": 32052, "text": "Output:" }, { "code": null, "e": 32070, "s": 32060, "text": "-2.144787" }, { "code": null, "e": 32161, "s": 32070, "text": "So, a t-value of 2.14 will be used as the critical value for a confidence interval of 95%." }, { "code": null, "e": 32168, "s": 32161, "text": "Picked" }, { "code": null, "e": 32181, "s": 32168, "text": "R-Statistics" }, { "code": null, "e": 32192, "s": 32181, "text": "R Language" }, { "code": null, "e": 32290, "s": 32192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32342, "s": 32290, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32377, "s": 32342, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32435, "s": 32377, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32473, "s": 32435, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32516, "s": 32473, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32533, "s": 32516, "text": "R - if statement" }, { "code": null, "e": 32583, "s": 32533, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 32632, "s": 32583, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 32669, "s": 32632, "text": "How to import an Excel File into R ?" } ]
Android Menus - GeeksforGeeks
21 Feb, 2022 In android, Menu is an important part of UI component which is used to provide some common functionality around the application. With the help of menu user can experience smooth and consistent experience throughout the application. In order to use menu, we should define it in separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities. Android Studio provides a standard XML format for type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application. Here, we should create a new folder menu inside of our project directory (res/menu) to define the menu and also add a new XML file to build the menu with following elements. Below is the example of defining a menu in XML file (menu_example.xml). XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http:// schemas.android.com/apk/res/android"> <item android:id="@+id/mail" android:icon="@drawable/ic_mail" android:title="@string/mail" /> <item android:id="@+id/upload" android:icon="@drawable/ic_upload" android:title="@string/upload" android:showAsAction="ifRoom" /> <item android:id="@+id/share" android:icon="@drawable/ic_share" android:title="@string/share" /></menu> <menu> It is the root element which helps in defining Menu in XML file and it also holds multiple elements. <item> It is used to create a single item in menu. It also contains nested <menu> element in order to create a submenu. <group> It is an optional and invisible for <item> elements to categorize the menu items so they can share properties like active state, visibility. If we want to add submenu in menu item, then we need to add a <menu> element as the child of an <item>. Below is the example of defining a submenu in menu item. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http:// schemas.android.com/apk/res/android"> <item android:id="@+id/file" android:title="@string/file" > <!-- "file" submenu --> <menu> <item android:id="@+id/create_new" android:title="@string/create_new" /> <item android:id="@+id/open" android:title="@string/open" /> </menu> </item></menu> In android, we have a three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are following – Android Options Menu Android Context Menu Android Popup Menu Android Options Menu – Android Options Menu is a primary collection of menu items in an android application and useful for actions that have a global impact on the searching application. Android Context Menu – Android Context Menu is a floating menu only appears when user click for a long time on an element and useful for elements that effect the selected content or context frame. Android Popup Menu – Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content. ayushpandey3july android Kotlin Android Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters Kotlin Android Tutorial How to Add and Customize Back Button of Action Bar in Android? Kotlin when expression How to Change the Color of Status Bar in an Android App? Kotlin Higher-Order Functions
[ { "code": null, "e": 25919, "s": 25891, "text": "\n21 Feb, 2022" }, { "code": null, "e": 26151, "s": 25919, "text": "In android, Menu is an important part of UI component which is used to provide some common functionality around the application. With the help of menu user can experience smooth and consistent experience throughout the application." }, { "code": null, "e": 26388, "s": 26151, "text": "In order to use menu, we should define it in separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities." }, { "code": null, "e": 26688, "s": 26388, "text": "Android Studio provides a standard XML format for type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application." }, { "code": null, "e": 26862, "s": 26688, "text": "Here, we should create a new folder menu inside of our project directory (res/menu) to define the menu and also add a new XML file to build the menu with following elements." }, { "code": null, "e": 26934, "s": 26862, "text": "Below is the example of defining a menu in XML file (menu_example.xml)." }, { "code": null, "e": 26938, "s": 26934, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http:// schemas.android.com/apk/res/android\"> <item android:id=\"@+id/mail\" android:icon=\"@drawable/ic_mail\" android:title=\"@string/mail\" /> <item android:id=\"@+id/upload\" android:icon=\"@drawable/ic_upload\" android:title=\"@string/upload\" android:showAsAction=\"ifRoom\" /> <item android:id=\"@+id/share\" android:icon=\"@drawable/ic_share\" android:title=\"@string/share\" /></menu>", "e": 27429, "s": 26938, "text": null }, { "code": null, "e": 27539, "s": 27431, "text": "<menu> It is the root element which helps in defining Menu in XML file and it also holds multiple elements." }, { "code": null, "e": 27659, "s": 27539, "text": "<item> It is used to create a single item in menu. It also contains nested <menu> element in order to create a submenu." }, { "code": null, "e": 27808, "s": 27659, "text": "<group> It is an optional and invisible for <item> elements to categorize the menu items so they can share properties like active state, visibility." }, { "code": null, "e": 27912, "s": 27808, "text": "If we want to add submenu in menu item, then we need to add a <menu> element as the child of an <item>." }, { "code": null, "e": 27969, "s": 27912, "text": "Below is the example of defining a submenu in menu item." }, { "code": null, "e": 27973, "s": 27969, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http:// schemas.android.com/apk/res/android\"> <item android:id=\"@+id/file\" android:title=\"@string/file\" > <!-- \"file\" submenu --> <menu> <item android:id=\"@+id/create_new\" android:title=\"@string/create_new\" /> <item android:id=\"@+id/open\" android:title=\"@string/open\" /> </menu> </item></menu>", "e": 28412, "s": 27973, "text": null }, { "code": null, "e": 28533, "s": 28412, "text": "In android, we have a three types of Menus available to define a set of options and actions in our android applications." }, { "code": null, "e": 28583, "s": 28533, "text": "The Menus in android applications are following –" }, { "code": null, "e": 28604, "s": 28583, "text": "Android Options Menu" }, { "code": null, "e": 28625, "s": 28604, "text": "Android Context Menu" }, { "code": null, "e": 28644, "s": 28625, "text": "Android Popup Menu" }, { "code": null, "e": 28831, "s": 28644, "text": "Android Options Menu – Android Options Menu is a primary collection of menu items in an android application and useful for actions that have a global impact on the searching application." }, { "code": null, "e": 29028, "s": 28831, "text": "Android Context Menu – Android Context Menu is a floating menu only appears when user click for a long time on an element and useful for elements that effect the selected content or context frame." }, { "code": null, "e": 29240, "s": 29028, "text": "Android Popup Menu – Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content." }, { "code": null, "e": 29257, "s": 29240, "text": "ayushpandey3july" }, { "code": null, "e": 29265, "s": 29257, "text": "android" }, { "code": null, "e": 29280, "s": 29265, "text": "Kotlin Android" }, { "code": null, "e": 29287, "s": 29280, "text": "Kotlin" }, { "code": null, "e": 29385, "s": 29287, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29428, "s": 29385, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29459, "s": 29428, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29501, "s": 29459, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29543, "s": 29501, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29570, "s": 29543, "text": "Kotlin Setters and Getters" }, { "code": null, "e": 29594, "s": 29570, "text": "Kotlin Android Tutorial" }, { "code": null, "e": 29657, "s": 29594, "text": "How to Add and Customize Back Button of Action Bar in Android?" }, { "code": null, "e": 29680, "s": 29657, "text": "Kotlin when expression" }, { "code": null, "e": 29737, "s": 29680, "text": "How to Change the Color of Status Bar in an Android App?" } ]
Analyzing London Crimes Data in R | by Hamza Rafiq | Towards Data Science
I was playing around with this dataset on crimes in London. The analysis and visualizations went a lot better than I expected so I thought I might as well write an article about it. I got this data while I was experimenting with bigquery but you can also download it from here on Kaggle. Let's begin by loading the libraries and our data. library(tidyverse) ## For data wrangling and visualization library(lubridate) ## To work with dateslibrary(ggpubr) ## Extra visualizations and themeslibrary(patchwork) ## Patch visualizations togetherlibrary(hrbrthemes)## extra themes and formattinglibrary(scales) ## For formatting numeric variableslibrary(tidytext) ## Reordering within facets in ggplot2library(pier) ## Make interactive piecharts in Rlibrary(ggalt) ## Extra visualizationslondon_crimes <- read_csv("C:\\Users\\ACER\\Downloads\\bq-results-20190830-212006-dh1ldd1zjzfc.csv",trim_ws = TRUE) %>% mutate(Date_Column = dmy(Date_Column)) After loading the libraries, I used the read_csv function and gave it a path to where the file is on my computer, set trim_ws to TRUE in case there is any whitespace and remove it followed by the mutate function to change the Date_Column to date type using the dmy function from the Lubridate package. To get an overview, I am going to visualize how the overall crime incidents have changed over the years. Let's walk through the code: london_crimes %>% group_by(Year = floor_date(Date_Column,unit = "year")) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ungroup() %>% mutate(pct_change= (Incidents-lag(Incidents))/lag(Incidents), pct_change=replace_na(pct_change,0)) %>% ggplot(aes(Year,Incidents))+ geom_bar(stat="identity",fill="firebrick",color="black")+ geom_line(color="steelblue",size=1.5,linetype="dashed")+ geom_text(aes(label=percent(pct_change)),vjust=-1,color="black",face="bold")+ geom_text(aes(label=comma(Incidents)),vjust=1,fontface="bold",color="white")+ scale_y_comma(expand = c(0,0),limits = c(0,800000))+ scale_x_date(breaks = "year",date_labels ="%Y")+ theme_classic()+ labs(title = "Total Incidents over the years") To get a yearly analysis, we group by the date column and round it on a yearly level using the floor_date function and then get a sum of total incidents against each year using the summarize function It is always good practice to ungroup after every group_by operation to remove the grouping context We then use the mutate function to create a new column — pct_change which is basically calculating the percentage change between each year using the lag function After getting the data in order, we make a standard bar chart using ggplot2. Since ggplot2 does not allow combo charts to show the percentage growth line graph, I just used the geom_line function to draw a trend line and annotate it with the percentage change values If we just compared 2008 to 2016, you would think that crime incidents remained almost the same but it was actually its lowest in 2014 and has been increasing since. Lets now analyze our data on a borough level. Let's visualize a simple barplot and see total incidents on a borough level. If you are familiar with the Tidyverse meta-package, then the following should not be hard to understand. london_crimes %>% group_by(borough) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% ggplot(aes(reorder(borough,Incidents),Incidents))+ geom_bar(stat = "identity",aes(fill=borough),color="black")+ coord_flip()+ scale_y_comma()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = "none")+ labs(x=" ",y=" ",title = "Total Incidents for boroughs from 2008-2016 ") I am not familiar with London’s geography but Westminister takes the lead by a considerable margin. I googled a bit and found that Westminister is one of the most densely populated areas in London. How has the crime rate changed over the years for these boroughs? For that, I am going to compare the data in 2016 with 2014 rather than in 2008 because crime incidents were lowest in 2014 and comparing it with 2016 could show some interesting changes. london_crimes %>% group_by(borough) %>% summarise(Incidents_2014=sum(total_incidents[year(Date_Column)==2014]), Incidents_2016=sum(total_incidents[year(Date_Column)==2016])) %>% ungroup() %>% mutate(Pct_Change=(Incidents_2016-Incidents_2014)/Incidents_2016) %>% ggplot(aes(reorder(borough,Pct_Change),Pct_Change))+ geom_bar(stat = "identity",aes(fill=borough),color="black")+ coord_flip()+ scale_y_continuous(labels = percent_format())+ geom_text(aes(label=percent(Pct_Change)),hjust=1)+ theme_classic()+ theme(legend.position = "none")+ labs(x=" ",y="Percentage Change ",title = "Percentage Change in Incidents from 2014-2016") Again we group the data by borough and calculated two conditional sums — Incidents_2004 and Incidents_2016 and calculate the percentage difference between the two to see change across every borough Then its a standard procedure as before to plot our barplot, reordering based on highest to the lowest percentage change The highest percentage for the City of London is a bit of a misrepresentation since it had a minuscule number of crime incidents Surprisingly, Westminister is second-to-last even though it is number one in total incidents. At least, it is not experiencing a considerable increase. I would like to see in which year did each borough experienced their historical highest number of crime incidents and also which year had the most of number of boroughs which experienced their highest numbers. london_crimes %>% group_by(borough,Yearly=floor_date(Date_Column,unit = "year")) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% group_by(borough) %>% filter(Incidents==max(Incidents)) %>% ungroup() %>% mutate(borough_max_year = paste0(borough,"-","(",year(Yearly),")")) %>% ggplot(aes(reorder(borough_max_year,Incidents),Incidents))+ geom_col(aes(fill=borough_max_year),color="black")+ scale_y_comma()+ coord_flip()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = "none")+ labs(title = "Max Incidents for each Borough",x="Borough and year of max Incidents ",y="Incidents") We start by grouping by year and borough and get the total incidents against each combination of borough and the corresponding year Since I want to filter for the max year for each borough based on incidents, I group the data by borough and then filter where the Incidents value of each borough is equal to their max value. This will also show the year of that value For visualization sake, I created a new column — borough_max_year which is basically a concatenated version of the Yearly and Incidents columns using the paste0 function. The rest is the same code I have been using for visualizing my bar plots. Now we can see in which year each borough experienced their max number of crime incidents but I am now going to make another visualization to see which year had the most number of boroughs experiencing their highest numbers. london_crimes %>% group_by(borough,Yearly=year(floor_date(Date_Column,unit = "year"))) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% group_by(borough) %>% filter(Incidents==max(Incidents)) %>% ungroup() %>% count(Yearly,sort = TRUE,name = "Boroughs_with_max_incidents") %>% ggplot(aes(reorder(Yearly,Boroughs_with_max_incidents),Boroughs_with_max_incidents))+ ggalt::geom_lollipop(aes(color=factor(Yearly)),point.size = 10)+ scale_y_comma()+ coord_flip()+ geom_text(aes(label=Boroughs_with_max_incidents),hjust=0.5,color="white",fontface="bold")+ theme_classic()+ theme(legend.position = "none")+ labs(title = "Number of boroughs that experienced their highest ever incidents",x="Year",y=" ") Using the same code as before, I added an extra step where I counted the number of boroughs against each year Bored of bar plots, I used the geom_lollipop function from the ggalt package to plot a lollipop chart So 2016 had the most boroughs even though 2016 is third place in terms of total crime incidents preceded by 2008 and 2012 I am now going to check the overall trend of crime incidents for each borough. london_crimes %>% group_by(Year=floor_date(Date_Column,unit = "year"),borough) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ggplot(aes(Year,Incidents))+ geom_line(aes(color=borough),size=0.75,style="--")+ theme_pubclean()+ scale_y_comma()+ expand_limits(y=0)+ facet_wrap(~borough,scales = "free")+ labs(y="Total Incidents",x=" ")+ theme(legend.position = "none",strip.background = element_rect(fill="firebrick"),strip.text=element_text(color = "white",face="bold")) I thought this would have been a really messy graph but it turned out a lot better than I expected. We can generally see on overall increasing trend from 2014 to 2016 for most boroughs. Let's see how the contribution of each major category in total crime incidents and their trend over time. # Piechartlondon_crimes %>% group_by(major_category) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ungroup() %>% mutate(color=RColorBrewer::brewer.pal(9, 'Spectral')) %>% select(label=major_category,value=Incidents,color) %>% pier() %>% pie.size(inner=70, outer=100, width = 600, height = 450) %>% pie.header(text='Crimes', font='Impact', location='pie-center') %>% pie.subtitle(text='by major category')%>% pie.tooltips()# Trend over timelondon_crimes %>% group_by(Yearly=floor_date(Date_Column,unit = "year"),major_category) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ggplot(aes(Yearly,Incidents))+ geom_line(aes(color=major_category),size=0.75)+ theme_pubclean()+ scale_y_comma()+ expand_limits(y=0)+ # making sure that the yaxis for every facet starts at 0 otherwise the trend may look misrepresentitive facet_wrap(~major_category,scales = "free")+ labs(y="Total Incidents",x=" ")+ theme(legend.position = "none",strip.background = element_rect(fill="firebrick"),strip.text=element_text(color = "white",face="bold")) I used the pier package to plot an interactive piechart here because I have always found that plotting decent piecharts in ggplot2 is a bit trickier than it needs to be pier requires that the columns need to be only labeled as “label”, “value” and “color” The code for the trend graphs is the same as the one for boroughs. The only difference is that I replaced the borough variable with the major_category variable Do note that I used the expand_limits(y=0) argument to make sure that y-axis in every line graph starts at 0 otherwise, they can look a bit misrepresentative Major contributors like Theft and Handling and Violence Against the Person have seen a noticeable increase from 2014–2016 Seems weird that there has been no incidence of Sexual Offences and Fraud or Forgery after 2008. Probably because these crimes were later recorded under different categories Now I want to see how different boroughs rank in each major category. I will only be looking at the top 40% since visualizing all the boroughs in a faceted plot looks very messy. london_crimes %>% group_by(major_category,borough) %>% summarise(Incidents=sum(total_incidents)) %>% filter(Incidents>quantile(Incidents,0.6)) %>% #filtering for only the top 40% to make the plot more readable ungroup() %>% mutate(borough=reorder_within(borough,Incidents,major_category)) %>% ggplot(aes(borough,Incidents))+ geom_bar(aes(fill=borough),stat = "identity",color="black")+ coord_flip()+ scale_x_reordered()+ scale_y_comma()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = "none")+ facet_wrap(~major_category,scales ="free")+ labs(x=" ",y=" ",title = "Top 40% Boroughs by Incidence",subtitle = "Segmented by Major Category")+ theme(legend.position = "none",strip.background = element_rect(fill="firebrick"),strip.text=element_text(color = "white",face="bold")) After grouping and summarizing, I keep the grouping context to filter for the top 40% boroughs under each major category using the quantile function Then I reorder the boroughs under each major category based on crime incidents using the reorder_within function from the tidytext package. Reason for doing this is so that the barplots are ordered within each major category facet Also, I want to see which are the dominant minor categories within each major category. london_crimes %>% group_by(major_category,minor_category) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% mutate(minor_category=reorder_within(minor_category,Incidents,major_category)) %>% ggplot(aes(minor_category,Incidents))+ geom_bar(aes(fill=minor_category),stat = "identity",color="black")+ coord_flip()+ scale_x_reordered()+ scale_y_comma()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = "none")+ facet_wrap(~major_category,scales ="free")+ labs(x=" ",y=" ",title = "Incidents by Minor Category",subtitle = "Segmented by Major Category")+ theme(legend.position = "none",strip.background = element_rect(fill="firebrick"),strip.text=element_text(color = "white",face="bold")) So most of these are cases of harassment, assaults, and thefts. I am guessing Sexual Offences were categorized under Violence Against the Person after 2008. Seems like businesses are mostly and personal properties relatively get robbed a lot. Although there is a lot of potential overlap between Theft and Handling, Robbery and Burglary. Despite the grim nature of the dataset, I had a lot of fun exploring it. There is potential for more exploratory analysis as well. You could do an analysis of the safest boroughs in London or dig deeper on minor categories of incidents.
[ { "code": null, "e": 510, "s": 171, "text": "I was playing around with this dataset on crimes in London. The analysis and visualizations went a lot better than I expected so I thought I might as well write an article about it. I got this data while I was experimenting with bigquery but you can also download it from here on Kaggle. Let's begin by loading the libraries and our data." }, { "code": null, "e": 1129, "s": 510, "text": "library(tidyverse) ## For data wrangling and visualization library(lubridate) ## To work with dateslibrary(ggpubr) ## Extra visualizations and themeslibrary(patchwork) ## Patch visualizations togetherlibrary(hrbrthemes)## extra themes and formattinglibrary(scales) ## For formatting numeric variableslibrary(tidytext) ## Reordering within facets in ggplot2library(pier) ## Make interactive piecharts in Rlibrary(ggalt) ## Extra visualizationslondon_crimes <- read_csv(\"C:\\\\Users\\\\ACER\\\\Downloads\\\\bq-results-20190830-212006-dh1ldd1zjzfc.csv\",trim_ws = TRUE) %>% mutate(Date_Column = dmy(Date_Column))" }, { "code": null, "e": 1431, "s": 1129, "text": "After loading the libraries, I used the read_csv function and gave it a path to where the file is on my computer, set trim_ws to TRUE in case there is any whitespace and remove it followed by the mutate function to change the Date_Column to date type using the dmy function from the Lubridate package." }, { "code": null, "e": 1565, "s": 1431, "text": "To get an overview, I am going to visualize how the overall crime incidents have changed over the years. Let's walk through the code:" }, { "code": null, "e": 2458, "s": 1565, "text": "london_crimes %>% group_by(Year = floor_date(Date_Column,unit = \"year\")) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ungroup() %>% mutate(pct_change= (Incidents-lag(Incidents))/lag(Incidents), pct_change=replace_na(pct_change,0)) %>% ggplot(aes(Year,Incidents))+ geom_bar(stat=\"identity\",fill=\"firebrick\",color=\"black\")+ geom_line(color=\"steelblue\",size=1.5,linetype=\"dashed\")+ geom_text(aes(label=percent(pct_change)),vjust=-1,color=\"black\",face=\"bold\")+ geom_text(aes(label=comma(Incidents)),vjust=1,fontface=\"bold\",color=\"white\")+ scale_y_comma(expand = c(0,0),limits = c(0,800000))+ scale_x_date(breaks = \"year\",date_labels =\"%Y\")+ theme_classic()+ labs(title = \"Total Incidents over the years\")" }, { "code": null, "e": 2658, "s": 2458, "text": "To get a yearly analysis, we group by the date column and round it on a yearly level using the floor_date function and then get a sum of total incidents against each year using the summarize function" }, { "code": null, "e": 2758, "s": 2658, "text": "It is always good practice to ungroup after every group_by operation to remove the grouping context" }, { "code": null, "e": 2920, "s": 2758, "text": "We then use the mutate function to create a new column — pct_change which is basically calculating the percentage change between each year using the lag function" }, { "code": null, "e": 3187, "s": 2920, "text": "After getting the data in order, we make a standard bar chart using ggplot2. Since ggplot2 does not allow combo charts to show the percentage growth line graph, I just used the geom_line function to draw a trend line and annotate it with the percentage change values" }, { "code": null, "e": 3399, "s": 3187, "text": "If we just compared 2008 to 2016, you would think that crime incidents remained almost the same but it was actually its lowest in 2014 and has been increasing since. Lets now analyze our data on a borough level." }, { "code": null, "e": 3582, "s": 3399, "text": "Let's visualize a simple barplot and see total incidents on a borough level. If you are familiar with the Tidyverse meta-package, then the following should not be hard to understand." }, { "code": null, "e": 4047, "s": 3582, "text": "london_crimes %>% group_by(borough) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% ggplot(aes(reorder(borough,Incidents),Incidents))+ geom_bar(stat = \"identity\",aes(fill=borough),color=\"black\")+ coord_flip()+ scale_y_comma()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = \"none\")+ labs(x=\" \",y=\" \",title = \"Total Incidents for boroughs from 2008-2016 \")" }, { "code": null, "e": 4245, "s": 4047, "text": "I am not familiar with London’s geography but Westminister takes the lead by a considerable margin. I googled a bit and found that Westminister is one of the most densely populated areas in London." }, { "code": null, "e": 4311, "s": 4245, "text": "How has the crime rate changed over the years for these boroughs?" }, { "code": null, "e": 4498, "s": 4311, "text": "For that, I am going to compare the data in 2016 with 2014 rather than in 2008 because crime incidents were lowest in 2014 and comparing it with 2016 could show some interesting changes." }, { "code": null, "e": 5269, "s": 4498, "text": "london_crimes %>% group_by(borough) %>% summarise(Incidents_2014=sum(total_incidents[year(Date_Column)==2014]), Incidents_2016=sum(total_incidents[year(Date_Column)==2016])) %>% ungroup() %>% mutate(Pct_Change=(Incidents_2016-Incidents_2014)/Incidents_2016) %>% ggplot(aes(reorder(borough,Pct_Change),Pct_Change))+ geom_bar(stat = \"identity\",aes(fill=borough),color=\"black\")+ coord_flip()+ scale_y_continuous(labels = percent_format())+ geom_text(aes(label=percent(Pct_Change)),hjust=1)+ theme_classic()+ theme(legend.position = \"none\")+ labs(x=\" \",y=\"Percentage Change \",title = \"Percentage Change in Incidents from 2014-2016\")" }, { "code": null, "e": 5467, "s": 5269, "text": "Again we group the data by borough and calculated two conditional sums — Incidents_2004 and Incidents_2016 and calculate the percentage difference between the two to see change across every borough" }, { "code": null, "e": 5588, "s": 5467, "text": "Then its a standard procedure as before to plot our barplot, reordering based on highest to the lowest percentage change" }, { "code": null, "e": 5717, "s": 5588, "text": "The highest percentage for the City of London is a bit of a misrepresentation since it had a minuscule number of crime incidents" }, { "code": null, "e": 5869, "s": 5717, "text": "Surprisingly, Westminister is second-to-last even though it is number one in total incidents. At least, it is not experiencing a considerable increase." }, { "code": null, "e": 6079, "s": 5869, "text": "I would like to see in which year did each borough experienced their historical highest number of crime incidents and also which year had the most of number of boroughs which experienced their highest numbers." }, { "code": null, "e": 6800, "s": 6079, "text": "london_crimes %>% group_by(borough,Yearly=floor_date(Date_Column,unit = \"year\")) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% group_by(borough) %>% filter(Incidents==max(Incidents)) %>% ungroup() %>% mutate(borough_max_year = paste0(borough,\"-\",\"(\",year(Yearly),\")\")) %>% ggplot(aes(reorder(borough_max_year,Incidents),Incidents))+ geom_col(aes(fill=borough_max_year),color=\"black\")+ scale_y_comma()+ coord_flip()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = \"none\")+ labs(title = \"Max Incidents for each Borough\",x=\"Borough and year of max Incidents \",y=\"Incidents\")" }, { "code": null, "e": 6932, "s": 6800, "text": "We start by grouping by year and borough and get the total incidents against each combination of borough and the corresponding year" }, { "code": null, "e": 7167, "s": 6932, "text": "Since I want to filter for the max year for each borough based on incidents, I group the data by borough and then filter where the Incidents value of each borough is equal to their max value. This will also show the year of that value" }, { "code": null, "e": 7412, "s": 7167, "text": "For visualization sake, I created a new column — borough_max_year which is basically a concatenated version of the Yearly and Incidents columns using the paste0 function. The rest is the same code I have been using for visualizing my bar plots." }, { "code": null, "e": 7637, "s": 7412, "text": "Now we can see in which year each borough experienced their max number of crime incidents but I am now going to make another visualization to see which year had the most number of boroughs experiencing their highest numbers." }, { "code": null, "e": 8373, "s": 7637, "text": "london_crimes %>% group_by(borough,Yearly=year(floor_date(Date_Column,unit = \"year\"))) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% group_by(borough) %>% filter(Incidents==max(Incidents)) %>% ungroup() %>% count(Yearly,sort = TRUE,name = \"Boroughs_with_max_incidents\") %>% ggplot(aes(reorder(Yearly,Boroughs_with_max_incidents),Boroughs_with_max_incidents))+ ggalt::geom_lollipop(aes(color=factor(Yearly)),point.size = 10)+ scale_y_comma()+ coord_flip()+ geom_text(aes(label=Boroughs_with_max_incidents),hjust=0.5,color=\"white\",fontface=\"bold\")+ theme_classic()+ theme(legend.position = \"none\")+ labs(title = \"Number of boroughs that experienced their highest ever incidents\",x=\"Year\",y=\" \")" }, { "code": null, "e": 8483, "s": 8373, "text": "Using the same code as before, I added an extra step where I counted the number of boroughs against each year" }, { "code": null, "e": 8585, "s": 8483, "text": "Bored of bar plots, I used the geom_lollipop function from the ggalt package to plot a lollipop chart" }, { "code": null, "e": 8707, "s": 8585, "text": "So 2016 had the most boroughs even though 2016 is third place in terms of total crime incidents preceded by 2008 and 2012" }, { "code": null, "e": 8786, "s": 8707, "text": "I am now going to check the overall trend of crime incidents for each borough." }, { "code": null, "e": 9283, "s": 8786, "text": "london_crimes %>% group_by(Year=floor_date(Date_Column,unit = \"year\"),borough) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ggplot(aes(Year,Incidents))+ geom_line(aes(color=borough),size=0.75,style=\"--\")+ theme_pubclean()+ scale_y_comma()+ expand_limits(y=0)+ facet_wrap(~borough,scales = \"free\")+ labs(y=\"Total Incidents\",x=\" \")+ theme(legend.position = \"none\",strip.background = element_rect(fill=\"firebrick\"),strip.text=element_text(color = \"white\",face=\"bold\"))" }, { "code": null, "e": 9469, "s": 9283, "text": "I thought this would have been a really messy graph but it turned out a lot better than I expected. We can generally see on overall increasing trend from 2014 to 2016 for most boroughs." }, { "code": null, "e": 9575, "s": 9469, "text": "Let's see how the contribution of each major category in total crime incidents and their trend over time." }, { "code": null, "e": 10667, "s": 9575, "text": "# Piechartlondon_crimes %>% group_by(major_category) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ungroup() %>% mutate(color=RColorBrewer::brewer.pal(9, 'Spectral')) %>% select(label=major_category,value=Incidents,color) %>% pier() %>% pie.size(inner=70, outer=100, width = 600, height = 450) %>% pie.header(text='Crimes', font='Impact', location='pie-center') %>% pie.subtitle(text='by major category')%>% pie.tooltips()# Trend over timelondon_crimes %>% group_by(Yearly=floor_date(Date_Column,unit = \"year\"),major_category) %>% summarise(Incidents=sum(total_incidents,na.rm = TRUE)) %>% ggplot(aes(Yearly,Incidents))+ geom_line(aes(color=major_category),size=0.75)+ theme_pubclean()+ scale_y_comma()+ expand_limits(y=0)+ # making sure that the yaxis for every facet starts at 0 otherwise the trend may look misrepresentitive facet_wrap(~major_category,scales = \"free\")+ labs(y=\"Total Incidents\",x=\" \")+ theme(legend.position = \"none\",strip.background = element_rect(fill=\"firebrick\"),strip.text=element_text(color = \"white\",face=\"bold\"))" }, { "code": null, "e": 10836, "s": 10667, "text": "I used the pier package to plot an interactive piechart here because I have always found that plotting decent piecharts in ggplot2 is a bit trickier than it needs to be" }, { "code": null, "e": 10923, "s": 10836, "text": "pier requires that the columns need to be only labeled as “label”, “value” and “color”" }, { "code": null, "e": 11083, "s": 10923, "text": "The code for the trend graphs is the same as the one for boroughs. The only difference is that I replaced the borough variable with the major_category variable" }, { "code": null, "e": 11241, "s": 11083, "text": "Do note that I used the expand_limits(y=0) argument to make sure that y-axis in every line graph starts at 0 otherwise, they can look a bit misrepresentative" }, { "code": null, "e": 11363, "s": 11241, "text": "Major contributors like Theft and Handling and Violence Against the Person have seen a noticeable increase from 2014–2016" }, { "code": null, "e": 11537, "s": 11363, "text": "Seems weird that there has been no incidence of Sexual Offences and Fraud or Forgery after 2008. Probably because these crimes were later recorded under different categories" }, { "code": null, "e": 11716, "s": 11537, "text": "Now I want to see how different boroughs rank in each major category. I will only be looking at the top 40% since visualizing all the boroughs in a faceted plot looks very messy." }, { "code": null, "e": 12616, "s": 11716, "text": "london_crimes %>% group_by(major_category,borough) %>% summarise(Incidents=sum(total_incidents)) %>% filter(Incidents>quantile(Incidents,0.6)) %>% #filtering for only the top 40% to make the plot more readable ungroup() %>% mutate(borough=reorder_within(borough,Incidents,major_category)) %>% ggplot(aes(borough,Incidents))+ geom_bar(aes(fill=borough),stat = \"identity\",color=\"black\")+ coord_flip()+ scale_x_reordered()+ scale_y_comma()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = \"none\")+ facet_wrap(~major_category,scales =\"free\")+ labs(x=\" \",y=\" \",title = \"Top 40% Boroughs by Incidence\",subtitle = \"Segmented by Major Category\")+ theme(legend.position = \"none\",strip.background = element_rect(fill=\"firebrick\"),strip.text=element_text(color = \"white\",face=\"bold\"))" }, { "code": null, "e": 12765, "s": 12616, "text": "After grouping and summarizing, I keep the grouping context to filter for the top 40% boroughs under each major category using the quantile function" }, { "code": null, "e": 12996, "s": 12765, "text": "Then I reorder the boroughs under each major category based on crime incidents using the reorder_within function from the tidytext package. Reason for doing this is so that the barplots are ordered within each major category facet" }, { "code": null, "e": 13084, "s": 12996, "text": "Also, I want to see which are the dominant minor categories within each major category." }, { "code": null, "e": 13841, "s": 13084, "text": "london_crimes %>% group_by(major_category,minor_category) %>% summarise(Incidents=sum(total_incidents)) %>% ungroup() %>% mutate(minor_category=reorder_within(minor_category,Incidents,major_category)) %>% ggplot(aes(minor_category,Incidents))+ geom_bar(aes(fill=minor_category),stat = \"identity\",color=\"black\")+ coord_flip()+ scale_x_reordered()+ scale_y_comma()+ geom_text(aes(label=comma(Incidents)),hjust=1)+ theme_classic()+ theme(legend.position = \"none\")+ facet_wrap(~major_category,scales =\"free\")+ labs(x=\" \",y=\" \",title = \"Incidents by Minor Category\",subtitle = \"Segmented by Major Category\")+ theme(legend.position = \"none\",strip.background = element_rect(fill=\"firebrick\"),strip.text=element_text(color = \"white\",face=\"bold\"))" }, { "code": null, "e": 13998, "s": 13841, "text": "So most of these are cases of harassment, assaults, and thefts. I am guessing Sexual Offences were categorized under Violence Against the Person after 2008." }, { "code": null, "e": 14179, "s": 13998, "text": "Seems like businesses are mostly and personal properties relatively get robbed a lot. Although there is a lot of potential overlap between Theft and Handling, Robbery and Burglary." } ]
Find Maximum Shortest Distance in Each Component of a Graph - GeeksforGeeks
18 Dec, 2021 Given an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes. Examples: Input: Output: 8 0 11 Explanation: There are three components in the graph namely a, b, c. In component (a) the shortest paths are following: The shortest distance between 3 and 4 is 5 units.The shortest distance between 3 and 1 is 1+5=6 units.The shortest distance between 3 and 5 is 5+3=8 units.The shortest distance between 1 and 4 is 1 unit.The shortest distance between 1 and 5 is 1+3=4 units.The shortest distance between 4 and 5 is 3 units. The shortest distance between 3 and 4 is 5 units. The shortest distance between 3 and 1 is 1+5=6 units. The shortest distance between 3 and 5 is 5+3=8 units. The shortest distance between 1 and 4 is 1 unit. The shortest distance between 1 and 5 is 1+3=4 units. The shortest distance between 4 and 5 is 3 units. Out of these shortest distances:The maximum shortest distance in component (a) is 8 units between node 3 and node 5.Similarly, The maximum shortest distance in component (b) is 0 units.The maximum shortest distance in component (c) is 11 units between nodes 2 and 6. Input: Output: 7 Explanation: Since, there is only one component with 2 nodes having an edge between them of distance 7. Therefore, the answer will be 7. Approach: This given problem can be solved by finding the connected components in the graph using DFS and store the components in a list of lists. Floyd Warshall’s Algorithm can be used to find all-pairs shortest paths in each connected component which is based on Dynamic Programming. After getting the shortest distances of all possible pairs in the graph, find the maximum shortest distances for each and every component in the graph. Follow the steps below to solve the problem: Define a function maxInThisComponent(vector<int> component, vector<vector<int>> graph) and perform the following steps:Initialize the variable maxDistance as INT_MIN and n as the size of the component.Iterate over the range [0, n) using the variable i and perform the following tasks:Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]].Return the value of maxDistance as the answer. Initialize the variable maxDistance as INT_MIN and n as the size of the component. Iterate over the range [0, n) using the variable i and perform the following tasks:Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]]. Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]]. Return the value of maxDistance as the answer. Initialize a vector visited of size N and initialize the values as false. Initialize vectors, say components[][] and temp[] to store each component of the graph. Using Depth First Search(DFS) find all the components and store them in the vector components[][]. Now, call the function floydWarshall(graph, V) to implement Floyd Warshall algorithm to find the shortest distance between all pairs of a component of a graph. Initialize a vector result[] to store the result. Initialize the variable numOfComp as the size of the vector components[][]. Iterate over the range [0, numOfComp) using the variable i and call the function maxInThisComponent(components[i], graph) and store the value returned by it in the vector result[]. After performing the above steps, print the values of the vector result[] as the answer. Below is the implementation of the above approach: C++ Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Below dfs function will be used to// get the connected components of a// graph and stores all the connected// nodes in the vector componentvoid dfs(int src, vector<bool>& visited, vector<vector<int> >& graph, vector<int>& component, int N){ // Mark this vertex as visited visited[src] = true; // Put this node in component vector component.push_back(src); // For all other vertices in graph for (int dest = 0; dest < N; dest++) { // If there is an edge between // src and dest i.e., the value // of graph[u][v]!=INT_MAX if (graph[src][dest] != INT_MAX) { // If we haven't visited dest // then recursively apply // dfs on dest if (!visited[dest]) dfs(dest, visited, graph, component, N); } }} // Below is the Floyd Warshall Algorithm// which is based on Dynamic Programmingvoid floydWarshall( vector<vector<int> >& graph, int N){ // For every vertex of graph find // the shortest distance with // other vertices for (int k = 0; k < N; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Taking care of integer // overflow if (graph[i][k] != INT_MAX && graph[k][j] != INT_MAX) { // Update distance between // vertex i and j if choosing // k as an intermediate vertex // make a shorter distance if (graph[i][k] + graph[k][j] < graph[i][j]) graph[i][j] = graph[i][k] + graph[k][j]; } } } }} // Function to find the maximum shortest// path distance in a component by checking// the shortest distances between all// possible pairs of nodesint maxInThisComponent(vector<int>& component, vector<vector<int> >& graph){ int maxDistance = INT_MIN; int n = component.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { maxDistance = max(maxDistance, graph[component[i]][component[j]]); } } // If the maxDistance is still INT_MIN // then return 0 because this component // has a single element return (maxDistance == INT_MIN ? 0 : maxDistance);} // Below function uses above two method// to get the maximum shortest distances// in each component of the graph the// function returns a vector, where each// element denotes maximum shortest path// distance for a componentvector<int> maximumShortesDistances( vector<vector<int> >& graph, int N){ // Find the connected components vector<bool> visited(N, false); vector<vector<int> > components; // For storing the nodes in a // particular component vector<int> temp; // Now for each unvisited node run // the dfs to get the connected // component having this unvisited node for (int i = 0; i < N; i++) { if (!visited[i]) { // First of all clear the temp temp.clear(); dfs(i, visited, graph, temp, N); components.push_back(temp); } } // Now for all-pair find the shortest // path distances using Floyd Warshall floydWarshall(graph, N); // Now for each component find the // maximum shortest distance and // store it in result vector<int> result; int numOfComp = components.size(); int maxDistance; for (int i = 0; i < numOfComp; i++) { maxDistance = maxInThisComponent(components[i], graph); result.push_back(maxDistance); } return result;} // Driver Codeint main(){ int N = 8; const int inf = INT_MAX; // Adjacency Matrix for the first // graph in the examples vector<vector<int> > graph1 = { { 0, inf, 9, inf, inf, inf, 3, inf }, { inf, 0, inf, 10, 1, 8, inf, inf }, { 9, inf, 0, inf, inf, inf, 11, inf }, { inf, 10, inf, 0, 5, 13, inf, inf }, { inf, 1, inf, 5, 0, 3, inf, inf }, { 8, inf, inf, 13, 3, 0, inf, inf }, { 3, inf, 11, inf, inf, inf, 0, inf }, { inf, inf, inf, inf, inf, inf, inf, 0 }, }; // Find the maximum shortest distances vector<int> result1 = maximumShortesDistances(graph1, N); // Printing the maximum shortest path // distances for each components for (int mx1 : result1) cout << mx1 << ' '; return 0;} <script>// Javascript program for the above approach // Below dfs function will be used to// get the connected components of a// graph and stores all the connected// nodes in the vector componentfunction dfs(src, visited, graph, component, N){ // Mark this vertex as visited visited[src] = true; // Put this node in component vector component.push(src); // For all other vertices in graph for (let dest = 0; dest < N; dest++) { // If there is an edge between // src and dest i.e., the value // of graph[u][v]!=INT_MAX if (graph[src][dest] != Number.MAX_SAFE_INTEGER) { // If we haven't visited dest // then recursively apply // dfs on dest if (!visited[dest]) dfs(dest, visited, graph, component, N); } }} // Below is the Floyd Warshall Algorithm// which is based on Dynamic Programmingfunction floydWarshall(graph, N){ // For every vertex of graph find // the shortest distance with // other vertices for (let k = 0; k < N; k++) { for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // Taking care of integer // overflow if (graph[i][k] != Number.MAX_SAFE_INTEGER && graph[k][j] != Number.MAX_SAFE_INTEGER) { // Update distance between // vertex i and j if choosing // k as an intermediate vertex // make a shorter distance if (graph[i][k] + graph[k][j] < graph[i][j]) graph[i][j] = graph[i][k] + graph[k][j]; } } } }} // Function to find the maximum shortest// path distance in a component by checking// the shortest distances between all// possible pairs of nodesfunction maxInThisComponent(component, graph) { let maxDistance = Number.MIN_SAFE_INTEGER; let n = component.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { maxDistance = Math.max(maxDistance, graph[component[i]][component[j]]); } } // If the maxDistance is still INT_MIN // then return 0 because this component // has a single element return maxDistance == Number.MIN_SAFE_INTEGER ? 0 : maxDistance;} // Below function uses above two method// to get the maximum shortest distances// in each component of the graph the// function returns a vector, where each// element denotes maximum shortest path// distance for a componentfunction maximumShortesDistances(graph, N) { // Find the connected components let visited = new Array(N).fill(false); let components = new Array(); // For storing the nodes in a // particular component let temp = []; // Now for each unvisited node run // the dfs to get the connected // component having this unvisited node for (let i = 0; i < N; i++) { if (!visited[i]) { // First of all clear the temp temp = []; dfs(i, visited, graph, temp, N); components.push(temp); } } // Now for all-pair find the shortest // path distances using Floyd Warshall floydWarshall(graph, N); // Now for each component find the // maximum shortest distance and // store it in result let result = []; let numOfComp = components.length; let maxDistance; for (let i = 0; i < numOfComp; i++) { maxDistance = maxInThisComponent(components[i], graph); result.push(maxDistance); } return result;} // Driver Code let N = 8;const inf = Number.MAX_SAFE_INTEGER; // Adjacency Matrix for the first// graph in the exampleslet graph1 = [ [0, inf, 9, inf, inf, inf, 3, inf], [inf, 0, inf, 10, 1, 8, inf, inf], [9, inf, 0, inf, inf, inf, 11, inf], [inf, 10, inf, 0, 5, 13, inf, inf], [inf, 1, inf, 5, 0, 3, inf, inf], [8, inf, inf, 13, 3, 0, inf, inf], [3, inf, 11, inf, inf, inf, 0, inf], [inf, inf, inf, inf, inf, inf, inf, 0],]; // Find the maximum shortest distanceslet result1 = maximumShortesDistances(graph1, N); // Printing the maximum shortest path// distances for each componentsfor (mx1 of result1) document.write(mx1 + " "); // This code is contributed by gfgking.</script> 11 8 0 Time Complexity: O(N3), where N is the number of vertices in the graph.Auxiliary Space: O(N) gfgking simranarora5sos DFS Dijkstra Dynamic Programming Graph Dynamic Programming DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Maximum sum such that no two elements are adjacent Gold Mine Problem Breadth First Search or BFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Depth First Search or DFS for a Graph Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
[ { "code": null, "e": 24307, "s": 24279, "text": "\n18 Dec, 2021" }, { "code": null, "e": 24548, "s": 24307, "text": "Given an adjacency matrix graph[][] of a weighted graph consisting of N nodes and positive weights, the task for each connected component of the graph is to find the maximum among all possible shortest distances between every pair of nodes." }, { "code": null, "e": 24558, "s": 24548, "text": "Examples:" }, { "code": null, "e": 24565, "s": 24558, "text": "Input:" }, { "code": null, "e": 24573, "s": 24565, "text": "Output:" }, { "code": null, "e": 24581, "s": 24573, "text": "8 0 11 " }, { "code": null, "e": 24701, "s": 24581, "text": "Explanation: There are three components in the graph namely a, b, c. In component (a) the shortest paths are following:" }, { "code": null, "e": 25007, "s": 24701, "text": "The shortest distance between 3 and 4 is 5 units.The shortest distance between 3 and 1 is 1+5=6 units.The shortest distance between 3 and 5 is 5+3=8 units.The shortest distance between 1 and 4 is 1 unit.The shortest distance between 1 and 5 is 1+3=4 units.The shortest distance between 4 and 5 is 3 units." }, { "code": null, "e": 25057, "s": 25007, "text": "The shortest distance between 3 and 4 is 5 units." }, { "code": null, "e": 25111, "s": 25057, "text": "The shortest distance between 3 and 1 is 1+5=6 units." }, { "code": null, "e": 25165, "s": 25111, "text": "The shortest distance between 3 and 5 is 5+3=8 units." }, { "code": null, "e": 25214, "s": 25165, "text": "The shortest distance between 1 and 4 is 1 unit." }, { "code": null, "e": 25268, "s": 25214, "text": "The shortest distance between 1 and 5 is 1+3=4 units." }, { "code": null, "e": 25318, "s": 25268, "text": "The shortest distance between 4 and 5 is 3 units." }, { "code": null, "e": 25585, "s": 25318, "text": "Out of these shortest distances:The maximum shortest distance in component (a) is 8 units between node 3 and node 5.Similarly, The maximum shortest distance in component (b) is 0 units.The maximum shortest distance in component (c) is 11 units between nodes 2 and 6." }, { "code": null, "e": 25592, "s": 25585, "text": "Input:" }, { "code": null, "e": 25600, "s": 25592, "text": "Output:" }, { "code": null, "e": 25603, "s": 25600, "text": "7 " }, { "code": null, "e": 25740, "s": 25603, "text": "Explanation: Since, there is only one component with 2 nodes having an edge between them of distance 7. Therefore, the answer will be 7." }, { "code": null, "e": 26223, "s": 25740, "text": "Approach: This given problem can be solved by finding the connected components in the graph using DFS and store the components in a list of lists. Floyd Warshall’s Algorithm can be used to find all-pairs shortest paths in each connected component which is based on Dynamic Programming. After getting the shortest distances of all possible pairs in the graph, find the maximum shortest distances for each and every component in the graph. Follow the steps below to solve the problem:" }, { "code": null, "e": 26710, "s": 26223, "text": "Define a function maxInThisComponent(vector<int> component, vector<vector<int>> graph) and perform the following steps:Initialize the variable maxDistance as INT_MIN and n as the size of the component.Iterate over the range [0, n) using the variable i and perform the following tasks:Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]].Return the value of maxDistance as the answer." }, { "code": null, "e": 26793, "s": 26710, "text": "Initialize the variable maxDistance as INT_MIN and n as the size of the component." }, { "code": null, "e": 27033, "s": 26793, "text": "Iterate over the range [0, n) using the variable i and perform the following tasks:Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]]." }, { "code": null, "e": 27190, "s": 27033, "text": "Iterate over the range [i+1, n) using the variable j and update the value of maxDistance as the maximum of maxDistance or graph[component[i]][component[j]]." }, { "code": null, "e": 27237, "s": 27190, "text": "Return the value of maxDistance as the answer." }, { "code": null, "e": 27311, "s": 27237, "text": "Initialize a vector visited of size N and initialize the values as false." }, { "code": null, "e": 27399, "s": 27311, "text": "Initialize vectors, say components[][] and temp[] to store each component of the graph." }, { "code": null, "e": 27498, "s": 27399, "text": "Using Depth First Search(DFS) find all the components and store them in the vector components[][]." }, { "code": null, "e": 27658, "s": 27498, "text": "Now, call the function floydWarshall(graph, V) to implement Floyd Warshall algorithm to find the shortest distance between all pairs of a component of a graph." }, { "code": null, "e": 27708, "s": 27658, "text": "Initialize a vector result[] to store the result." }, { "code": null, "e": 27784, "s": 27708, "text": "Initialize the variable numOfComp as the size of the vector components[][]." }, { "code": null, "e": 27965, "s": 27784, "text": "Iterate over the range [0, numOfComp) using the variable i and call the function maxInThisComponent(components[i], graph) and store the value returned by it in the vector result[]." }, { "code": null, "e": 28054, "s": 27965, "text": "After performing the above steps, print the values of the vector result[] as the answer." }, { "code": null, "e": 28105, "s": 28054, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28109, "s": 28105, "text": "C++" }, { "code": null, "e": 28120, "s": 28109, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Below dfs function will be used to// get the connected components of a// graph and stores all the connected// nodes in the vector componentvoid dfs(int src, vector<bool>& visited, vector<vector<int> >& graph, vector<int>& component, int N){ // Mark this vertex as visited visited[src] = true; // Put this node in component vector component.push_back(src); // For all other vertices in graph for (int dest = 0; dest < N; dest++) { // If there is an edge between // src and dest i.e., the value // of graph[u][v]!=INT_MAX if (graph[src][dest] != INT_MAX) { // If we haven't visited dest // then recursively apply // dfs on dest if (!visited[dest]) dfs(dest, visited, graph, component, N); } }} // Below is the Floyd Warshall Algorithm// which is based on Dynamic Programmingvoid floydWarshall( vector<vector<int> >& graph, int N){ // For every vertex of graph find // the shortest distance with // other vertices for (int k = 0; k < N; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Taking care of integer // overflow if (graph[i][k] != INT_MAX && graph[k][j] != INT_MAX) { // Update distance between // vertex i and j if choosing // k as an intermediate vertex // make a shorter distance if (graph[i][k] + graph[k][j] < graph[i][j]) graph[i][j] = graph[i][k] + graph[k][j]; } } } }} // Function to find the maximum shortest// path distance in a component by checking// the shortest distances between all// possible pairs of nodesint maxInThisComponent(vector<int>& component, vector<vector<int> >& graph){ int maxDistance = INT_MIN; int n = component.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { maxDistance = max(maxDistance, graph[component[i]][component[j]]); } } // If the maxDistance is still INT_MIN // then return 0 because this component // has a single element return (maxDistance == INT_MIN ? 0 : maxDistance);} // Below function uses above two method// to get the maximum shortest distances// in each component of the graph the// function returns a vector, where each// element denotes maximum shortest path// distance for a componentvector<int> maximumShortesDistances( vector<vector<int> >& graph, int N){ // Find the connected components vector<bool> visited(N, false); vector<vector<int> > components; // For storing the nodes in a // particular component vector<int> temp; // Now for each unvisited node run // the dfs to get the connected // component having this unvisited node for (int i = 0; i < N; i++) { if (!visited[i]) { // First of all clear the temp temp.clear(); dfs(i, visited, graph, temp, N); components.push_back(temp); } } // Now for all-pair find the shortest // path distances using Floyd Warshall floydWarshall(graph, N); // Now for each component find the // maximum shortest distance and // store it in result vector<int> result; int numOfComp = components.size(); int maxDistance; for (int i = 0; i < numOfComp; i++) { maxDistance = maxInThisComponent(components[i], graph); result.push_back(maxDistance); } return result;} // Driver Codeint main(){ int N = 8; const int inf = INT_MAX; // Adjacency Matrix for the first // graph in the examples vector<vector<int> > graph1 = { { 0, inf, 9, inf, inf, inf, 3, inf }, { inf, 0, inf, 10, 1, 8, inf, inf }, { 9, inf, 0, inf, inf, inf, 11, inf }, { inf, 10, inf, 0, 5, 13, inf, inf }, { inf, 1, inf, 5, 0, 3, inf, inf }, { 8, inf, inf, 13, 3, 0, inf, inf }, { 3, inf, 11, inf, inf, inf, 0, inf }, { inf, inf, inf, inf, inf, inf, inf, 0 }, }; // Find the maximum shortest distances vector<int> result1 = maximumShortesDistances(graph1, N); // Printing the maximum shortest path // distances for each components for (int mx1 : result1) cout << mx1 << ' '; return 0;}", "e": 32770, "s": 28120, "text": null }, { "code": "<script>// Javascript program for the above approach // Below dfs function will be used to// get the connected components of a// graph and stores all the connected// nodes in the vector componentfunction dfs(src, visited, graph, component, N){ // Mark this vertex as visited visited[src] = true; // Put this node in component vector component.push(src); // For all other vertices in graph for (let dest = 0; dest < N; dest++) { // If there is an edge between // src and dest i.e., the value // of graph[u][v]!=INT_MAX if (graph[src][dest] != Number.MAX_SAFE_INTEGER) { // If we haven't visited dest // then recursively apply // dfs on dest if (!visited[dest]) dfs(dest, visited, graph, component, N); } }} // Below is the Floyd Warshall Algorithm// which is based on Dynamic Programmingfunction floydWarshall(graph, N){ // For every vertex of graph find // the shortest distance with // other vertices for (let k = 0; k < N; k++) { for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // Taking care of integer // overflow if (graph[i][k] != Number.MAX_SAFE_INTEGER && graph[k][j] != Number.MAX_SAFE_INTEGER) { // Update distance between // vertex i and j if choosing // k as an intermediate vertex // make a shorter distance if (graph[i][k] + graph[k][j] < graph[i][j]) graph[i][j] = graph[i][k] + graph[k][j]; } } } }} // Function to find the maximum shortest// path distance in a component by checking// the shortest distances between all// possible pairs of nodesfunction maxInThisComponent(component, graph) { let maxDistance = Number.MIN_SAFE_INTEGER; let n = component.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { maxDistance = Math.max(maxDistance, graph[component[i]][component[j]]); } } // If the maxDistance is still INT_MIN // then return 0 because this component // has a single element return maxDistance == Number.MIN_SAFE_INTEGER ? 0 : maxDistance;} // Below function uses above two method// to get the maximum shortest distances// in each component of the graph the// function returns a vector, where each// element denotes maximum shortest path// distance for a componentfunction maximumShortesDistances(graph, N) { // Find the connected components let visited = new Array(N).fill(false); let components = new Array(); // For storing the nodes in a // particular component let temp = []; // Now for each unvisited node run // the dfs to get the connected // component having this unvisited node for (let i = 0; i < N; i++) { if (!visited[i]) { // First of all clear the temp temp = []; dfs(i, visited, graph, temp, N); components.push(temp); } } // Now for all-pair find the shortest // path distances using Floyd Warshall floydWarshall(graph, N); // Now for each component find the // maximum shortest distance and // store it in result let result = []; let numOfComp = components.length; let maxDistance; for (let i = 0; i < numOfComp; i++) { maxDistance = maxInThisComponent(components[i], graph); result.push(maxDistance); } return result;} // Driver Code let N = 8;const inf = Number.MAX_SAFE_INTEGER; // Adjacency Matrix for the first// graph in the exampleslet graph1 = [ [0, inf, 9, inf, inf, inf, 3, inf], [inf, 0, inf, 10, 1, 8, inf, inf], [9, inf, 0, inf, inf, inf, 11, inf], [inf, 10, inf, 0, 5, 13, inf, inf], [inf, 1, inf, 5, 0, 3, inf, inf], [8, inf, inf, 13, 3, 0, inf, inf], [3, inf, 11, inf, inf, inf, 0, inf], [inf, inf, inf, inf, inf, inf, inf, 0],]; // Find the maximum shortest distanceslet result1 = maximumShortesDistances(graph1, N); // Printing the maximum shortest path// distances for each componentsfor (mx1 of result1) document.write(mx1 + \" \"); // This code is contributed by gfgking.</script>", "e": 36723, "s": 32770, "text": null }, { "code": null, "e": 36731, "s": 36723, "text": "11 8 0 " }, { "code": null, "e": 36824, "s": 36731, "text": "Time Complexity: O(N3), where N is the number of vertices in the graph.Auxiliary Space: O(N)" }, { "code": null, "e": 36834, "s": 36826, "text": "gfgking" }, { "code": null, "e": 36850, "s": 36834, "text": "simranarora5sos" }, { "code": null, "e": 36854, "s": 36850, "text": "DFS" }, { "code": null, "e": 36863, "s": 36854, "text": "Dijkstra" }, { "code": null, "e": 36883, "s": 36863, "text": "Dynamic Programming" }, { "code": null, "e": 36889, "s": 36883, "text": "Graph" }, { "code": null, "e": 36909, "s": 36889, "text": "Dynamic Programming" }, { "code": null, "e": 36913, "s": 36909, "text": "DFS" }, { "code": null, "e": 36919, "s": 36913, "text": "Graph" }, { "code": null, "e": 37017, "s": 36919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37026, "s": 37017, "text": "Comments" }, { "code": null, "e": 37039, "s": 37026, "text": "Old Comments" }, { "code": null, "e": 37099, "s": 37039, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 37120, "s": 37099, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 37176, "s": 37120, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 37227, "s": 37176, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 37245, "s": 37227, "text": "Gold Mine Problem" }, { "code": null, "e": 37285, "s": 37245, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 37336, "s": 37285, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 37374, "s": 37336, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 37425, "s": 37374, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" } ]
Cypress - Architecture and Environment Setup
Cypress architecture is illustrated in the below diagram − The source of the above diagram is https://www.tutorialspoint.com/cypress-architecturetest-automation Automation tools like Selenium work by running outside the browser. However, the Cypress has a different architecture. It runs within the browser. Cypress is basically based on the server - Node.js. There is a continued interaction of Cypress with the Node.js and they work in coordination with each other. As a result, Cypress can be utilised for testing both the front and backend of the application. Cypress is thus, capable of handling the tasks performed at a real time on the UI and simultaneously can also perform the actions outside of the browser. The basic differences between Cypress and Selenium are listed below − For Cypress environment setup, visit the link −https://nodejs.org/en/download/. The screen that will appear is given below − There shall be both Windows and macOS Installer. We have to get the package as per the local operating system. For a 64- bit Windows configuration, the following pop-up comes up to save the installer. Once the installation is done, a nodejs file gets created in the Program files. The path of this file should be noted. Then, enter environment variables from the Start, as shown below − In the System Properties pop-up, move to Advanced, click on Environment Variables. Then click on OK. In the Environment Variables pop-up, move to the System variables section and click on New. Enter NODE_HOME and the node.js path (noted earlier) in the Variable name and the Variable value fields respectively in the New System Variable pop-up. Once the path of the node.js file is set, we shall create an empty folder (say cypressautomation) in any desired location. Next, we need to have a JavaScript editor to write the code for Cypress. For this, we can download Visual Studio Code from the link https://code.visualstudio.com/ As per the local operating system, choose the correct package − Once the executable file is downloaded, and all the installation steps are completed, the Visual Studio Code gets launched. Select the option Open Folder from the File menu. Then, add the CypressAutomation folder (that we have created before) to the Visual Studio Code. We need to create the package.json file with the below command from terminal − We have to enter details like the package name, description, and so on, as mentioned in the image given below − npm init Once done, the package.json file gets created within the project folder with the information we have provided. Once done, the package.json file gets created within the project folder with the information we have provided. Finally, to install Cypress run the command given below − npm install cypress --save-dev You will get the following output − 73 Lectures 12 hours Rahul Shetty Print Add Notes Bookmark this page
[ { "code": null, "e": 2556, "s": 2497, "text": "Cypress architecture is illustrated in the below diagram −" }, { "code": null, "e": 2658, "s": 2556, "text": "The source of the above diagram is https://www.tutorialspoint.com/cypress-architecturetest-automation" }, { "code": null, "e": 2857, "s": 2658, "text": "Automation tools like Selenium work by running outside the browser. However, the Cypress has a different architecture. It runs within the browser. Cypress is basically based on the server - Node.js." }, { "code": null, "e": 3061, "s": 2857, "text": "There is a continued interaction of Cypress with the Node.js and they work in coordination with each other. As a result, Cypress can be utilised for testing both the front and backend of the application." }, { "code": null, "e": 3215, "s": 3061, "text": "Cypress is thus, capable of handling the tasks performed at a real time on the UI and simultaneously can also perform the actions outside of the browser." }, { "code": null, "e": 3285, "s": 3215, "text": "The basic differences between Cypress and Selenium are listed below −" }, { "code": null, "e": 3410, "s": 3285, "text": "For Cypress environment setup, visit the link −https://nodejs.org/en/download/. The screen that will appear is given below −" }, { "code": null, "e": 3521, "s": 3410, "text": "There shall be both Windows and macOS Installer. We have to get the package as per the local operating system." }, { "code": null, "e": 3611, "s": 3521, "text": "For a 64- bit Windows configuration, the following pop-up comes up to save the installer." }, { "code": null, "e": 3797, "s": 3611, "text": "Once the installation is done, a nodejs file gets created in the Program files. The path of this file should be noted. Then, enter environment variables from the Start, as shown below −" }, { "code": null, "e": 3898, "s": 3797, "text": "In the System Properties pop-up, move to Advanced, click on Environment Variables. Then click on OK." }, { "code": null, "e": 3990, "s": 3898, "text": "In the Environment Variables pop-up, move to the System variables section and click on New." }, { "code": null, "e": 4142, "s": 3990, "text": "Enter NODE_HOME and the node.js path (noted earlier) in the Variable name and the Variable value fields respectively in the New System Variable pop-up." }, { "code": null, "e": 4265, "s": 4142, "text": "Once the path of the node.js file is set, we shall create an empty folder (say cypressautomation) in any desired location." }, { "code": null, "e": 4428, "s": 4265, "text": "Next, we need to have a JavaScript editor to write the code for Cypress. For this, we can download Visual Studio Code from the link https://code.visualstudio.com/" }, { "code": null, "e": 4492, "s": 4428, "text": "As per the local operating system, choose the correct package −" }, { "code": null, "e": 4616, "s": 4492, "text": "Once the executable file is downloaded, and all the installation steps are completed, the Visual Studio Code gets launched." }, { "code": null, "e": 4762, "s": 4616, "text": "Select the option Open Folder from the File menu. Then, add the CypressAutomation folder (that we have created before) to the Visual Studio Code." }, { "code": null, "e": 4841, "s": 4762, "text": "We need to create the package.json file with the below command from terminal −" }, { "code": null, "e": 4953, "s": 4841, "text": "We have to enter details like the package name, description, and so on, as mentioned in the image given below −" }, { "code": null, "e": 4963, "s": 4953, "text": "npm init\n" }, { "code": null, "e": 5074, "s": 4963, "text": "Once done, the package.json file gets created within the project folder with the information we have provided." }, { "code": null, "e": 5185, "s": 5074, "text": "Once done, the package.json file gets created within the project folder with the information we have provided." }, { "code": null, "e": 5243, "s": 5185, "text": "Finally, to install Cypress run the command given below −" }, { "code": null, "e": 5275, "s": 5243, "text": "npm install cypress --save-dev\n" }, { "code": null, "e": 5311, "s": 5275, "text": "You will get the following output −" }, { "code": null, "e": 5345, "s": 5311, "text": "\n 73 Lectures \n 12 hours \n" }, { "code": null, "e": 5359, "s": 5345, "text": " Rahul Shetty" }, { "code": null, "e": 5366, "s": 5359, "text": " Print" }, { "code": null, "e": 5377, "s": 5366, "text": " Add Notes" } ]
Find smallest number with given number of digits and sum of digits in C++
In this problem, we are given two values that are the sum (denoting the sum of digits) and digit (denoting the number of digits). Our task is to find the smallest number with a given number of digits and sum of digits. Let’s take an example to understand the problem, sum = 15, dgiti = 2 69 All 2 digits numbers with sum 15 are : 69, 78, 87, 96. A simple solution to the problem is by considering all the numbers with digit count as digit and find the smallest number whose sum of digit is equal to the sum. An efficient solution is using the greedy approach. We will create the number by filling the elements from the last digit i.e. the LSB of the number. We will consider the largest possible element for LSB and then go for the next position. We will try to keep the LSB as large as possible and MSB as small as possible. Program to illustrate the working of our solution, Live Demo #include <iostream> using namespace std; void findSmallestNumWithSum(int digit, int sum) { if (sum == 0) { if(digit == 1) cout<<"Smallest number is 0"; else cout<<"Smallest number with sum cannot be found"; return ; } if (sum > 9*digit) { cout<<"Smallest number with sum cannot be found"; return ; } int number[digit]; sum -= 1; for (int i = digit-1; i>0; i--) { if (sum > 9) { number[i] = 9; sum -= 9; } else { number[i] = sum; sum = 0; } } number[0] = sum + 1; cout<<"Smallest number is "; for (int i=0; i<digit; i++) cout<<number[i]; } int main() { int sum = 15, digit = 3; findSmallestNumWithSum(digit, sum); return 0; } Smallest number is 159
[ { "code": null, "e": 1281, "s": 1062, "text": "In this problem, we are given two values that are the sum (denoting the sum\nof digits) and digit (denoting the number of digits). Our task is to find the\nsmallest number with a given number of digits and sum of digits." }, { "code": null, "e": 1330, "s": 1281, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1350, "s": 1330, "text": "sum = 15, dgiti = 2" }, { "code": null, "e": 1353, "s": 1350, "text": "69" }, { "code": null, "e": 1408, "s": 1353, "text": "All 2 digits numbers with sum 15 are : 69, 78, 87, 96." }, { "code": null, "e": 1570, "s": 1408, "text": "A simple solution to the problem is by considering all the numbers with digit\ncount as digit and find the smallest number whose sum of digit is equal to\nthe sum." }, { "code": null, "e": 1809, "s": 1570, "text": "An efficient solution is using the greedy approach. We will create the\nnumber by filling the elements from the last digit i.e. the LSB of the number.\nWe will consider the largest possible element for LSB and then go for the\nnext position." }, { "code": null, "e": 1888, "s": 1809, "text": "We will try to keep the LSB as large as possible and MSB as small as possible." }, { "code": null, "e": 1939, "s": 1888, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 1950, "s": 1939, "text": " Live Demo" }, { "code": null, "e": 2725, "s": 1950, "text": "#include <iostream>\nusing namespace std;\nvoid findSmallestNumWithSum(int digit, int sum) {\n if (sum == 0) {\n if(digit == 1)\n cout<<\"Smallest number is 0\";\n else\n cout<<\"Smallest number with sum cannot be found\";\n return ;\n }\n if (sum > 9*digit) {\n cout<<\"Smallest number with sum cannot be found\";\n return ;\n }\n int number[digit];\n sum -= 1;\n for (int i = digit-1; i>0; i--) {\n if (sum > 9) {\n number[i] = 9;\n sum -= 9;\n } else {\n number[i] = sum;\n sum = 0;\n }\n }\n number[0] = sum + 1;\n cout<<\"Smallest number is \";\n for (int i=0; i<digit; i++)\n cout<<number[i];\n}\nint main() {\n int sum = 15, digit = 3;\n findSmallestNumWithSum(digit, sum);\n return 0;\n}" }, { "code": null, "e": 2748, "s": 2725, "text": "Smallest number is 159" } ]
Copy from clipboard using Python and Tkinter
To copy from clipboard, we can use the clipboard_get() method of Tkinter. Let's take an example and see how to get the data from the clipboard and display it on a Tkinter window. Import the tkinter library and create an instance of tkinter frame. Import the tkinter library and create an instance of tkinter frame. Set the size of the frame using geometry method. Set the size of the frame using geometry method. Next, call clipboard_get() to get the text from the clipboard and store the data in a variable "cliptext". Next, call clipboard_get() to get the text from the clipboard and store the data in a variable "cliptext". Create a label to the display the clipboard text. Pass cliptext as text, "text=cliptext". Create a label to the display the clipboard text. Pass cliptext as text, "text=cliptext". Finally, run the mainloop of the application window. Finally, run the mainloop of the application window. # Import the tkinter library from tkinter import * # Instance of tkinter canvas win = Tk() win.geometry("700x250") win.title("Data from Clipboard") # Get the data from the clipboard cliptext = win.clipboard_get() # Label to print clipboard text lab=Label(win, text = cliptext, font=("Calibri",15,"bold")) lab.pack(padx=20, pady=50) # Run the mainloop win.mainloop() It will produce the following output − It will display the contents of the clipboard on the window.
[ { "code": null, "e": 1241, "s": 1062, "text": "To copy from clipboard, we can use the clipboard_get() method of Tkinter. Let's take an example and see how to get the data from the clipboard and display it on a Tkinter window." }, { "code": null, "e": 1309, "s": 1241, "text": "Import the tkinter library and create an instance of tkinter frame." }, { "code": null, "e": 1377, "s": 1309, "text": "Import the tkinter library and create an instance of tkinter frame." }, { "code": null, "e": 1426, "s": 1377, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1475, "s": 1426, "text": "Set the size of the frame using geometry method." }, { "code": null, "e": 1582, "s": 1475, "text": "Next, call clipboard_get() to get the text from the clipboard and store the data in a variable \"cliptext\"." }, { "code": null, "e": 1689, "s": 1582, "text": "Next, call clipboard_get() to get the text from the clipboard and store the data in a variable \"cliptext\"." }, { "code": null, "e": 1779, "s": 1689, "text": "Create a label to the display the clipboard text. Pass cliptext as text, \"text=cliptext\"." }, { "code": null, "e": 1869, "s": 1779, "text": "Create a label to the display the clipboard text. Pass cliptext as text, \"text=cliptext\"." }, { "code": null, "e": 1922, "s": 1869, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 1975, "s": 1922, "text": "Finally, run the mainloop of the application window." }, { "code": null, "e": 2345, "s": 1975, "text": "# Import the tkinter library\nfrom tkinter import *\n\n# Instance of tkinter canvas\nwin = Tk()\nwin.geometry(\"700x250\")\nwin.title(\"Data from Clipboard\")\n\n# Get the data from the clipboard\ncliptext = win.clipboard_get()\n\n# Label to print clipboard text\nlab=Label(win, text = cliptext, font=(\"Calibri\",15,\"bold\"))\nlab.pack(padx=20, pady=50)\n\n# Run the mainloop\nwin.mainloop()" }, { "code": null, "e": 2384, "s": 2345, "text": "It will produce the following output −" }, { "code": null, "e": 2445, "s": 2384, "text": "It will display the contents of the clipboard on the window." } ]
Char.IsDigit() Method in C#
The Char.IsDigit() method in C# indicates whether the specified Unicode character is categorized as a decimal digit. Following is the syntax − public static bool IsDigit (char ch); Above, the parameter ch is the Unicode character to evaluate. Let us now see an example to implement the Char.IsDigit() method − using System; public class Demo { public static void Main(){ bool res; char val = 'g'; Console.WriteLine("Value = "+val); res = Char.IsDigit(val); Console.WriteLine("Is the value a digit? = "+res); } } This will produce the following output − Value = g Is the value a digit? = False Let us now see another example − using System; public class Demo { public static void Main(){ bool res; char val = '2'; Console.WriteLine("Value = "+val); res = Char.IsDigit(val); Console.WriteLine("Is the value a digit? = "+res); } } This will produce the following output − Value = 2 Is the value a digit? = True
[ { "code": null, "e": 1179, "s": 1062, "text": "The Char.IsDigit() method in C# indicates whether the specified Unicode character is categorized as a decimal digit." }, { "code": null, "e": 1205, "s": 1179, "text": "Following is the syntax −" }, { "code": null, "e": 1243, "s": 1205, "text": "public static bool IsDigit (char ch);" }, { "code": null, "e": 1305, "s": 1243, "text": "Above, the parameter ch is the Unicode character to evaluate." }, { "code": null, "e": 1372, "s": 1305, "text": "Let us now see an example to implement the Char.IsDigit() method −" }, { "code": null, "e": 1610, "s": 1372, "text": "using System;\npublic class Demo {\n public static void Main(){\n bool res;\n char val = 'g';\n Console.WriteLine(\"Value = \"+val);\n res = Char.IsDigit(val);\n Console.WriteLine(\"Is the value a digit? = \"+res);\n }\n}" }, { "code": null, "e": 1651, "s": 1610, "text": "This will produce the following output −" }, { "code": null, "e": 1691, "s": 1651, "text": "Value = g\nIs the value a digit? = False" }, { "code": null, "e": 1724, "s": 1691, "text": "Let us now see another example −" }, { "code": null, "e": 1962, "s": 1724, "text": "using System;\npublic class Demo {\n public static void Main(){\n bool res;\n char val = '2';\n Console.WriteLine(\"Value = \"+val);\n res = Char.IsDigit(val);\n Console.WriteLine(\"Is the value a digit? = \"+res);\n }\n}" }, { "code": null, "e": 2003, "s": 1962, "text": "This will produce the following output −" }, { "code": null, "e": 2042, "s": 2003, "text": "Value = 2\nIs the value a digit? = True" } ]
Java - String charAt() Method
This method returns the character located at the String's specified index. The string indexes start from zero. Here is the syntax of this method − public char charAt(int index) Here is the detail of parameters − index − Index of the character to be returned. index − Index of the character to be returned. This method returns a char at the specified index. public class Test { public static void main(String args[]) { String s = "Strings are immutable"; char result = s.charAt(8); System.out.println(result); } } This will produce the following result − a 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2377, "text": "This method returns the character located at the String's specified index. The string indexes start from zero." }, { "code": null, "e": 2524, "s": 2488, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2555, "s": 2524, "text": "public char charAt(int index)\n" }, { "code": null, "e": 2590, "s": 2555, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2637, "s": 2590, "text": "index − Index of the character to be returned." }, { "code": null, "e": 2684, "s": 2637, "text": "index − Index of the character to be returned." }, { "code": null, "e": 2735, "s": 2684, "text": "This method returns a char at the specified index." }, { "code": null, "e": 2916, "s": 2735, "text": "public class Test {\n\n public static void main(String args[]) {\n String s = \"Strings are immutable\";\n char result = s.charAt(8);\n System.out.println(result);\n }\n}" }, { "code": null, "e": 2957, "s": 2916, "text": "This will produce the following result −" }, { "code": null, "e": 2960, "s": 2957, "text": "a\n" }, { "code": null, "e": 2993, "s": 2960, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3009, "s": 2993, "text": " Malhar Lathkar" }, { "code": null, "e": 3042, "s": 3009, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3058, "s": 3042, "text": " Malhar Lathkar" }, { "code": null, "e": 3093, "s": 3058, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3107, "s": 3093, "text": " Anadi Sharma" }, { "code": null, "e": 3141, "s": 3107, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3155, "s": 3141, "text": " Tushar Kale" }, { "code": null, "e": 3192, "s": 3155, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3207, "s": 3192, "text": " Monica Mittal" }, { "code": null, "e": 3240, "s": 3207, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3259, "s": 3240, "text": " Arnab Chakraborty" }, { "code": null, "e": 3266, "s": 3259, "text": " Print" }, { "code": null, "e": 3277, "s": 3266, "text": " Add Notes" } ]
MongoDB - GridFS
GridFS is the MongoDB specification for storing and retrieving large files such as images, audio files, video files, etc. It is kind of a file system to store files but its data is stored within MongoDB collections. GridFS has the capability to store files even greater than its document size limit of 16MB. GridFS divides a file into chunks and stores each chunk of data in a separate document, each of maximum size 255k. GridFS by default uses two collections fs.files and fs.chunks to store the file's metadata and the chunks. Each chunk is identified by its unique _id ObjectId field. The fs.files serves as a parent document. The files_id field in the fs.chunks document links the chunk to its parent. Following is a sample document of fs.files collection − { "filename": "test.txt", "chunkSize": NumberInt(261120), "uploadDate": ISODate("2014-04-13T11:32:33.557Z"), "md5": "7b762939321e146569b07f72c62cca4f", "length": NumberInt(646) } The document specifies the file name, chunk size, uploaded date, and length. Following is a sample document of fs.chunks document − { "files_id": ObjectId("534a75d19f54bfec8a2fe44b"), "n": NumberInt(0), "data": "Mongo Binary Data" } Now, we will store an mp3 file using GridFS using the put command. For this, we will use the mongofiles.exe utility present in the bin folder of the MongoDB installation folder. Open your command prompt, navigate to the mongofiles.exe in the bin folder of MongoDB installation folder and type the following code − >mongofiles.exe -d gridfs put song.mp3 Here, gridfs is the name of the database in which the file will be stored. If the database is not present, MongoDB will automatically create a new document on the fly. Song.mp3 is the name of the file uploaded. To see the file's document in database, you can use find query − >db.fs.files.find() The above command returned the following document − { _id: ObjectId('534a811bf8b4aa4d33fdf94d'), filename: "song.mp3", chunkSize: 261120, uploadDate: new Date(1397391643474), md5: "e4f53379c909f7bed2e9d631e15c1c41", length: 10401959 } We can also see all the chunks present in fs.chunks collection related to the stored file with the following code, using the document id returned in the previous query − >db.fs.chunks.find({files_id:ObjectId('534a811bf8b4aa4d33fdf94d')}) In my case, the query returned 40 documents meaning that the whole mp3 document was divided in 40 chunks of data. 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2861, "s": 2553, "text": "GridFS is the MongoDB specification for storing and retrieving large files such as images, audio files, video files, etc. It is kind of a file system to store files but its data is stored within MongoDB collections. GridFS has the capability to store files even greater than its document size limit of 16MB." }, { "code": null, "e": 2976, "s": 2861, "text": "GridFS divides a file into chunks and stores each chunk of data in a separate document, each of maximum size 255k." }, { "code": null, "e": 3260, "s": 2976, "text": "GridFS by default uses two collections fs.files and fs.chunks to store the file's metadata and the chunks. Each chunk is identified by its unique _id ObjectId field. The fs.files serves as a parent document. The files_id field in the fs.chunks document links the chunk to its parent." }, { "code": null, "e": 3316, "s": 3260, "text": "Following is a sample document of fs.files collection −" }, { "code": null, "e": 3510, "s": 3316, "text": "{\n \"filename\": \"test.txt\",\n \"chunkSize\": NumberInt(261120),\n \"uploadDate\": ISODate(\"2014-04-13T11:32:33.557Z\"),\n \"md5\": \"7b762939321e146569b07f72c62cca4f\",\n \"length\": NumberInt(646)\n}" }, { "code": null, "e": 3587, "s": 3510, "text": "The document specifies the file name, chunk size, uploaded date, and length." }, { "code": null, "e": 3642, "s": 3587, "text": "Following is a sample document of fs.chunks document −" }, { "code": null, "e": 3752, "s": 3642, "text": "{\n \"files_id\": ObjectId(\"534a75d19f54bfec8a2fe44b\"),\n \"n\": NumberInt(0),\n \"data\": \"Mongo Binary Data\"\n}" }, { "code": null, "e": 3930, "s": 3752, "text": "Now, we will store an mp3 file using GridFS using the put command. For this, we will use the mongofiles.exe utility present in the bin folder of the MongoDB installation folder." }, { "code": null, "e": 4066, "s": 3930, "text": "Open your command prompt, navigate to the mongofiles.exe in the bin folder of MongoDB installation folder and type the following code −" }, { "code": null, "e": 4105, "s": 4066, "text": ">mongofiles.exe -d gridfs put song.mp3" }, { "code": null, "e": 4381, "s": 4105, "text": "Here, gridfs is the name of the database in which the file will be stored. If the database is not present, MongoDB will automatically create a new document on the fly. Song.mp3 is the name of the file uploaded. To see the file's document in database, you can use find query −" }, { "code": null, "e": 4401, "s": 4381, "text": ">db.fs.files.find()" }, { "code": null, "e": 4453, "s": 4401, "text": "The above command returned the following document −" }, { "code": null, "e": 4655, "s": 4453, "text": "{\n _id: ObjectId('534a811bf8b4aa4d33fdf94d'), \n filename: \"song.mp3\", \n chunkSize: 261120, \n uploadDate: new Date(1397391643474), md5: \"e4f53379c909f7bed2e9d631e15c1c41\",\n length: 10401959 \n}" }, { "code": null, "e": 4825, "s": 4655, "text": "We can also see all the chunks present in fs.chunks collection related to the stored file with the following code, using the document id returned in the previous query −" }, { "code": null, "e": 4893, "s": 4825, "text": ">db.fs.chunks.find({files_id:ObjectId('534a811bf8b4aa4d33fdf94d')})" }, { "code": null, "e": 5007, "s": 4893, "text": "In my case, the query returned 40 documents meaning that the whole mp3 document was divided in 40 chunks of data." }, { "code": null, "e": 5040, "s": 5007, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 5059, "s": 5040, "text": " Arnab Chakraborty" }, { "code": null, "e": 5094, "s": 5059, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5122, "s": 5094, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5157, "s": 5122, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5180, "s": 5157, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5215, "s": 5180, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5232, "s": 5215, "text": " University Code" }, { "code": null, "e": 5265, "s": 5232, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 5284, "s": 5265, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 5319, "s": 5284, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5339, "s": 5319, "text": " Skillbakerystudios" }, { "code": null, "e": 5346, "s": 5339, "text": " Print" }, { "code": null, "e": 5357, "s": 5346, "text": " Add Notes" } ]
Common Divisors of Two Numbers - GeeksforGeeks
29 Jun, 2021 Given two integer numbers, the task is to find count of all common divisors of given numbers? Examples : Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4 It is recommended to refer all divisors of a given number as a prerequisite of this article. Naive Solution A simple solution is to first find all divisors of first number and store them in an array or hash. Then find common divisors of second number and store them. Finally print common elements of two stored arrays or hash. The key is that the magnitude of powers of prime factors of a divisor should be equal to the minimum power of two prime factors of a and b. Find the prime factors of a using prime factorization. Find the count of each prime factor of a and store it in a Hashmap. Prime factorize b using distinct prime factors of a. Then the total number of divisors would be equal to the product of (count + 1) of each factor. count is the minimum of counts of each prime factors of a and b. This gives the count of all divisors of a and b. C++ Java Python3 C# Javascript // C++ implementation of program#include <bits/stdc++.h>using namespace std; // Map to store the count of each// prime factor of amap<int, int> ma; // Function that calculate the count of// each prime factor of a numbervoid primeFactorize(int a){ for(int i = 2; i * i <= a; i += 2) { int cnt = 0; while (a % i == 0) { cnt++; a /= i; } ma[i] = cnt; } if (a > 1) { ma[a] = 1; }} // Function to calculate all common// divisors of two given numbers// a, b --> input integer numbersint commDiv(int a, int b){ // Find count of each prime factor of a primeFactorize(a); // stores number of common divisors int res = 1; // Find the count of prime factors // of b using distinct prime factors of a for(auto m = ma.begin(); m != ma.end(); m++) { int cnt = 0; int key = m->first; int value = m->second; while (b % key == 0) { b /= key; cnt++; } // Prime factor of common divisor // has minimum cnt of both a and b res *= (min(cnt, value) + 1); } return res;} // Driver code int main(){ int a = 12, b = 24; cout << commDiv(a, b) << endl; return 0;} // This code is contributed by divyeshrabadiya07 // Java implementation of programimport java.util.*;import java.io.*; class GFG { // map to store the count of each prime factor of a static HashMap<Integer, Integer> ma = new HashMap<>(); // method that calculate the count of // each prime factor of a number static void primeFactorize(int a) { for (int i = 2; i * i <= a; i += 2) { int cnt = 0; while (a % i == 0) { cnt++; a /= i; } ma.put(i, cnt); } if (a > 1) ma.put(a, 1); } // method to calculate all common divisors // of two given numbers // a, b --> input integer numbers static int commDiv(int a, int b) { // Find count of each prime factor of a primeFactorize(a); // stores number of common divisors int res = 1; // Find the count of prime factors of b using // distinct prime factors of a for (Map.Entry<Integer, Integer> m : ma.entrySet()) { int cnt = 0; int key = m.getKey(); int value = m.getValue(); while (b % key == 0) { b /= key; cnt++; } // prime factor of common divisor // has minimum cnt of both a and b res *= (Math.min(cnt, value) + 1); } return res; } // Driver method public static void main(String args[]) { int a = 12, b = 24; System.out.println(commDiv(a, b)); }} # Python3 implementation of programimport math # Map to store the count of each# prime factor of ama = {} # Function that calculate the count of# each prime factor of a numberdef primeFactorize(a): sqt = int(math.sqrt(a)) for i in range(2, sqt, 2): cnt = 0 while (a % i == 0): cnt += 1 a /= i ma[i] = cnt if (a > 1): ma[a] = 1 # Function to calculate all common# divisors of two given numbers# a, b --> input integer numbersdef commDiv(a, b): # Find count of each prime factor of a primeFactorize(a) # stores number of common divisors res = 1 # Find the count of prime factors # of b using distinct prime factors of a for key, value in ma.items(): cnt = 0 while (b % key == 0): b /= key cnt += 1 # Prime factor of common divisor # has minimum cnt of both a and b res *= (min(cnt, value) + 1) return res # Driver code a = 12b = 24 print(commDiv(a, b)) # This code is contributed by Stream_Cipher // C# implementation of programusing System;using System.Collections.Generic; class GFG{ // Map to store the count of each// prime factor of astatic Dictionary<int, int> ma = new Dictionary<int, int>(); // Function that calculate the count of// each prime factor of a numberstatic void primeFactorize(int a){ for(int i = 2; i * i <= a; i += 2) { int cnt = 0; while (a % i == 0) { cnt++; a /= i; } ma.Add(i, cnt); } if (a > 1) ma.Add(a, 1);} // Function to calculate all common// divisors of two given numbers// a, b --> input integer numbersstatic int commDiv(int a, int b){ // Find count of each prime factor of a primeFactorize(a); // Stores number of common divisors int res = 1; // Find the count of prime factors // of b using distinct prime factors of a foreach(KeyValuePair<int, int> m in ma) { int cnt = 0; int key = m.Key; int value = m.Value; while (b % key == 0) { b /= key; cnt++; } // Prime factor of common divisor // has minimum cnt of both a and b res *= (Math.Min(cnt, value) + 1); } return res;} // Driver code static void Main(){ int a = 12, b = 24; Console.WriteLine(commDiv(a, b));}} // This code is contributed by divyesh072019 <script> // JavaScript implementation of program // Map to store the count of each // prime factor of a let ma = new Map(); // Function that calculate the count of // each prime factor of a number function primeFactorize(a) { for(let i = 2; i * i <= a; i += 2) { let cnt = 0; while (a % i == 0) { cnt++; a = parseInt(a / i, 10); } ma.set(i, cnt); } if (a > 1) { ma.set(a, 1); } } // Function to calculate all common // divisors of two given numbers // a, b --> input integer numbers function commDiv(a,b) { // Find count of each prime factor of a primeFactorize(a); // stores number of common divisors let res = 1; // Find the count of prime factors // of b using distinct prime factors of a ma.forEach((values,keys)=>{ let cnt = 0; let key = keys; let value = values; while (b % key == 0) { b = parseInt(b / key, 10); cnt++; } // Prime factor of common divisor // has minimum cnt of both a and b res *= (Math.min(cnt, value) + 1); }) return res; } // Driver code let a = 12, b = 24; document.write(commDiv(a, b)); </script> Output: 6 Efficient Solution – A better solution is to calculate the greatest common divisor (gcd) of given two numbers, and then count divisors of that gcd. C++ Java Python3 C# PHP Javascript // C++ implementation of program#include <bits/stdc++.h>using namespace std; // Function to calculate gcd of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate all common divisors// of two given numbers// a, b --> input integer numbersint commDiv(int a, int b){ // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result;} // Driver program to run the caseint main(){ int a = 12, b = 24; cout << commDiv(a, b); return 0;} // Java implementation of program class Test { // method to calculate gcd of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to calculate all common divisors // of two given numbers // a, b --> input integer numbers static int commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } // Driver method public static void main(String args[]) { int a = 12, b = 24; System.out.println(commDiv(a, b)); }} # Python implementation of programfrom math import sqrt # Function to calculate gcd of two numbersdef gcd(a, b): if a == 0: return b return gcd(b % a, a) # Function to calculate all common divisors# of two given numbers# a, b --> input integer numbersdef commDiv(a, b): # find GCD of a, b n = gcd(a, b) # Count divisors of n result = 0 for i in range(1,int(sqrt(n))+1): # if i is a factor of n if n % i == 0: # check if divisors are equal if n/i == i: result += 1 else: result += 2 return result # Driver program to run the caseif __name__ == "__main__": a = 12 b = 24; print(commDiv(a, b)) // C# implementation of programusing System; class GFG { // method to calculate gcd // of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to calculate all // common divisors of two // given numbers a, b --> // input integer numbers static int commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= Math.Sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } // Driver method public static void Main(String[] args) { int a = 12, b = 24; Console.Write(commDiv(a, b)); }} // This code contributed by parashar. <?php// PHP implementation of program // Function to calculate// gcd of two numbersfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to calculate all common// divisors of two given numbers// a, b --> input integer numbersfunction commDiv($a, $b){ // find gcd of a, b $n = gcd($a, $b); // Count divisors of n. $result = 0; for ($i = 1; $i <= sqrt($n); $i++) { // if 'i' is factor of n if ($n % $i == 0) { // check if divisors // are equal if ($n / $i == $i) $result += 1; else $result += 2; } } return $result;} // Driver Code$a = 12; $b = 24;echo(commDiv($a, $b)); // This code is contributed by Ajit.?> <script> // Javascript implementation of program // Function to calculate gcd of two numbers function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // Function to calculate all common divisors // of two given numbers // a, b --> input integer numbers function commDiv(a, b) { // find gcd of a, b let n = gcd(a, b); // Count divisors of n. let result = 0; for (let i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } let a = 12, b = 24; document.write(commDiv(a, b)); </script> Output : 6 Time complexity: O(log(n)+ n1/2) where n is the gcd of two numbers. This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. parashar jit_t Ganeshchowdharysadanala divyeshrabadiya07 divyesh072019 Stream_Cipher mukesh07 vaibhavrabadiya3 divisors number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Minimum number of jumps to reach end Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 24622, "s": 24594, "text": "\n29 Jun, 2021" }, { "code": null, "e": 24716, "s": 24622, "text": "Given two integer numbers, the task is to find count of all common divisors of given numbers?" }, { "code": null, "e": 24728, "s": 24716, "text": "Examples : " }, { "code": null, "e": 24944, "s": 24728, "text": "Input : a = 12, b = 24\nOutput: 6\n// all common divisors are 1, 2, 3, \n// 4, 6 and 12\n\nInput : a = 3, b = 17\nOutput: 1\n// all common divisors are 1\n\nInput : a = 20, b = 36\nOutput: 3\n// all common divisors are 1, 2, 4" }, { "code": null, "e": 25038, "s": 24944, "text": "It is recommended to refer all divisors of a given number as a prerequisite of this article. " }, { "code": null, "e": 25412, "s": 25038, "text": "Naive Solution A simple solution is to first find all divisors of first number and store them in an array or hash. Then find common divisors of second number and store them. Finally print common elements of two stored arrays or hash. The key is that the magnitude of powers of prime factors of a divisor should be equal to the minimum power of two prime factors of a and b." }, { "code": null, "e": 25467, "s": 25412, "text": "Find the prime factors of a using prime factorization." }, { "code": null, "e": 25535, "s": 25467, "text": "Find the count of each prime factor of a and store it in a Hashmap." }, { "code": null, "e": 25588, "s": 25535, "text": "Prime factorize b using distinct prime factors of a." }, { "code": null, "e": 25683, "s": 25588, "text": "Then the total number of divisors would be equal to the product of (count + 1) of each factor." }, { "code": null, "e": 25748, "s": 25683, "text": "count is the minimum of counts of each prime factors of a and b." }, { "code": null, "e": 25797, "s": 25748, "text": "This gives the count of all divisors of a and b." }, { "code": null, "e": 25801, "s": 25797, "text": "C++" }, { "code": null, "e": 25806, "s": 25801, "text": "Java" }, { "code": null, "e": 25814, "s": 25806, "text": "Python3" }, { "code": null, "e": 25817, "s": 25814, "text": "C#" }, { "code": null, "e": 25828, "s": 25817, "text": "Javascript" }, { "code": "// C++ implementation of program#include <bits/stdc++.h>using namespace std; // Map to store the count of each// prime factor of amap<int, int> ma; // Function that calculate the count of// each prime factor of a numbervoid primeFactorize(int a){ for(int i = 2; i * i <= a; i += 2) { int cnt = 0; while (a % i == 0) { cnt++; a /= i; } ma[i] = cnt; } if (a > 1) { ma[a] = 1; }} // Function to calculate all common// divisors of two given numbers// a, b --> input integer numbersint commDiv(int a, int b){ // Find count of each prime factor of a primeFactorize(a); // stores number of common divisors int res = 1; // Find the count of prime factors // of b using distinct prime factors of a for(auto m = ma.begin(); m != ma.end(); m++) { int cnt = 0; int key = m->first; int value = m->second; while (b % key == 0) { b /= key; cnt++; } // Prime factor of common divisor // has minimum cnt of both a and b res *= (min(cnt, value) + 1); } return res;} // Driver code int main(){ int a = 12, b = 24; cout << commDiv(a, b) << endl; return 0;} // This code is contributed by divyeshrabadiya07", "e": 27153, "s": 25828, "text": null }, { "code": "// Java implementation of programimport java.util.*;import java.io.*; class GFG { // map to store the count of each prime factor of a static HashMap<Integer, Integer> ma = new HashMap<>(); // method that calculate the count of // each prime factor of a number static void primeFactorize(int a) { for (int i = 2; i * i <= a; i += 2) { int cnt = 0; while (a % i == 0) { cnt++; a /= i; } ma.put(i, cnt); } if (a > 1) ma.put(a, 1); } // method to calculate all common divisors // of two given numbers // a, b --> input integer numbers static int commDiv(int a, int b) { // Find count of each prime factor of a primeFactorize(a); // stores number of common divisors int res = 1; // Find the count of prime factors of b using // distinct prime factors of a for (Map.Entry<Integer, Integer> m : ma.entrySet()) { int cnt = 0; int key = m.getKey(); int value = m.getValue(); while (b % key == 0) { b /= key; cnt++; } // prime factor of common divisor // has minimum cnt of both a and b res *= (Math.min(cnt, value) + 1); } return res; } // Driver method public static void main(String args[]) { int a = 12, b = 24; System.out.println(commDiv(a, b)); }}", "e": 28657, "s": 27153, "text": null }, { "code": "# Python3 implementation of programimport math # Map to store the count of each# prime factor of ama = {} # Function that calculate the count of# each prime factor of a numberdef primeFactorize(a): sqt = int(math.sqrt(a)) for i in range(2, sqt, 2): cnt = 0 while (a % i == 0): cnt += 1 a /= i ma[i] = cnt if (a > 1): ma[a] = 1 # Function to calculate all common# divisors of two given numbers# a, b --> input integer numbersdef commDiv(a, b): # Find count of each prime factor of a primeFactorize(a) # stores number of common divisors res = 1 # Find the count of prime factors # of b using distinct prime factors of a for key, value in ma.items(): cnt = 0 while (b % key == 0): b /= key cnt += 1 # Prime factor of common divisor # has minimum cnt of both a and b res *= (min(cnt, value) + 1) return res # Driver code a = 12b = 24 print(commDiv(a, b)) # This code is contributed by Stream_Cipher", "e": 29788, "s": 28657, "text": null }, { "code": "// C# implementation of programusing System;using System.Collections.Generic; class GFG{ // Map to store the count of each// prime factor of astatic Dictionary<int, int> ma = new Dictionary<int, int>(); // Function that calculate the count of// each prime factor of a numberstatic void primeFactorize(int a){ for(int i = 2; i * i <= a; i += 2) { int cnt = 0; while (a % i == 0) { cnt++; a /= i; } ma.Add(i, cnt); } if (a > 1) ma.Add(a, 1);} // Function to calculate all common// divisors of two given numbers// a, b --> input integer numbersstatic int commDiv(int a, int b){ // Find count of each prime factor of a primeFactorize(a); // Stores number of common divisors int res = 1; // Find the count of prime factors // of b using distinct prime factors of a foreach(KeyValuePair<int, int> m in ma) { int cnt = 0; int key = m.Key; int value = m.Value; while (b % key == 0) { b /= key; cnt++; } // Prime factor of common divisor // has minimum cnt of both a and b res *= (Math.Min(cnt, value) + 1); } return res;} // Driver code static void Main(){ int a = 12, b = 24; Console.WriteLine(commDiv(a, b));}} // This code is contributed by divyesh072019", "e": 31233, "s": 29788, "text": null }, { "code": "<script> // JavaScript implementation of program // Map to store the count of each // prime factor of a let ma = new Map(); // Function that calculate the count of // each prime factor of a number function primeFactorize(a) { for(let i = 2; i * i <= a; i += 2) { let cnt = 0; while (a % i == 0) { cnt++; a = parseInt(a / i, 10); } ma.set(i, cnt); } if (a > 1) { ma.set(a, 1); } } // Function to calculate all common // divisors of two given numbers // a, b --> input integer numbers function commDiv(a,b) { // Find count of each prime factor of a primeFactorize(a); // stores number of common divisors let res = 1; // Find the count of prime factors // of b using distinct prime factors of a ma.forEach((values,keys)=>{ let cnt = 0; let key = keys; let value = values; while (b % key == 0) { b = parseInt(b / key, 10); cnt++; } // Prime factor of common divisor // has minimum cnt of both a and b res *= (Math.min(cnt, value) + 1); }) return res; } // Driver code let a = 12, b = 24; document.write(commDiv(a, b)); </script>", "e": 32667, "s": 31233, "text": null }, { "code": null, "e": 32676, "s": 32667, "text": "Output: " }, { "code": null, "e": 32678, "s": 32676, "text": "6" }, { "code": null, "e": 32827, "s": 32678, "text": "Efficient Solution – A better solution is to calculate the greatest common divisor (gcd) of given two numbers, and then count divisors of that gcd. " }, { "code": null, "e": 32831, "s": 32827, "text": "C++" }, { "code": null, "e": 32836, "s": 32831, "text": "Java" }, { "code": null, "e": 32844, "s": 32836, "text": "Python3" }, { "code": null, "e": 32847, "s": 32844, "text": "C#" }, { "code": null, "e": 32851, "s": 32847, "text": "PHP" }, { "code": null, "e": 32862, "s": 32851, "text": "Javascript" }, { "code": "// C++ implementation of program#include <bits/stdc++.h>using namespace std; // Function to calculate gcd of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate all common divisors// of two given numbers// a, b --> input integer numbersint commDiv(int a, int b){ // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result;} // Driver program to run the caseint main(){ int a = 12, b = 24; cout << commDiv(a, b); return 0;}", "e": 33661, "s": 32862, "text": null }, { "code": "// Java implementation of program class Test { // method to calculate gcd of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to calculate all common divisors // of two given numbers // a, b --> input integer numbers static int commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } // Driver method public static void main(String args[]) { int a = 12, b = 24; System.out.println(commDiv(a, b)); }}", "e": 34591, "s": 33661, "text": null }, { "code": "# Python implementation of programfrom math import sqrt # Function to calculate gcd of two numbersdef gcd(a, b): if a == 0: return b return gcd(b % a, a) # Function to calculate all common divisors# of two given numbers# a, b --> input integer numbersdef commDiv(a, b): # find GCD of a, b n = gcd(a, b) # Count divisors of n result = 0 for i in range(1,int(sqrt(n))+1): # if i is a factor of n if n % i == 0: # check if divisors are equal if n/i == i: result += 1 else: result += 2 return result # Driver program to run the caseif __name__ == \"__main__\": a = 12 b = 24; print(commDiv(a, b))", "e": 35332, "s": 34591, "text": null }, { "code": "// C# implementation of programusing System; class GFG { // method to calculate gcd // of two numbers static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to calculate all // common divisors of two // given numbers a, b --> // input integer numbers static int commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= Math.Sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } // Driver method public static void Main(String[] args) { int a = 12, b = 24; Console.Write(commDiv(a, b)); }} // This code contributed by parashar.", "e": 36325, "s": 35332, "text": null }, { "code": "<?php// PHP implementation of program // Function to calculate// gcd of two numbersfunction gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to calculate all common// divisors of two given numbers// a, b --> input integer numbersfunction commDiv($a, $b){ // find gcd of a, b $n = gcd($a, $b); // Count divisors of n. $result = 0; for ($i = 1; $i <= sqrt($n); $i++) { // if 'i' is factor of n if ($n % $i == 0) { // check if divisors // are equal if ($n / $i == $i) $result += 1; else $result += 2; } } return $result;} // Driver Code$a = 12; $b = 24;echo(commDiv($a, $b)); // This code is contributed by Ajit.?>", "e": 37119, "s": 36325, "text": null }, { "code": "<script> // Javascript implementation of program // Function to calculate gcd of two numbers function gcd(a, b) { if (a == 0) return b; return gcd(b % a, a); } // Function to calculate all common divisors // of two given numbers // a, b --> input integer numbers function commDiv(a, b) { // find gcd of a, b let n = gcd(a, b); // Count divisors of n. let result = 0; for (let i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result; } let a = 12, b = 24; document.write(commDiv(a, b)); </script>", "e": 37972, "s": 37119, "text": null }, { "code": null, "e": 37983, "s": 37972, "text": "Output : " }, { "code": null, "e": 37985, "s": 37983, "text": "6" }, { "code": null, "e": 38053, "s": 37985, "text": "Time complexity: O(log(n)+ n1/2) where n is the gcd of two numbers." }, { "code": null, "e": 38362, "s": 38053, "text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 38487, "s": 38362, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38496, "s": 38487, "text": "parashar" }, { "code": null, "e": 38502, "s": 38496, "text": "jit_t" }, { "code": null, "e": 38526, "s": 38502, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 38544, "s": 38526, "text": "divyeshrabadiya07" }, { "code": null, "e": 38558, "s": 38544, "text": "divyesh072019" }, { "code": null, "e": 38572, "s": 38558, "text": "Stream_Cipher" }, { "code": null, "e": 38581, "s": 38572, "text": "mukesh07" }, { "code": null, "e": 38598, "s": 38581, "text": "vaibhavrabadiya3" }, { "code": null, "e": 38607, "s": 38598, "text": "divisors" }, { "code": null, "e": 38621, "s": 38607, "text": "number-theory" }, { "code": null, "e": 38634, "s": 38621, "text": "Mathematical" }, { "code": null, "e": 38648, "s": 38634, "text": "number-theory" }, { "code": null, "e": 38661, "s": 38648, "text": "Mathematical" }, { "code": null, "e": 38759, "s": 38661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38783, "s": 38759, "text": "Merge two sorted arrays" }, { "code": null, "e": 38826, "s": 38783, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38840, "s": 38826, "text": "Prime Numbers" }, { "code": null, "e": 38889, "s": 38840, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 38923, "s": 38889, "text": "Program for factorial of a number" }, { "code": null, "e": 38944, "s": 38923, "text": "Operators in C / C++" }, { "code": null, "e": 38987, "s": 38944, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 39040, "s": 38987, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 39077, "s": 39040, "text": "Minimum number of jumps to reach end" } ]
Bootstrap Estimates and Experimentation | by Charles Copley | Towards Data Science
Many digital experiments carried out these days can be happily analyzed using frequentist statistical methods since we expect the data to be normally distributed. However, there are certain metrics that are not so easy. Take, for example, an experiment designed to increase tax collections, or to pay an invoice. If all the invoices were either fully paid, or not paid at all, this could be analyzed with a binomial proportion test or a chi-squared test. However, a certain fraction of the invoices will be partially paid, making these tests unsuitable. Even if we tried to compare the actual bill distributions, these are likely to be some form of exponential distribution with many small bills and fewer large bills, as shown below. So what to do? One way to handle this is to use random sampling statistical tools, often referred to as Monte Carlo Simulations. Two that are particularly relevant in assessing the results of an experiment are bootstrapping (which is useful for determining the distribution of a statistical parameter like the mean) and permutation testing (used to determine if there is a difference in a statistic between two distributions, and how likely that difference is to be real as opposed to by chance). In this post we will deal with bootstrapping. Bootstrapping uses the concept of sampling-with-replacement to generate the distribution of a parameter. To illustrate this, let’s say we want to estimate the average height of twenty flowers. Without access to a computer, we would go about this as follows: Measure each flower and record the flower ID and height on a piece of paperCalculate the average height of the flowers in your sample and write this down. Measure each flower and record the flower ID and height on a piece of paper Calculate the average height of the flowers in your sample and write this down. And now for the fun and (slightly) magical part... Put the pieces of paper in a hat and choose one at random.Write down the height of the flower you chose, and put the paper back in the hat.Choose again at random- you might choose the same one again! This is called sampling-with-replacement.Repeat 20 times to correspond with the original sample size. These should be the same.Calculate the average AGAIN and write this down- that is the second estimate of the average. Put the pieces of paper in a hat and choose one at random. Write down the height of the flower you chose, and put the paper back in the hat. Choose again at random- you might choose the same one again! This is called sampling-with-replacement. Repeat 20 times to correspond with the original sample size. These should be the same. Calculate the average AGAIN and write this down- that is the second estimate of the average. If you repeat the above 1000 times, you will end up with 1000 slightly different estimates for the average- and those estimates will be: Normally distributed,Provide the standard error of the mean value of your estimate of the average height of the flowers. Normally distributed, Provide the standard error of the mean value of your estimate of the average height of the flowers. In (very unoptimized but perhaps more readable?!) Python we can do the above as follows: #generate a few normally distributed heights for demonstrationN_flowers = 20flower_heights = np.random.normal(5,size = N_flowers)data_points = flower_heightsnumber_of_bootstraps = 1000average_estimate = [np.mean(data_points)]for j in range(0,number_of_bootstraps): random_sample = [] for i in range(0,len(data_points)): random_sample.append(np.random.choice(data_points)) average_estimate.append(np.mean(random_sample))ax = sns.distplot(average_estimate, bins = 100).set_title('Average Flower Heights')plt.xlabel("Height [cm]")plt.ylabel("Count") As a sanity check, it’s worth comparing the bootstrapped standard error with the standard error we would expect from a normal distribution using frequentist methods. The standard error of the mean (SE) for a normal distribution with standard deviation σ, and sample size N, is given below: We can compare the above to our bootstrapped estimate by using: #normal distribution estimatestd_error_mean = np.std(flower_heights) / np.sqrt(N_flowers) -- 0.1983#bootstrap estimatebootstrap_estimate = np.std(average_estimate) -- 0.1977 I hear some of you muttering in the background- big deal! We could have done this without all this random choice nonsense.... BUT... what if (instead of flowers) we had some other sample that wasn’t normally distributed? What about bills which typically have some sort of exponential distribution? What is the mean of the bills shown below? More importantly for experimentation (where we’re trying to determine if there is a difference between two means or other statistical parameter) what is the standard error on that mean estimate ? bill_size = np.random.pareto(1,200)sns.distplot(pareto).set_title("Average Bill Size")plt.xlabel("Bill ($)")plt.ylabel("Count") That's a bit more tricky isn’t it... Let's try estimating this using a bootstrap technique, but this time let’s tidy things up a bit and use a function... def get_bootstrap_mean(data_values, n_bootstraps): ''' data_values: Pandas Dataframe n_bootstrapes: Number of bootstrap estimates to calculate Return: Pandas Dataframe of the mean estimates ''' bootstrap_means = [] for j in range(0, n_bootstraps): sample = data_values.sample(frac=1, replace=True).copy() bootstrap_means.append(sample.mean()) return(pd.DataFrame(bootstrap_means))bill_size_experiment_a = pd.DataFrame(np.random.exponential(3,10000) )average_estimate_a = get_bootstrap_mean(bill_size_experiment_a, 100)ax = sns.distplot(average_estimate_a, bins = 100).set_title('Average Bill Size Experiment Arm A')plt.xlabel("Bill Amount ($)")plt.ylabel("Count") Great! But what does this mean for experimentation? Well, for experiments we would like to convince ourselves that the intervention has actually had an effect. For example, imagine we ran an experiment that was designed to increase the average repayment? How would we know it had worked? We could compare the bootstrapped mean distributions as below: bill_size_experiment_b = 1.1 +pd.DataFrame(np.random.exponential(3,10000) )average_estimate_b = get_bootstrap_mean(bill_size_experiment_b, 100) And then compare the two histograms as done below (where A and B are experiment arms A and B respectively): fig, ax = plt.subplots()for a in [average_estimate_a, average_estimate_b]: sns.distplot(a, bins = 20, ax=ax, kde=False)plt.legend(["A","B"])plt.title("Comparison of the Bill Bootstrapped Means")plt.xlabel("Bill Amount ($)")plt.ylabel("Count") A great thing, is that we can now use a t-test to compare the two mean distributions t2, p2 = stats.ttest_ind(average_estimate_a,average_estimate_b) For the above we get a p~0 i.e. there is a nearly zero percent probability that the means of the two samples are the same. If these were representative of two experimental conditions, we could safely assume that there is a difference between them. This is a VERY powerful technique- it can be used to estimate the standard error of any statistical parameter no matter what the underlying data distribution. Also, the resulting estimate is normally distributed, making it easy to compare using standard frequentist techniques. In the next post I will describe permutation tests. These are used specifically to determine the likelihood that a parameter differs between two distributions.
[ { "code": null, "e": 907, "s": 172, "text": "Many digital experiments carried out these days can be happily analyzed using frequentist statistical methods since we expect the data to be normally distributed. However, there are certain metrics that are not so easy. Take, for example, an experiment designed to increase tax collections, or to pay an invoice. If all the invoices were either fully paid, or not paid at all, this could be analyzed with a binomial proportion test or a chi-squared test. However, a certain fraction of the invoices will be partially paid, making these tests unsuitable. Even if we tried to compare the actual bill distributions, these are likely to be some form of exponential distribution with many small bills and fewer large bills, as shown below." }, { "code": null, "e": 1450, "s": 907, "text": "So what to do? One way to handle this is to use random sampling statistical tools, often referred to as Monte Carlo Simulations. Two that are particularly relevant in assessing the results of an experiment are bootstrapping (which is useful for determining the distribution of a statistical parameter like the mean) and permutation testing (used to determine if there is a difference in a statistic between two distributions, and how likely that difference is to be real as opposed to by chance). In this post we will deal with bootstrapping." }, { "code": null, "e": 1708, "s": 1450, "text": "Bootstrapping uses the concept of sampling-with-replacement to generate the distribution of a parameter. To illustrate this, let’s say we want to estimate the average height of twenty flowers. Without access to a computer, we would go about this as follows:" }, { "code": null, "e": 1863, "s": 1708, "text": "Measure each flower and record the flower ID and height on a piece of paperCalculate the average height of the flowers in your sample and write this down." }, { "code": null, "e": 1939, "s": 1863, "text": "Measure each flower and record the flower ID and height on a piece of paper" }, { "code": null, "e": 2019, "s": 1939, "text": "Calculate the average height of the flowers in your sample and write this down." }, { "code": null, "e": 2070, "s": 2019, "text": "And now for the fun and (slightly) magical part..." }, { "code": null, "e": 2490, "s": 2070, "text": "Put the pieces of paper in a hat and choose one at random.Write down the height of the flower you chose, and put the paper back in the hat.Choose again at random- you might choose the same one again! This is called sampling-with-replacement.Repeat 20 times to correspond with the original sample size. These should be the same.Calculate the average AGAIN and write this down- that is the second estimate of the average." }, { "code": null, "e": 2549, "s": 2490, "text": "Put the pieces of paper in a hat and choose one at random." }, { "code": null, "e": 2631, "s": 2549, "text": "Write down the height of the flower you chose, and put the paper back in the hat." }, { "code": null, "e": 2734, "s": 2631, "text": "Choose again at random- you might choose the same one again! This is called sampling-with-replacement." }, { "code": null, "e": 2821, "s": 2734, "text": "Repeat 20 times to correspond with the original sample size. These should be the same." }, { "code": null, "e": 2914, "s": 2821, "text": "Calculate the average AGAIN and write this down- that is the second estimate of the average." }, { "code": null, "e": 3051, "s": 2914, "text": "If you repeat the above 1000 times, you will end up with 1000 slightly different estimates for the average- and those estimates will be:" }, { "code": null, "e": 3172, "s": 3051, "text": "Normally distributed,Provide the standard error of the mean value of your estimate of the average height of the flowers." }, { "code": null, "e": 3194, "s": 3172, "text": "Normally distributed," }, { "code": null, "e": 3294, "s": 3194, "text": "Provide the standard error of the mean value of your estimate of the average height of the flowers." }, { "code": null, "e": 3383, "s": 3294, "text": "In (very unoptimized but perhaps more readable?!) Python we can do the above as follows:" }, { "code": null, "e": 3946, "s": 3383, "text": "#generate a few normally distributed heights for demonstrationN_flowers = 20flower_heights = np.random.normal(5,size = N_flowers)data_points = flower_heightsnumber_of_bootstraps = 1000average_estimate = [np.mean(data_points)]for j in range(0,number_of_bootstraps): random_sample = [] for i in range(0,len(data_points)): random_sample.append(np.random.choice(data_points)) average_estimate.append(np.mean(random_sample))ax = sns.distplot(average_estimate, bins = 100).set_title('Average Flower Heights')plt.xlabel(\"Height [cm]\")plt.ylabel(\"Count\")" }, { "code": null, "e": 4236, "s": 3946, "text": "As a sanity check, it’s worth comparing the bootstrapped standard error with the standard error we would expect from a normal distribution using frequentist methods. The standard error of the mean (SE) for a normal distribution with standard deviation σ, and sample size N, is given below:" }, { "code": null, "e": 4300, "s": 4236, "text": "We can compare the above to our bootstrapped estimate by using:" }, { "code": null, "e": 4474, "s": 4300, "text": "#normal distribution estimatestd_error_mean = np.std(flower_heights) / np.sqrt(N_flowers) -- 0.1983#bootstrap estimatebootstrap_estimate = np.std(average_estimate) -- 0.1977" }, { "code": null, "e": 4600, "s": 4474, "text": "I hear some of you muttering in the background- big deal! We could have done this without all this random choice nonsense...." }, { "code": null, "e": 4772, "s": 4600, "text": "BUT... what if (instead of flowers) we had some other sample that wasn’t normally distributed? What about bills which typically have some sort of exponential distribution?" }, { "code": null, "e": 5011, "s": 4772, "text": "What is the mean of the bills shown below? More importantly for experimentation (where we’re trying to determine if there is a difference between two means or other statistical parameter) what is the standard error on that mean estimate ?" }, { "code": null, "e": 5139, "s": 5011, "text": "bill_size = np.random.pareto(1,200)sns.distplot(pareto).set_title(\"Average Bill Size\")plt.xlabel(\"Bill ($)\")plt.ylabel(\"Count\")" }, { "code": null, "e": 5176, "s": 5139, "text": "That's a bit more tricky isn’t it..." }, { "code": null, "e": 5294, "s": 5176, "text": "Let's try estimating this using a bootstrap technique, but this time let’s tidy things up a bit and use a function..." }, { "code": null, "e": 5999, "s": 5294, "text": "def get_bootstrap_mean(data_values, n_bootstraps): ''' data_values: Pandas Dataframe n_bootstrapes: Number of bootstrap estimates to calculate Return: Pandas Dataframe of the mean estimates ''' bootstrap_means = [] for j in range(0, n_bootstraps): sample = data_values.sample(frac=1, replace=True).copy() bootstrap_means.append(sample.mean()) return(pd.DataFrame(bootstrap_means))bill_size_experiment_a = pd.DataFrame(np.random.exponential(3,10000) )average_estimate_a = get_bootstrap_mean(bill_size_experiment_a, 100)ax = sns.distplot(average_estimate_a, bins = 100).set_title('Average Bill Size Experiment Arm A')plt.xlabel(\"Bill Amount ($)\")plt.ylabel(\"Count\")" }, { "code": null, "e": 6350, "s": 5999, "text": "Great! But what does this mean for experimentation? Well, for experiments we would like to convince ourselves that the intervention has actually had an effect. For example, imagine we ran an experiment that was designed to increase the average repayment? How would we know it had worked? We could compare the bootstrapped mean distributions as below:" }, { "code": null, "e": 6494, "s": 6350, "text": "bill_size_experiment_b = 1.1 +pd.DataFrame(np.random.exponential(3,10000) )average_estimate_b = get_bootstrap_mean(bill_size_experiment_b, 100)" }, { "code": null, "e": 6602, "s": 6494, "text": "And then compare the two histograms as done below (where A and B are experiment arms A and B respectively):" }, { "code": null, "e": 6848, "s": 6602, "text": "fig, ax = plt.subplots()for a in [average_estimate_a, average_estimate_b]: sns.distplot(a, bins = 20, ax=ax, kde=False)plt.legend([\"A\",\"B\"])plt.title(\"Comparison of the Bill Bootstrapped Means\")plt.xlabel(\"Bill Amount ($)\")plt.ylabel(\"Count\")" }, { "code": null, "e": 6933, "s": 6848, "text": "A great thing, is that we can now use a t-test to compare the two mean distributions" }, { "code": null, "e": 6997, "s": 6933, "text": "t2, p2 = stats.ttest_ind(average_estimate_a,average_estimate_b)" }, { "code": null, "e": 7245, "s": 6997, "text": "For the above we get a p~0 i.e. there is a nearly zero percent probability that the means of the two samples are the same. If these were representative of two experimental conditions, we could safely assume that there is a difference between them." }, { "code": null, "e": 7523, "s": 7245, "text": "This is a VERY powerful technique- it can be used to estimate the standard error of any statistical parameter no matter what the underlying data distribution. Also, the resulting estimate is normally distributed, making it easy to compare using standard frequentist techniques." } ]
How to deploy a MongoDB Replica Set using Docker | by Cristian Ramirez | Towards Data Science
I have written a new article about how to deploy a mongodb cluster using a DevOps fashion Style, in this article i am using Terraform, Ansible, Packer and more cool technologies, i highly encourage you to read it. medium.com This article is going to be a walk-through in how to set up a MongoDB replica set with authentication using docker. What we are going to use for this article is: MongoDB 3.4.1 Docker for Mac 1.12.6 In the image above we are seeing what is going to be the result of our replication set with docker. basic knowledge in docker docker and docker-machine installed basic knowledge in mongoDB basic knowledge in bash scripting If you are on Mac or Windows, consider using a Virtual Machine. I will use VirtualBox on MacOS Sierra to run our mongoDB instances. To create a docker machine we need to issue the next command in a terminal: $ docker-machine create -d virtualbox manager1 This command will create a machine called manager1 using virtualbox as our virtualization provider. Now let’s create the two lefting docker-machine $ docker-machine create -d virtualbox worker1$ docker-machine create -d virtualbox worker2 To verify if our machines are created, let’s run the following command: $ docker-machine ls// the result will beNAME ACTIVE DRIVER STATE URL manager1 - virtualbox Running tcp://192.168.99.100:2376 worker1 - virtualbox Running tcp://192.168.99.101:2376worker2 - virtualbox Running tcp://192.168.99.102:2376 Now that we have our three machines lets position it in our first machine to start the mongodb configuration, let’s run the next command: $ eval `docker-machine env manager1` Before creating our mongoDB containers, there is a very important topic that has been long discussed around database persistence in docker containers, and to achieve this challenge what we are going to do is to create a docker volume. $ docker volume create --name mongo_storage Now let’s attached our volume created to start our first mongo container and set the configurations. $ docker run --name mongoNode1 \-v mongo_storage:/data \-d mongo \--smallfiles Next we need to create the key file. The contents of the keyfile serves as the shared password for the members of the replica set. The content of the keyfile must be the same for all members of the replica set. $ openssl rand -base64 741 > mongo-keyfile$ chmod 600 mongo-keyfile Next let’s create the folders where is going to hold the data, keyfile and configurations inside the mongo_storage volume: $ docker exec mongoNode1 bash -c 'mkdir /data/keyfile /data/admin' The next step is to create some admin users, let’s create a admin.js and a replica.js file that looks like this: // admin.jsadmin = db.getSiblingDB("admin")// creation of the admin useradmin.createUser( { user: "cristian", pwd: "cristianPassword2017", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })// let's authenticate to create the other userdb.getSiblingDB("admin").auth("cristian", "cristianPassword2017" )// creation of the replica set admin userdb.getSiblingDB("admin").createUser( { "user" : "replicaAdmin", "pwd" : "replicaAdminPassword2017", roles: [ { "role" : "clusterAdmin", "db" : "admin" } ] }) //replica.jsrs.initiate({ _id: 'rs1', members: [{ _id: 0, host: 'manager1:27017' }]}) Passwords should be random, long, and complex to ensure system security and to prevent or delay malicious access. See Database User Roles for a full list of built-in roles and related to database administration operations. What we have done until know: created the mongo_storage, docker volume. created the mongo-keyfile, openssl key generation. created the admin.js file, admin users for mongoDB. created the replica.js file, to init the replica set. Ok let’s continue with passing the files to the container. $ docker cp admin.js mongoNode1:/data/admin/$ docker cp replica.js mongoNode1:/data/admin/$ docker cp mongo-keyfile mongoNode1:/data/keyfile/ // change folder owner to the user container$ docker exec mongoNode1 bash -c 'chown -R mongodb:mongodb /data' What we have done is that we pass the files needed to the container, and then change the /data folder owner to the container user, since the the container user is the user that will need access to this folder and files. Now everything has been set, and we are ready to restart the mongod instance with the replica set configurations. Before we start the authenticated mongo container let’s create an env file to set our users and passwords. MONGO_USER_ADMIN=cristianMONGO_PASS_ADMIN=cristianPassword2017MONGO_REPLICA_ADMIN=replicaAdminMONGO_PASS_REPLICA=replicaAdminPassword2017 Now we need to remove the container and start a new one. Why ?, because we need to provide the replica set and authentication parameters, and to do that we need to run the following command: // first let's remove our container$ docker rm -f mongoNode1// now lets start our container with authentication $ docker run --name mongoNode1 --hostname mongoNode1 \-v mongo_storage:/data \--env-file env \--add-host manager1:192.168.99.100 \--add-host worker1:192.168.99.101 \--add-host worker2:192.168.99.102 \-p 27017:27017 \-d mongo --smallfiles \--keyFile /data/keyfile/mongo-keyfile \--replSet 'rs1' \--storageEngine wiredTiger \--port 27017 What is going on here... 🤔 it seems that is an abuse of flags. let me explaint to you in two parts: Docker Flags: The --env-file reads an env file and sets environment variables inside the container.The --add-host flag adds entries into the docker container’s /etc/hosts file so we can use hostnames instead of IP addresses. Here we are mapping our 3 docker-machines that we have created before. The --env-file reads an env file and sets environment variables inside the container. The --add-host flag adds entries into the docker container’s /etc/hosts file so we can use hostnames instead of IP addresses. Here we are mapping our 3 docker-machines that we have created before. For more deep understanding in docker run commands, read Docker’s documentation. Mongo Flags: For setting up the mongo replica set we need a variety of mongo flags --keyFile this flag is for telling mongo where is the mongo-keyfile.--replSet this flag is for setting the name of the replica set.--storageEngine this flag is for setting the engine of the mongoDB, is not requiered, since mongoDB 3.4.1 its default engine is wiredTiger. --keyFile this flag is for telling mongo where is the mongo-keyfile. --replSet this flag is for setting the name of the replica set. --storageEngine this flag is for setting the engine of the mongoDB, is not requiered, since mongoDB 3.4.1 its default engine is wiredTiger. For more deep understanding in mongo replica set, read MongoDB documentation, also i recommend the MongoUniversity Courses for learning more about this topic. Final step for the mongoNode1 container, is to start the replica set, and we are going to do that by running the following command: $ docker exec mongoNode1 bash -c 'mongo < /data/admin/replica.js' You should see something like this: MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ "ok" : 1 }bye And now let’s create the admin users with the following command: $ docker exec mongoNode1 bash -c 'mongo < /data/admin/admin.js' You should see something like this: MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1adminSuccessfully added user: { "user" : "cristian", ...Successfully added user: { "user" : "replicaAdmin",...bye And now to get in to the replica run the following command: $ docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_REPLICA_ADMIN -p $MONGO_PASS_REPLICA --eval "rs.status()" --authenticationDatabase "admin"' And you should be ready and see something like this: MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ "set" : "rs1", ... "members" : [ { "_id" : 0, "name" : "manager1:27017", ... "ok" : 1} Now that everything is ready, let’s start 2 more nodes and join them to the replica set. To add the first node let’s change to the worker1 docker machine, if you are using a local computer run the following command: eval `docker-machine env worker1` If you’re not running on local, just point your terminal to the next server. Now since we are going to repeat almost all the steps we made for mongoNode1 let’s make a script that runs all of our commands for us. Let’s create a file called create-replica-set.sh and let’s see how is going to be composed the main function: function main { init_mongo_primary init_mongo_secondaries add_replicas manager1 mongoNode1 check_status manager1 mongoNode1}main Now let me show you how are composed this functions: INIT MONGO PRIMARY FUNCTION function init_mongo_primary { # @params name-of-keyfile createKeyFile mongo-keyfile # @params server container volume createMongoDBNode manager1 mongoNode1 mongo_storage # @params container init_replica_set mongoNode1} This function has calls to functions inside also, there is nothing new added, we already saw all the functionality before, let me describe it for you what it does: creation of the keyfile for the replica set authentication.creation of a mongodb container, and recieves 2 parameters: a) the server where is going to be located, b) the name of the container, c) the name of the docker volume, all this functionality we saw it before.and finally, it will initiate the replica with the exact same steps, we do before. creation of the keyfile for the replica set authentication. creation of a mongodb container, and recieves 2 parameters: a) the server where is going to be located, b) the name of the container, c) the name of the docker volume, all this functionality we saw it before. and finally, it will initiate the replica with the exact same steps, we do before. INIT MONGO SECONDARY FUNCTION function init_mongo_secondaries { # @Params server container volume createMongoDBNode worker1 mongoNode1 mongo_storage createMongoDBNode worker2 mongoNode2 mongo_storage} This function what it does is to creates the other 2 mongo containers for the replica set, and executes the same steps as the mongoNode1, but here we don’t include the replica set instantiation, and the admin users creation, because those aren’t necessary, since the replica set, will share with all the nodes of the replica the database configurations, and later on they will be added to the primary database. # @params server containerfunction add_replicas { echo '·· adding replicas >>>> '$1' ··' switchToServer $1 for server in worker1 worker2 do rs="rs.add('$server:27017')" add='mongo --eval "'$rs'" -u $MONGO_REPLICA_ADMIN -p $MONGO_PASS_REPLICA --authenticationDatabase="admin"' sleep 2 wait_for_databases $server docker exec -i $2 bash -c "$add" done} Here what are we doing, is finally adding the 2 other mongo containers to the primary database on the replica set configuration, first we loop through the machines left to add the containers, in the loop we prepare the configuration, then we check if the container is ready, we do that by calling the function wait_for_databases and we pass the machine to check as the parameter, then we execute the configuration inside the primary database and we should se messages like this: MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ "ok" : 1 } That means that the mongo container was added successfully to the replica. And finally we check the status of the replica set with the last function in the main: # @params server containerfunction check_status { switchToServer $1 cmd='mongo -u $MONGO_REPLICA_ADMIN -p $MONGO_PASS_REPLICA --eval "rs.status()" --authenticationDatabase "admin"' docker exec -i $2 bash -c "$cmd"} Now that we have seen the functions of our automated script and that we know is going to do, it’s time to execute the automated bash script like the following: note if you have made all the steps above, you need to reset everything that we have implemented, to avoid any collision name problems, to reset the configurations there is a reset.sh file on the github repository # and this how we can execute the script that will configure # everything for us.$ bash < create-replica-set.sh And if everything was set correctly, we should see a message from mongodb like this: MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ "set" : "rs1", ... }, "members" : [ { "_id" : 0, "name" : "manager1:27017", "health" : 1, "state" : 1, "stateStr" : "PRIMARY", ... }, { "_id" : 1, "name" : "worker1:27017", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", ... }, { "_id" : 2, "name" : "worker2:27017", "health" : 1, "state" : 0, "stateStr" : "STARTUP", ... } ], "ok" : 1} As you can see every container is now well configured, some things to notice is that we we use the --add-host flag from docker as we used before and this adds these entries into the Docker container’s /etc/hosts file so we can use hostnames instead of IP addresses. It might take a minute for both node to complete syncing from mongoNode1. You can view what is happening in each mongo Docker container by looking at the logs. You can do this by running this command on any of the docker-machine servers. $ docker logs -ft mongoContainerName Now that we have a MongoDB replica set service up and running, let’s modify our user or you can create another user and grant some permissions to make crud operations over a database, so for illustration purposes only, this a bad practice, let me add a super role to our admin user. # we are going to assign the root role to our admin user# we enter to the container$ docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase "admin"'# Then we execute the following in the mongo shell# Mongo 3.4.1 shell> use admin> db.grantRolesToUser( "cristian", [ "root" , { role: "root", db: "admin" } ] )> Now he have a super user that can make anything, so let’s create a database and insert some data. $ docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase "admin"'# Mongo 3.4.1 shell> use movies> db.movies.insertMany([{ id: '1', title: 'Assasins Creed', runtime: 115, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 6}, { id: '2', title: 'Aliados', runtime: 124, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 13}, { id: '3', title: 'xXx: Reactivado', runtime: 107, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 20}, { id: '4', title: 'Resident Evil: Capitulo Final', runtime: 107, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 27}, { id: '5', title: 'Moana: Un Mar de Aventuras', runtime: 114, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2016, releaseMonth: 12, releaseDay: 2}])# inserted 5 documents> Now we have a movies database with a movies collection that contains 5 movies :D. What we have done... We configure and start a MongoDB Replica Set with Authentication using Docker, with an automated script. In security terms, we create: 2 type of users, the admin database and the cluster admin database. we create a key file, and start the replica with authentication enabled. If access control is configured correctly for the database, attackers should not have been able to gain access to your data. Review our Security Checklist to help catch potential weaknesses. — @MongoDB Docs If we want to add more security to our architecture, we can create a Swarm Cluster, with our docker-machines, and docker swarm handles well the network communication, also we can create non-root users in our containers, and we can enable encryption data in mongoDB, but this topics are outside of scope of the pretentions of this article. Now we have a working MongoDB replica set. You are free to add nodes to this replica set at any time. You can even stop one of the mongo container or the primary mongoNode1 and watch another mongoNode take over as the new primary. Since the data is written on docker volumes, restarting any of these nodes is not a problem. The data will persist and rejoin the replica set perfectly fine. One bonus for us is that we saw how to automate this whole process with a bash file. One challenge for you is to modify the bash script and make it more dynamically since this script is very attached to this article specifiactions, and another challenge is to add an Arbitrary Mongo Node, to the architecture. To get the complete script files of the article you can check it at the following repo. github.com Deploy Replica Set With Keyfile Access Control — MongoDB Docs. Add Members to a Replica Set — MongoDB Docs. MongoDB Docker Hub — Docker Docs. How to Avoid a Malicious Attack That Ransoms Your Data How to setup a secure mongoDB 3.4 server on ubuntu 16.04 I hope you enjoyed this article, i’m currently still exploring the MongoDB world, so i am open to accept feedback or contributions, and if you liked it, recommend it to a friend, share it or read it again. You can follow me at twitter @cramirez_92https://twitter.com/cramirez_92 Until next time 😁👨🏼‍🎨👨🏻‍💻
[ { "code": null, "e": 386, "s": 172, "text": "I have written a new article about how to deploy a mongodb cluster using a DevOps fashion Style, in this article i am using Terraform, Ansible, Packer and more cool technologies, i highly encourage you to read it." }, { "code": null, "e": 397, "s": 386, "text": "medium.com" }, { "code": null, "e": 513, "s": 397, "text": "This article is going to be a walk-through in how to set up a MongoDB replica set with authentication using docker." }, { "code": null, "e": 559, "s": 513, "text": "What we are going to use for this article is:" }, { "code": null, "e": 573, "s": 559, "text": "MongoDB 3.4.1" }, { "code": null, "e": 595, "s": 573, "text": "Docker for Mac 1.12.6" }, { "code": null, "e": 695, "s": 595, "text": "In the image above we are seeing what is going to be the result of our replication set with docker." }, { "code": null, "e": 721, "s": 695, "text": "basic knowledge in docker" }, { "code": null, "e": 757, "s": 721, "text": "docker and docker-machine installed" }, { "code": null, "e": 784, "s": 757, "text": "basic knowledge in mongoDB" }, { "code": null, "e": 818, "s": 784, "text": "basic knowledge in bash scripting" }, { "code": null, "e": 950, "s": 818, "text": "If you are on Mac or Windows, consider using a Virtual Machine. I will use VirtualBox on MacOS Sierra to run our mongoDB instances." }, { "code": null, "e": 1026, "s": 950, "text": "To create a docker machine we need to issue the next command in a terminal:" }, { "code": null, "e": 1073, "s": 1026, "text": "$ docker-machine create -d virtualbox manager1" }, { "code": null, "e": 1173, "s": 1073, "text": "This command will create a machine called manager1 using virtualbox as our virtualization provider." }, { "code": null, "e": 1221, "s": 1173, "text": "Now let’s create the two lefting docker-machine" }, { "code": null, "e": 1312, "s": 1221, "text": "$ docker-machine create -d virtualbox worker1$ docker-machine create -d virtualbox worker2" }, { "code": null, "e": 1384, "s": 1312, "text": "To verify if our machines are created, let’s run the following command:" }, { "code": null, "e": 1667, "s": 1384, "text": "$ docker-machine ls// the result will beNAME ACTIVE DRIVER STATE URL manager1 - virtualbox Running tcp://192.168.99.100:2376 worker1 - virtualbox Running tcp://192.168.99.101:2376worker2 - virtualbox Running tcp://192.168.99.102:2376" }, { "code": null, "e": 1805, "s": 1667, "text": "Now that we have our three machines lets position it in our first machine to start the mongodb configuration, let’s run the next command:" }, { "code": null, "e": 1842, "s": 1805, "text": "$ eval `docker-machine env manager1`" }, { "code": null, "e": 2077, "s": 1842, "text": "Before creating our mongoDB containers, there is a very important topic that has been long discussed around database persistence in docker containers, and to achieve this challenge what we are going to do is to create a docker volume." }, { "code": null, "e": 2121, "s": 2077, "text": "$ docker volume create --name mongo_storage" }, { "code": null, "e": 2222, "s": 2121, "text": "Now let’s attached our volume created to start our first mongo container and set the configurations." }, { "code": null, "e": 2301, "s": 2222, "text": "$ docker run --name mongoNode1 \\-v mongo_storage:/data \\-d mongo \\--smallfiles" }, { "code": null, "e": 2338, "s": 2301, "text": "Next we need to create the key file." }, { "code": null, "e": 2512, "s": 2338, "text": "The contents of the keyfile serves as the shared password for the members of the replica set. The content of the keyfile must be the same for all members of the replica set." }, { "code": null, "e": 2580, "s": 2512, "text": "$ openssl rand -base64 741 > mongo-keyfile$ chmod 600 mongo-keyfile" }, { "code": null, "e": 2703, "s": 2580, "text": "Next let’s create the folders where is going to hold the data, keyfile and configurations inside the mongo_storage volume:" }, { "code": null, "e": 2770, "s": 2703, "text": "$ docker exec mongoNode1 bash -c 'mkdir /data/keyfile /data/admin'" }, { "code": null, "e": 2883, "s": 2770, "text": "The next step is to create some admin users, let’s create a admin.js and a replica.js file that looks like this:" }, { "code": null, "e": 3414, "s": 2883, "text": "// admin.jsadmin = db.getSiblingDB(\"admin\")// creation of the admin useradmin.createUser( { user: \"cristian\", pwd: \"cristianPassword2017\", roles: [ { role: \"userAdminAnyDatabase\", db: \"admin\" } ] })// let's authenticate to create the other userdb.getSiblingDB(\"admin\").auth(\"cristian\", \"cristianPassword2017\" )// creation of the replica set admin userdb.getSiblingDB(\"admin\").createUser( { \"user\" : \"replicaAdmin\", \"pwd\" : \"replicaAdminPassword2017\", roles: [ { \"role\" : \"clusterAdmin\", \"db\" : \"admin\" } ] })" }, { "code": null, "e": 3501, "s": 3414, "text": "//replica.jsrs.initiate({ _id: 'rs1', members: [{ _id: 0, host: 'manager1:27017' }]})" }, { "code": null, "e": 3724, "s": 3501, "text": "Passwords should be random, long, and complex to ensure system security and to prevent or delay malicious access. See Database User Roles for a full list of built-in roles and related to database administration operations." }, { "code": null, "e": 3754, "s": 3724, "text": "What we have done until know:" }, { "code": null, "e": 3796, "s": 3754, "text": "created the mongo_storage, docker volume." }, { "code": null, "e": 3847, "s": 3796, "text": "created the mongo-keyfile, openssl key generation." }, { "code": null, "e": 3899, "s": 3847, "text": "created the admin.js file, admin users for mongoDB." }, { "code": null, "e": 3953, "s": 3899, "text": "created the replica.js file, to init the replica set." }, { "code": null, "e": 4012, "s": 3953, "text": "Ok let’s continue with passing the files to the container." }, { "code": null, "e": 4154, "s": 4012, "text": "$ docker cp admin.js mongoNode1:/data/admin/$ docker cp replica.js mongoNode1:/data/admin/$ docker cp mongo-keyfile mongoNode1:/data/keyfile/" }, { "code": null, "e": 4264, "s": 4154, "text": "// change folder owner to the user container$ docker exec mongoNode1 bash -c 'chown -R mongodb:mongodb /data'" }, { "code": null, "e": 4484, "s": 4264, "text": "What we have done is that we pass the files needed to the container, and then change the /data folder owner to the container user, since the the container user is the user that will need access to this folder and files." }, { "code": null, "e": 4598, "s": 4484, "text": "Now everything has been set, and we are ready to restart the mongod instance with the replica set configurations." }, { "code": null, "e": 4705, "s": 4598, "text": "Before we start the authenticated mongo container let’s create an env file to set our users and passwords." }, { "code": null, "e": 4843, "s": 4705, "text": "MONGO_USER_ADMIN=cristianMONGO_PASS_ADMIN=cristianPassword2017MONGO_REPLICA_ADMIN=replicaAdminMONGO_PASS_REPLICA=replicaAdminPassword2017" }, { "code": null, "e": 5034, "s": 4843, "text": "Now we need to remove the container and start a new one. Why ?, because we need to provide the replica set and authentication parameters, and to do that we need to run the following command:" }, { "code": null, "e": 5482, "s": 5034, "text": "// first let's remove our container$ docker rm -f mongoNode1// now lets start our container with authentication $ docker run --name mongoNode1 --hostname mongoNode1 \\-v mongo_storage:/data \\--env-file env \\--add-host manager1:192.168.99.100 \\--add-host worker1:192.168.99.101 \\--add-host worker2:192.168.99.102 \\-p 27017:27017 \\-d mongo --smallfiles \\--keyFile /data/keyfile/mongo-keyfile \\--replSet 'rs1' \\--storageEngine wiredTiger \\--port 27017" }, { "code": null, "e": 5545, "s": 5482, "text": "What is going on here... 🤔 it seems that is an abuse of flags." }, { "code": null, "e": 5582, "s": 5545, "text": "let me explaint to you in two parts:" }, { "code": null, "e": 5596, "s": 5582, "text": "Docker Flags:" }, { "code": null, "e": 5878, "s": 5596, "text": "The --env-file reads an env file and sets environment variables inside the container.The --add-host flag adds entries into the docker container’s /etc/hosts file so we can use hostnames instead of IP addresses. Here we are mapping our 3 docker-machines that we have created before." }, { "code": null, "e": 5964, "s": 5878, "text": "The --env-file reads an env file and sets environment variables inside the container." }, { "code": null, "e": 6161, "s": 5964, "text": "The --add-host flag adds entries into the docker container’s /etc/hosts file so we can use hostnames instead of IP addresses. Here we are mapping our 3 docker-machines that we have created before." }, { "code": null, "e": 6242, "s": 6161, "text": "For more deep understanding in docker run commands, read Docker’s documentation." }, { "code": null, "e": 6255, "s": 6242, "text": "Mongo Flags:" }, { "code": null, "e": 6325, "s": 6255, "text": "For setting up the mongo replica set we need a variety of mongo flags" }, { "code": null, "e": 6596, "s": 6325, "text": "--keyFile this flag is for telling mongo where is the mongo-keyfile.--replSet this flag is for setting the name of the replica set.--storageEngine this flag is for setting the engine of the mongoDB, is not requiered, since mongoDB 3.4.1 its default engine is wiredTiger." }, { "code": null, "e": 6665, "s": 6596, "text": "--keyFile this flag is for telling mongo where is the mongo-keyfile." }, { "code": null, "e": 6729, "s": 6665, "text": "--replSet this flag is for setting the name of the replica set." }, { "code": null, "e": 6869, "s": 6729, "text": "--storageEngine this flag is for setting the engine of the mongoDB, is not requiered, since mongoDB 3.4.1 its default engine is wiredTiger." }, { "code": null, "e": 7028, "s": 6869, "text": "For more deep understanding in mongo replica set, read MongoDB documentation, also i recommend the MongoUniversity Courses for learning more about this topic." }, { "code": null, "e": 7160, "s": 7028, "text": "Final step for the mongoNode1 container, is to start the replica set, and we are going to do that by running the following command:" }, { "code": null, "e": 7226, "s": 7160, "text": "$ docker exec mongoNode1 bash -c 'mongo < /data/admin/replica.js'" }, { "code": null, "e": 7262, "s": 7226, "text": "You should see something like this:" }, { "code": null, "e": 7375, "s": 7262, "text": "MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ \"ok\" : 1 }bye" }, { "code": null, "e": 7440, "s": 7375, "text": "And now let’s create the admin users with the following command:" }, { "code": null, "e": 7504, "s": 7440, "text": "$ docker exec mongoNode1 bash -c 'mongo < /data/admin/admin.js'" }, { "code": null, "e": 7540, "s": 7504, "text": "You should see something like this:" }, { "code": null, "e": 7751, "s": 7540, "text": "MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1adminSuccessfully added user: { \"user\" : \"cristian\", ...Successfully added user: { \"user\" : \"replicaAdmin\",...bye" }, { "code": null, "e": 7811, "s": 7751, "text": "And now to get in to the replica run the following command:" }, { "code": null, "e": 7957, "s": 7811, "text": "$ docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_REPLICA_ADMIN -p $MONGO_PASS_REPLICA --eval \"rs.status()\" --authenticationDatabase \"admin\"'" }, { "code": null, "e": 8010, "s": 7957, "text": "And you should be ready and see something like this:" }, { "code": null, "e": 8203, "s": 8010, "text": "MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ \"set\" : \"rs1\", ... \"members\" : [ { \"_id\" : 0, \"name\" : \"manager1:27017\", ... \"ok\" : 1}" }, { "code": null, "e": 8292, "s": 8203, "text": "Now that everything is ready, let’s start 2 more nodes and join them to the replica set." }, { "code": null, "e": 8419, "s": 8292, "text": "To add the first node let’s change to the worker1 docker machine, if you are using a local computer run the following command:" }, { "code": null, "e": 8453, "s": 8419, "text": "eval `docker-machine env worker1`" }, { "code": null, "e": 8530, "s": 8453, "text": "If you’re not running on local, just point your terminal to the next server." }, { "code": null, "e": 8665, "s": 8530, "text": "Now since we are going to repeat almost all the steps we made for mongoNode1 let’s make a script that runs all of our commands for us." }, { "code": null, "e": 8775, "s": 8665, "text": "Let’s create a file called create-replica-set.sh and let’s see how is going to be composed the main function:" }, { "code": null, "e": 8908, "s": 8775, "text": "function main { init_mongo_primary init_mongo_secondaries add_replicas manager1 mongoNode1 check_status manager1 mongoNode1}main" }, { "code": null, "e": 8961, "s": 8908, "text": "Now let me show you how are composed this functions:" }, { "code": null, "e": 8989, "s": 8961, "text": "INIT MONGO PRIMARY FUNCTION" }, { "code": null, "e": 9218, "s": 8989, "text": "function init_mongo_primary { # @params name-of-keyfile createKeyFile mongo-keyfile # @params server container volume createMongoDBNode manager1 mongoNode1 mongo_storage # @params container init_replica_set mongoNode1}" }, { "code": null, "e": 9382, "s": 9218, "text": "This function has calls to functions inside also, there is nothing new added, we already saw all the functionality before, let me describe it for you what it does:" }, { "code": null, "e": 9732, "s": 9382, "text": "creation of the keyfile for the replica set authentication.creation of a mongodb container, and recieves 2 parameters: a) the server where is going to be located, b) the name of the container, c) the name of the docker volume, all this functionality we saw it before.and finally, it will initiate the replica with the exact same steps, we do before." }, { "code": null, "e": 9792, "s": 9732, "text": "creation of the keyfile for the replica set authentication." }, { "code": null, "e": 10001, "s": 9792, "text": "creation of a mongodb container, and recieves 2 parameters: a) the server where is going to be located, b) the name of the container, c) the name of the docker volume, all this functionality we saw it before." }, { "code": null, "e": 10084, "s": 10001, "text": "and finally, it will initiate the replica with the exact same steps, we do before." }, { "code": null, "e": 10114, "s": 10084, "text": "INIT MONGO SECONDARY FUNCTION" }, { "code": null, "e": 10288, "s": 10114, "text": "function init_mongo_secondaries { # @Params server container volume createMongoDBNode worker1 mongoNode1 mongo_storage createMongoDBNode worker2 mongoNode2 mongo_storage}" }, { "code": null, "e": 10699, "s": 10288, "text": "This function what it does is to creates the other 2 mongo containers for the replica set, and executes the same steps as the mongoNode1, but here we don’t include the replica set instantiation, and the admin users creation, because those aren’t necessary, since the replica set, will share with all the nodes of the replica the database configurations, and later on they will be added to the primary database." }, { "code": null, "e": 11081, "s": 10699, "text": "# @params server containerfunction add_replicas { echo '·· adding replicas >>>> '$1' ··' switchToServer $1 for server in worker1 worker2 do rs=\"rs.add('$server:27017')\" add='mongo --eval \"'$rs'\" -u $MONGO_REPLICA_ADMIN -p $MONGO_PASS_REPLICA --authenticationDatabase=\"admin\"' sleep 2 wait_for_databases $server docker exec -i $2 bash -c \"$add\" done}" }, { "code": null, "e": 11560, "s": 11081, "text": "Here what are we doing, is finally adding the 2 other mongo containers to the primary database on the replica set configuration, first we loop through the machines left to add the containers, in the loop we prepare the configuration, then we check if the container is ready, we do that by calling the function wait_for_databases and we pass the machine to check as the parameter, then we execute the configuration inside the primary database and we should se messages like this:" }, { "code": null, "e": 11670, "s": 11560, "text": "MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ \"ok\" : 1 }" }, { "code": null, "e": 11745, "s": 11670, "text": "That means that the mongo container was added successfully to the replica." }, { "code": null, "e": 11832, "s": 11745, "text": "And finally we check the status of the replica set with the last function in the main:" }, { "code": null, "e": 12058, "s": 11832, "text": "# @params server containerfunction check_status { switchToServer $1 cmd='mongo -u $MONGO_REPLICA_ADMIN -p $MONGO_PASS_REPLICA --eval \"rs.status()\" --authenticationDatabase \"admin\"' docker exec -i $2 bash -c \"$cmd\"}" }, { "code": null, "e": 12218, "s": 12058, "text": "Now that we have seen the functions of our automated script and that we know is going to do, it’s time to execute the automated bash script like the following:" }, { "code": null, "e": 12432, "s": 12218, "text": "note if you have made all the steps above, you need to reset everything that we have implemented, to avoid any collision name problems, to reset the configurations there is a reset.sh file on the github repository" }, { "code": null, "e": 12544, "s": 12432, "text": "# and this how we can execute the script that will configure # everything for us.$ bash < create-replica-set.sh" }, { "code": null, "e": 12629, "s": 12544, "text": "And if everything was set correctly, we should see a message from mongodb like this:" }, { "code": null, "e": 13112, "s": 12629, "text": "MongoDB shell version v3.4.1connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.1{ \"set\" : \"rs1\", ... }, \"members\" : [ { \"_id\" : 0, \"name\" : \"manager1:27017\", \"health\" : 1, \"state\" : 1, \"stateStr\" : \"PRIMARY\", ... }, { \"_id\" : 1, \"name\" : \"worker1:27017\", \"health\" : 1, \"state\" : 2, \"stateStr\" : \"SECONDARY\", ... }, { \"_id\" : 2, \"name\" : \"worker2:27017\", \"health\" : 1, \"state\" : 0, \"stateStr\" : \"STARTUP\", ... } ], \"ok\" : 1}" }, { "code": null, "e": 13378, "s": 13112, "text": "As you can see every container is now well configured, some things to notice is that we we use the --add-host flag from docker as we used before and this adds these entries into the Docker container’s /etc/hosts file so we can use hostnames instead of IP addresses." }, { "code": null, "e": 13452, "s": 13378, "text": "It might take a minute for both node to complete syncing from mongoNode1." }, { "code": null, "e": 13616, "s": 13452, "text": "You can view what is happening in each mongo Docker container by looking at the logs. You can do this by running this command on any of the docker-machine servers." }, { "code": null, "e": 13653, "s": 13616, "text": "$ docker logs -ft mongoContainerName" }, { "code": null, "e": 13936, "s": 13653, "text": "Now that we have a MongoDB replica set service up and running, let’s modify our user or you can create another user and grant some permissions to make crud operations over a database, so for illustration purposes only, this a bad practice, let me add a super role to our admin user." }, { "code": null, "e": 14299, "s": 13936, "text": "# we are going to assign the root role to our admin user# we enter to the container$ docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase \"admin\"'# Then we execute the following in the mongo shell# Mongo 3.4.1 shell> use admin> db.grantRolesToUser( \"cristian\", [ \"root\" , { role: \"root\", db: \"admin\" } ] )>" }, { "code": null, "e": 14397, "s": 14299, "text": "Now he have a super user that can make anything, so let’s create a database and insert some data." }, { "code": null, "e": 15431, "s": 14397, "text": "$ docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase \"admin\"'# Mongo 3.4.1 shell> use movies> db.movies.insertMany([{ id: '1', title: 'Assasins Creed', runtime: 115, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 6}, { id: '2', title: 'Aliados', runtime: 124, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 13}, { id: '3', title: 'xXx: Reactivado', runtime: 107, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 20}, { id: '4', title: 'Resident Evil: Capitulo Final', runtime: 107, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2017, releaseMonth: 1, releaseDay: 27}, { id: '5', title: 'Moana: Un Mar de Aventuras', runtime: 114, format: 'IMAX', plot: 'Lorem ipsum dolor sit amet', releaseYear: 2016, releaseMonth: 12, releaseDay: 2}])# inserted 5 documents> " }, { "code": null, "e": 15513, "s": 15431, "text": "Now we have a movies database with a movies collection that contains 5 movies :D." }, { "code": null, "e": 15534, "s": 15513, "text": "What we have done..." }, { "code": null, "e": 15639, "s": 15534, "text": "We configure and start a MongoDB Replica Set with Authentication using Docker, with an automated script." }, { "code": null, "e": 15669, "s": 15639, "text": "In security terms, we create:" }, { "code": null, "e": 15737, "s": 15669, "text": "2 type of users, the admin database and the cluster admin database." }, { "code": null, "e": 15810, "s": 15737, "text": "we create a key file, and start the replica with authentication enabled." }, { "code": null, "e": 16017, "s": 15810, "text": "If access control is configured correctly for the database, attackers should not have been able to gain access to your data. Review our Security Checklist to help catch potential weaknesses. — @MongoDB Docs" }, { "code": null, "e": 16356, "s": 16017, "text": "If we want to add more security to our architecture, we can create a Swarm Cluster, with our docker-machines, and docker swarm handles well the network communication, also we can create non-root users in our containers, and we can enable encryption data in mongoDB, but this topics are outside of scope of the pretentions of this article." }, { "code": null, "e": 16745, "s": 16356, "text": "Now we have a working MongoDB replica set. You are free to add nodes to this replica set at any time. You can even stop one of the mongo container or the primary mongoNode1 and watch another mongoNode take over as the new primary. Since the data is written on docker volumes, restarting any of these nodes is not a problem. The data will persist and rejoin the replica set perfectly fine." }, { "code": null, "e": 16830, "s": 16745, "text": "One bonus for us is that we saw how to automate this whole process with a bash file." }, { "code": null, "e": 17055, "s": 16830, "text": "One challenge for you is to modify the bash script and make it more dynamically since this script is very attached to this article specifiactions, and another challenge is to add an Arbitrary Mongo Node, to the architecture." }, { "code": null, "e": 17143, "s": 17055, "text": "To get the complete script files of the article you can check it at the following repo." }, { "code": null, "e": 17154, "s": 17143, "text": "github.com" }, { "code": null, "e": 17217, "s": 17154, "text": "Deploy Replica Set With Keyfile Access Control — MongoDB Docs." }, { "code": null, "e": 17262, "s": 17217, "text": "Add Members to a Replica Set — MongoDB Docs." }, { "code": null, "e": 17296, "s": 17262, "text": "MongoDB Docker Hub — Docker Docs." }, { "code": null, "e": 17351, "s": 17296, "text": "How to Avoid a Malicious Attack That Ransoms Your Data" }, { "code": null, "e": 17408, "s": 17351, "text": "How to setup a secure mongoDB 3.4 server on ubuntu 16.04" }, { "code": null, "e": 17614, "s": 17408, "text": "I hope you enjoyed this article, i’m currently still exploring the MongoDB world, so i am open to accept feedback or contributions, and if you liked it, recommend it to a friend, share it or read it again." }, { "code": null, "e": 17687, "s": 17614, "text": "You can follow me at twitter @cramirez_92https://twitter.com/cramirez_92" } ]
CSS | clear Property - GeeksforGeeks
08 Aug, 2019 The clear property is used to specify that which side of floating elements are not allowed to float. It sets or returns the position of the element in relation to floating objects. If the element can fit horizontally in the space next to another element which is floated, it will. Syntax: clear: none|left|right|both|initial; Property values: none: It has a default value. It allows element are float on both the sides.Syntax:clear:none;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: none; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:none;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: Syntax: clear:none; Example: <!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: none; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:none;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: left: This property specifies that elements are not allowed to Float on the left side in relation to other element.Syntax:clear:left;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: left; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:left;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: Syntax: clear:left; Example: <!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: left; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:left;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: right: It means elements are not allowed to float on the right side.Syntax:clear:right;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: right; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:right;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: Syntax: clear:right; Example: <!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: right; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:right;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: both: It means floating elements are not allowed to float on the both sides.Syntax:clear:both;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: both; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:both;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: Syntax: clear:both; Example: <!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: both; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:both;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: initial: It sets the property to its default value.Syntax:clear:initial;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: initial; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:initial;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output:Supported Browsers: The browsers supported by clear property are listed below:Google Chrome 1.0Internet Explorer 5.0Firefox 1.0Opera 6.0Safari 1.0Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes arrow_drop_upSave clear:initial; Example: <!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: initial; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:initial;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class="GFG">GeeksforGeeks</P> </body></html> Output: Supported Browsers: The browsers supported by clear property are listed below: Google Chrome 1.0 Internet Explorer 5.0 Firefox 1.0 Opera 6.0 Safari 1.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 23684, "s": 23656, "text": "\n08 Aug, 2019" }, { "code": null, "e": 23965, "s": 23684, "text": "The clear property is used to specify that which side of floating elements are not allowed to float. It sets or returns the position of the element in relation to floating objects. If the element can fit horizontally in the space next to another element which is floated, it will." }, { "code": null, "e": 23973, "s": 23965, "text": "Syntax:" }, { "code": null, "e": 24010, "s": 23973, "text": "clear: none|left|right|both|initial;" }, { "code": null, "e": 24027, "s": 24010, "text": "Property values:" }, { "code": null, "e": 25000, "s": 24027, "text": "none: It has a default value. It allows element are float on both the sides.Syntax:clear:none;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: none; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:none;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> Output:" }, { "code": null, "e": 25008, "s": 25000, "text": "Syntax:" }, { "code": null, "e": 25020, "s": 25008, "text": "clear:none;" }, { "code": null, "e": 25029, "s": 25020, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: none; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:none;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> ", "e": 25893, "s": 25029, "text": null }, { "code": null, "e": 25901, "s": 25893, "text": "Output:" }, { "code": null, "e": 26901, "s": 25901, "text": "left: This property specifies that elements are not allowed to Float on the left side in relation to other element.Syntax:clear:left;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: left; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:left;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> Output:" }, { "code": null, "e": 26909, "s": 26901, "text": "Syntax:" }, { "code": null, "e": 26921, "s": 26909, "text": "clear:left;" }, { "code": null, "e": 26930, "s": 26921, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: left; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:left;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> ", "e": 27782, "s": 26930, "text": null }, { "code": null, "e": 27790, "s": 27782, "text": "Output:" }, { "code": null, "e": 28738, "s": 27790, "text": "right: It means elements are not allowed to float on the right side.Syntax:clear:right;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: right; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:right;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> Output:" }, { "code": null, "e": 28746, "s": 28738, "text": "Syntax:" }, { "code": null, "e": 28759, "s": 28746, "text": "clear:right;" }, { "code": null, "e": 28768, "s": 28759, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: right; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:right;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> ", "e": 29614, "s": 28768, "text": null }, { "code": null, "e": 29622, "s": 29614, "text": "Output:" }, { "code": null, "e": 30575, "s": 29622, "text": "both: It means floating elements are not allowed to float on the both sides.Syntax:clear:both;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: both; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:both;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> Output:" }, { "code": null, "e": 30583, "s": 30575, "text": "Syntax:" }, { "code": null, "e": 30595, "s": 30583, "text": "clear:both;" }, { "code": null, "e": 30604, "s": 30595, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: both; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:both;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> ", "e": 31448, "s": 30604, "text": null }, { "code": null, "e": 31456, "s": 31448, "text": "Output:" }, { "code": null, "e": 32710, "s": 31456, "text": "initial: It sets the property to its default value.Syntax:clear:initial;Example:<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: initial; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:initial;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> Output:Supported Browsers: The browsers supported by clear property are listed below:Google Chrome 1.0Internet Explorer 5.0Firefox 1.0Opera 6.0Safari 1.0Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32725, "s": 32710, "text": "clear:initial;" }, { "code": null, "e": 32734, "s": 32725, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { width:100px; height:100px; background-color:green; color:white; font-weight:bold; font-style;itallic; font-size:25px; text-align:center; float: left; padding:15px; } p.GFG { clear: initial; } h1, h2 { color:green; text-align:center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h1>clear:initial;</h1> <div><pre>GFG</pre></div> <p> GeeksforGeeks: A computer science portal for geeks </p> <p class=\"GFG\">GeeksforGeeks</P> </body></html> ", "e": 33584, "s": 32734, "text": null }, { "code": null, "e": 33592, "s": 33584, "text": "Output:" }, { "code": null, "e": 33671, "s": 33592, "text": "Supported Browsers: The browsers supported by clear property are listed below:" }, { "code": null, "e": 33689, "s": 33671, "text": "Google Chrome 1.0" }, { "code": null, "e": 33711, "s": 33689, "text": "Internet Explorer 5.0" }, { "code": null, "e": 33723, "s": 33711, "text": "Firefox 1.0" }, { "code": null, "e": 33733, "s": 33723, "text": "Opera 6.0" }, { "code": null, "e": 33744, "s": 33733, "text": "Safari 1.0" }, { "code": null, "e": 33881, "s": 33744, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33896, "s": 33881, "text": "CSS-Properties" }, { "code": null, "e": 33920, "s": 33896, "text": "Technical Scripter 2018" }, { "code": null, "e": 33924, "s": 33920, "text": "CSS" }, { "code": null, "e": 33929, "s": 33924, "text": "HTML" }, { "code": null, "e": 33948, "s": 33929, "text": "Technical Scripter" }, { "code": null, "e": 33965, "s": 33948, "text": "Web Technologies" }, { "code": null, "e": 33970, "s": 33965, "text": "HTML" }, { "code": null, "e": 34068, "s": 33970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34130, "s": 34068, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34180, "s": 34130, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34238, "s": 34180, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34286, "s": 34238, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34336, "s": 34286, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 34386, "s": 34336, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34448, "s": 34386, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34508, "s": 34448, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34556, "s": 34508, "text": "How to update Node.js and NPM to next version ?" } ]
Convert string to datetime in Python with timezone - GeeksforGeeks
14 Sep, 2021 Prerequisite: Datetime module In this article, we will learn how to get datetime object from time string using Python. To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. Syntax : datetime.strptime(date_string, format) Parameters : date_string : Specified time string containing of which datetime object is required. **Required format : Abbreviation format of date_string Returns : Returns the datetime object of given date_string List of the acceptable format that can be passed to strptime(): Example 1: Converting datetime string to datetime Python3 # Python3 code to demonstrate# Getting datetime object using a date_string # importing datetime moduleimport datetime # datestring for which datetime_obj requireddate_string = '2021-09-01 15:27:05.004573 +0530'print("string datetime: ")print(date_string)print("datestring class is :", type(date_string)) # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime( date_string, '%Y-%m-%d %H:%M:%S.%f %z') print("converted to datetime:") # Printing datetimeprint(datetime_obj) # Checking class of datetime_obj.print("datetime_obj class is :", type(datetime_obj)) Output: string datetime: 2021-09-01 15:27:05.004573 +0530 datestring class is : <class 'str'> converted to datetime: 2021-09-01 15:27:05.004573+05:30 datetime_obj class is : <class 'datetime.datetime'> Example 2: Converting datetime string to datetime Python3 # Python3 code to demonstrate# Getting datetime object using a date_string # importing datetime moduleimport datetime # datestring for which datetime_obj requireddate_string = '2021-09-01 15:27:05' # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') # Printing datetimeprint(datetime_obj) Output: 2021-09-01 15:27:05 In this example, microseconds and time zone parts are removed from first example, so we need to remove microseconds and time zone abbreviations also from format string Example 3: Converting datetime string to datetime Python3 # Python3 code to demonstrate# Getting datetime object using a date_string # importing datetime moduleimport datetime # datestring for which datetime_obj requireddate_string = 'Sep 01 2021 03:27:05 PM' # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(date_string, '%b %d %Y %I:%M:%S %p') # Printing datetimeprint(datetime_obj) Output: 2021-09-01 15:27:05 Picked Python datetime-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24322, "s": 24292, "text": "Prerequisite: Datetime module" }, { "code": null, "e": 24411, "s": 24322, "text": "In this article, we will learn how to get datetime object from time string using Python." }, { "code": null, "e": 24555, "s": 24411, "text": "To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. " }, { "code": null, "e": 24603, "s": 24555, "text": "Syntax : datetime.strptime(date_string, format)" }, { "code": null, "e": 24616, "s": 24603, "text": "Parameters :" }, { "code": null, "e": 24712, "s": 24616, "text": "date_string : Specified time string containing of which datetime object is required. **Required" }, { "code": null, "e": 24756, "s": 24712, "text": "format : Abbreviation format of date_string" }, { "code": null, "e": 24815, "s": 24756, "text": "Returns : Returns the datetime object of given date_string" }, { "code": null, "e": 24879, "s": 24815, "text": "List of the acceptable format that can be passed to strptime():" }, { "code": null, "e": 24929, "s": 24879, "text": "Example 1: Converting datetime string to datetime" }, { "code": null, "e": 24937, "s": 24929, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Getting datetime object using a date_string # importing datetime moduleimport datetime # datestring for which datetime_obj requireddate_string = '2021-09-01 15:27:05.004573 +0530'print(\"string datetime: \")print(date_string)print(\"datestring class is :\", type(date_string)) # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime( date_string, '%Y-%m-%d %H:%M:%S.%f %z') print(\"converted to datetime:\") # Printing datetimeprint(datetime_obj) # Checking class of datetime_obj.print(\"datetime_obj class is :\", type(datetime_obj))", "e": 25531, "s": 24937, "text": null }, { "code": null, "e": 25539, "s": 25531, "text": "Output:" }, { "code": null, "e": 25734, "s": 25539, "text": "string datetime: \n2021-09-01 15:27:05.004573 +0530\ndatestring class is : <class 'str'>\nconverted to datetime:\n2021-09-01 15:27:05.004573+05:30\ndatetime_obj class is : <class 'datetime.datetime'>" }, { "code": null, "e": 25784, "s": 25734, "text": "Example 2: Converting datetime string to datetime" }, { "code": null, "e": 25792, "s": 25784, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Getting datetime object using a date_string # importing datetime moduleimport datetime # datestring for which datetime_obj requireddate_string = '2021-09-01 15:27:05' # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') # Printing datetimeprint(datetime_obj)", "e": 26150, "s": 25792, "text": null }, { "code": null, "e": 26158, "s": 26150, "text": "Output:" }, { "code": null, "e": 26178, "s": 26158, "text": "2021-09-01 15:27:05" }, { "code": null, "e": 26346, "s": 26178, "text": "In this example, microseconds and time zone parts are removed from first example, so we need to remove microseconds and time zone abbreviations also from format string" }, { "code": null, "e": 26396, "s": 26346, "text": "Example 3: Converting datetime string to datetime" }, { "code": null, "e": 26404, "s": 26396, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Getting datetime object using a date_string # importing datetime moduleimport datetime # datestring for which datetime_obj requireddate_string = 'Sep 01 2021 03:27:05 PM' # using strptime() to get datetime objectdatetime_obj = datetime.datetime.strptime(date_string, '%b %d %Y %I:%M:%S %p') # Printing datetimeprint(datetime_obj)", "e": 26769, "s": 26404, "text": null }, { "code": null, "e": 26777, "s": 26769, "text": "Output:" }, { "code": null, "e": 26797, "s": 26777, "text": "2021-09-01 15:27:05" }, { "code": null, "e": 26804, "s": 26797, "text": "Picked" }, { "code": null, "e": 26828, "s": 26804, "text": "Python datetime-program" }, { "code": null, "e": 26835, "s": 26828, "text": "Python" }, { "code": null, "e": 26933, "s": 26835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26965, "s": 26933, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27007, "s": 26965, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27063, "s": 27007, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27105, "s": 27063, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27160, "s": 27105, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27191, "s": 27160, "text": "Python | os.path.join() method" }, { "code": null, "e": 27213, "s": 27191, "text": "Defaultdict in Python" }, { "code": null, "e": 27252, "s": 27213, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27281, "s": 27252, "text": "Create a directory in Python" } ]
Tryit Editor v3.7
Tryit: Canvas with a text
[]
Java Examples - Display Time in different Country's format
How to display time in different country's format? Following example uses Locale class & DateFormat class to display date in different Country's format. import java.text.DateFormat; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Date d1 = new Date(); System.out.println("today is "+ d1.toString()); Locale locItalian = new Locale("it","ch"); DateFormat df = DateFormat.getDateInstance (DateFormat.FULL, locItalian); System.out.println("today is in Italian Language in Switzerland Format : "+ df.format(d1)); } } The above code sample will produce the following result. today is Mon Jun 22 02:37:06 IST 2009 today is in Italian Language in Switzerland Format : sabato, 22. febbraio 2014 Print Add Notes Bookmark this page
[ { "code": null, "e": 2119, "s": 2068, "text": "How to display time in different country's format?" }, { "code": null, "e": 2221, "s": 2119, "text": "Following example uses Locale class & DateFormat class to display date in different Country's format." }, { "code": null, "e": 2673, "s": 2221, "text": "import java.text.DateFormat;\nimport java.util.*;\n\npublic class Main {\n public static void main(String[] args) throws Exception {\n Date d1 = new Date();\n System.out.println(\"today is \"+ d1.toString()); \n Locale locItalian = new Locale(\"it\",\"ch\");\n DateFormat df = DateFormat.getDateInstance (DateFormat.FULL, locItalian);\n System.out.println(\"today is in Italian Language in Switzerland Format : \"+ df.format(d1));\n }\n}" }, { "code": null, "e": 2730, "s": 2673, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2848, "s": 2730, "text": "today is Mon Jun 22 02:37:06 IST 2009\ntoday is in Italian Language in Switzerland Format : sabato, 22. febbraio 2014\n" }, { "code": null, "e": 2855, "s": 2848, "text": " Print" }, { "code": null, "e": 2866, "s": 2855, "text": " Add Notes" } ]
Explain the concept of primary key with an example (DBMS)?
Key is a data item which is used to identify a record or a value used to identify a record in a database is called a key. It helps uniquely to identify an entity from an entity set. Key allows us to identify a set of attributes that make them sufficient to distinguish entities from each other. Example Account number, employee number, customer number are used as key fields because they specifically identify a record stored in a database. The different types of keys in the database management system (DBMS) are as follows − Primary key Primary key Super key Super key Candidate key Candidate key Alternate key Alternate key Artificial key Artificial key Foreign key Foreign key Primary, super, candidate, alternate and artificial keys show the property of uniqueness whereas the foreign key shows referential integrity. From many candidate keys, the database designer selects one candidate key for his database called as primary key. The primary key uniquely identifies each record in a table and must never be the same for two records. Primary key has some properties which are as follows − Uniqueness (two different records cannot be identical). Uniqueness (two different records cannot be identical). NOT NULL (null value is not allowed). NOT NULL (null value is not allowed). Value in a primary key column can never be modified or updated, if any foreign key refers to that primary key. Value in a primary key column can never be modified or updated, if any foreign key refers to that primary key. Primary key is underlined in a table to clearly identify. For Example − stdNo Consider an employee table given below − Here, Here, Here, In the column, we choose to maintain uniqueness in a table at row level. In the column, we choose to maintain uniqueness in a table at row level. In the column, we choose to maintain uniqueness in a table at row level. In the column, we choose to maintain uniqueness in a table at row level. EmpID is a preferable choice because SSN is a secure value. EmpID is a preferable choice because SSN is a secure value. Primary key is a candidate key which is chosen by a database designer to identify entities with an entity set. Primary key is a candidate key which is chosen by a database designer to identify entities with an entity set. Primary key is minimal super keys. Primary key is minimal super keys. In the ER diagram primary keys are represented by underlining. In the ER diagram primary keys are represented by underlining. Primary key is composed of only a single attribute. Primary key is composed of only a single attribute. But it is possible to have a primary key composed of more than one attribute. But it is possible to have a primary key composed of more than one attribute. To identify the column field as primary key, it has to meet the following conditions − No two rows have the same primary key value. No two rows have the same primary key value. Every row must have a primary key value. Every row must have a primary key value. The primary key field cannot be NULL value. The primary key field cannot be NULL value. Value in the primary key column can never be modified or updated, if any foreign key refers to that primary key. Value in the primary key column can never be modified or updated, if any foreign key refers to that primary key. In the above Entity Relationship Model (ER) diagram: In the customer table customer-id is the primary key. In the customer table customer-id is the primary key. In the loan table loan-number is the primary key. In the loan table loan-number is the primary key.
[ { "code": null, "e": 1244, "s": 1062, "text": "Key is a data item which is used to identify a record or a value used to identify a record in a database is called a key. It helps uniquely to identify an entity from an entity set." }, { "code": null, "e": 1357, "s": 1244, "text": "Key allows us to identify a set of attributes that make them sufficient to distinguish entities from each other." }, { "code": null, "e": 1365, "s": 1357, "text": "Example" }, { "code": null, "e": 1503, "s": 1365, "text": "Account number, employee number, customer number are used as key fields because they specifically identify a record stored in a database." }, { "code": null, "e": 1589, "s": 1503, "text": "The different types of keys in the database management system (DBMS) are as follows −" }, { "code": null, "e": 1601, "s": 1589, "text": "Primary key" }, { "code": null, "e": 1613, "s": 1601, "text": "Primary key" }, { "code": null, "e": 1623, "s": 1613, "text": "Super key" }, { "code": null, "e": 1633, "s": 1623, "text": "Super key" }, { "code": null, "e": 1647, "s": 1633, "text": "Candidate key" }, { "code": null, "e": 1661, "s": 1647, "text": "Candidate key" }, { "code": null, "e": 1675, "s": 1661, "text": "Alternate key" }, { "code": null, "e": 1689, "s": 1675, "text": "Alternate key" }, { "code": null, "e": 1704, "s": 1689, "text": "Artificial key" }, { "code": null, "e": 1719, "s": 1704, "text": "Artificial key" }, { "code": null, "e": 1731, "s": 1719, "text": "Foreign key" }, { "code": null, "e": 1743, "s": 1731, "text": "Foreign key" }, { "code": null, "e": 1885, "s": 1743, "text": "Primary, super, candidate, alternate and artificial keys show the property of uniqueness whereas the foreign key shows referential integrity." }, { "code": null, "e": 2102, "s": 1885, "text": "From many candidate keys, the database designer selects one candidate key for his database called as primary key. The primary key uniquely identifies each record in a table and must never be the same for two records." }, { "code": null, "e": 2157, "s": 2102, "text": "Primary key has some properties which are as follows −" }, { "code": null, "e": 2213, "s": 2157, "text": "Uniqueness (two different records cannot be identical)." }, { "code": null, "e": 2269, "s": 2213, "text": "Uniqueness (two different records cannot be identical)." }, { "code": null, "e": 2307, "s": 2269, "text": "NOT NULL (null value is not allowed)." }, { "code": null, "e": 2345, "s": 2307, "text": "NOT NULL (null value is not allowed)." }, { "code": null, "e": 2456, "s": 2345, "text": "Value in a primary key column can never be modified or updated, if any foreign key refers to that primary key." }, { "code": null, "e": 2567, "s": 2456, "text": "Value in a primary key column can never be modified or updated, if any foreign key refers to that primary key." }, { "code": null, "e": 2625, "s": 2567, "text": "Primary key is underlined in a table to clearly identify." }, { "code": null, "e": 2639, "s": 2625, "text": "For Example −" }, { "code": null, "e": 2645, "s": 2639, "text": "stdNo" }, { "code": null, "e": 2686, "s": 2645, "text": "Consider an employee table given below −" }, { "code": null, "e": 2692, "s": 2686, "text": "Here," }, { "code": null, "e": 2698, "s": 2692, "text": "Here," }, { "code": null, "e": 2704, "s": 2698, "text": "Here," }, { "code": null, "e": 2777, "s": 2704, "text": "In the column, we choose to maintain uniqueness in a table at row level." }, { "code": null, "e": 2850, "s": 2777, "text": "In the column, we choose to maintain uniqueness in a table at row level." }, { "code": null, "e": 2923, "s": 2850, "text": "In the column, we choose to maintain uniqueness in a table at row level." }, { "code": null, "e": 2996, "s": 2923, "text": "In the column, we choose to maintain uniqueness in a table at row level." }, { "code": null, "e": 3056, "s": 2996, "text": "EmpID is a preferable choice because SSN is a secure value." }, { "code": null, "e": 3116, "s": 3056, "text": "EmpID is a preferable choice because SSN is a secure value." }, { "code": null, "e": 3227, "s": 3116, "text": "Primary key is a candidate key which is chosen by a database designer to identify entities with an entity set." }, { "code": null, "e": 3338, "s": 3227, "text": "Primary key is a candidate key which is chosen by a database designer to identify entities with an entity set." }, { "code": null, "e": 3373, "s": 3338, "text": "Primary key is minimal super keys." }, { "code": null, "e": 3408, "s": 3373, "text": "Primary key is minimal super keys." }, { "code": null, "e": 3471, "s": 3408, "text": "In the ER diagram primary keys are represented by underlining." }, { "code": null, "e": 3534, "s": 3471, "text": "In the ER diagram primary keys are represented by underlining." }, { "code": null, "e": 3586, "s": 3534, "text": "Primary key is composed of only a single attribute." }, { "code": null, "e": 3638, "s": 3586, "text": "Primary key is composed of only a single attribute." }, { "code": null, "e": 3716, "s": 3638, "text": "But it is possible to have a primary key composed of more than one attribute." }, { "code": null, "e": 3794, "s": 3716, "text": "But it is possible to have a primary key composed of more than one attribute." }, { "code": null, "e": 3881, "s": 3794, "text": "To identify the column field as primary key, it has to meet the following conditions −" }, { "code": null, "e": 3926, "s": 3881, "text": "No two rows have the same primary key value." }, { "code": null, "e": 3971, "s": 3926, "text": "No two rows have the same primary key value." }, { "code": null, "e": 4012, "s": 3971, "text": "Every row must have a primary key value." }, { "code": null, "e": 4053, "s": 4012, "text": "Every row must have a primary key value." }, { "code": null, "e": 4097, "s": 4053, "text": "The primary key field cannot be NULL value." }, { "code": null, "e": 4141, "s": 4097, "text": "The primary key field cannot be NULL value." }, { "code": null, "e": 4254, "s": 4141, "text": "Value in the primary key column can never be modified or updated, if any foreign key refers to that primary key." }, { "code": null, "e": 4367, "s": 4254, "text": "Value in the primary key column can never be modified or updated, if any foreign key refers to that primary key." }, { "code": null, "e": 4420, "s": 4367, "text": "In the above Entity Relationship Model (ER) diagram:" }, { "code": null, "e": 4474, "s": 4420, "text": "In the customer table customer-id is the primary key." }, { "code": null, "e": 4528, "s": 4474, "text": "In the customer table customer-id is the primary key." }, { "code": null, "e": 4578, "s": 4528, "text": "In the loan table loan-number is the primary key." }, { "code": null, "e": 4628, "s": 4578, "text": "In the loan table loan-number is the primary key." } ]
Different Shells in Linux - GeeksforGeeks
03 Dec, 2019 SHELL is a program which provides the interface between the user and an operating system. When the user logs in OS starts a shell for user. Kernel controls all essential computer operations, and provides the restriction to hardware access, coordinates all executing utilities, and manages Resources between process. Using kernel only user can access utilities provided by operating system. Types of Shell: The C Shell –Denoted as csh Bill Joy created it at the University of California at Berkeley. It incorporated features such as aliases and command history. It includes helpful programming features like built-in arithmetic and C-like expression syntax.In C shell:Command full-path name is /bin/csh, Non-root user default prompt is hostname %, Root user default prompt is hostname #. Denoted as csh Bill Joy created it at the University of California at Berkeley. It incorporated features such as aliases and command history. It includes helpful programming features like built-in arithmetic and C-like expression syntax. In C shell: Command full-path name is /bin/csh, Non-root user default prompt is hostname %, Root user default prompt is hostname #. The Bourne Shell –Denoted as sh It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is faster and more preferred. It lacks features for interactive use like the ability to recall previous commands. It also lacks built-in arithmetic and logical expression handling. It is default shell for Solaris OS.For the Bourne shell the:Command full-path name is /bin/sh and /sbin/sh, Non-root user default prompt is $, Root user default prompt is #. Denoted as sh It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is faster and more preferred. It lacks features for interactive use like the ability to recall previous commands. It also lacks built-in arithmetic and logical expression handling. It is default shell for Solaris OS. For the Bourne shell the: Command full-path name is /bin/sh and /sbin/sh, Non-root user default prompt is $, Root user default prompt is #. The Korn ShellIt is denoted as ksh It Was written by David Korn at AT&T Bell LabsIt is a superset of the Bourne shell.So it supports everything in the Bourne shell.It has interactive features. It includes features like built-in arithmetic and C-like arrays, functions, and string-manipulation facilities.It is faster than C shell. It is compatible with script written for C shell.For the Korn shell the:Command full-path name is /bin/ksh, Non-root user default prompt is $, Root user default prompt is #. It is denoted as ksh It Was written by David Korn at AT&T Bell LabsIt is a superset of the Bourne shell.So it supports everything in the Bourne shell.It has interactive features. It includes features like built-in arithmetic and C-like arrays, functions, and string-manipulation facilities.It is faster than C shell. It is compatible with script written for C shell. For the Korn shell the: Command full-path name is /bin/ksh, Non-root user default prompt is $, Root user default prompt is #. GNU Bourne-Again Shell –Denoted as bash It is compatible to the Bourne shell. It includes features from Korn and Bourne shell.For the GNU Bourne-Again shell the:Command full-path name is /bin/bash, Default prompt for a non-root user is bash-g.gg$ (g.ggindicates the shell version number like bash-3.50$), Root user default prompt is bash-g.gg#. Denoted as bash It is compatible to the Bourne shell. It includes features from Korn and Bourne shell. For the GNU Bourne-Again shell the: Command full-path name is /bin/bash, Default prompt for a non-root user is bash-g.gg$ (g.ggindicates the shell version number like bash-3.50$), Root user default prompt is bash-g.gg#. aniketpaul446 linux-command Shell Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization echo command in Linux with Examples tee command in Linux with examples
[ { "code": null, "e": 24642, "s": 24614, "text": "\n03 Dec, 2019" }, { "code": null, "e": 25032, "s": 24642, "text": "SHELL is a program which provides the interface between the user and an operating system. When the user logs in OS starts a shell for user. Kernel controls all essential computer operations, and provides the restriction to hardware access, coordinates all executing utilities, and manages Resources between process. Using kernel only user can access utilities provided by operating system." }, { "code": null, "e": 25048, "s": 25032, "text": "Types of Shell:" }, { "code": null, "e": 25430, "s": 25048, "text": "The C Shell –Denoted as csh Bill Joy created it at the University of California at Berkeley. It incorporated features such as aliases and command history. It includes helpful programming features like built-in arithmetic and C-like expression syntax.In C shell:Command full-path name is /bin/csh,\nNon-root user default prompt is hostname %,\nRoot user default prompt is hostname #. " }, { "code": null, "e": 25446, "s": 25430, "text": "Denoted as csh " }, { "code": null, "e": 25669, "s": 25446, "text": "Bill Joy created it at the University of California at Berkeley. It incorporated features such as aliases and command history. It includes helpful programming features like built-in arithmetic and C-like expression syntax." }, { "code": null, "e": 25681, "s": 25669, "text": "In C shell:" }, { "code": null, "e": 25802, "s": 25681, "text": "Command full-path name is /bin/csh,\nNon-root user default prompt is hostname %,\nRoot user default prompt is hostname #. " }, { "code": null, "e": 26274, "s": 25802, "text": "The Bourne Shell –Denoted as sh It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is faster and more preferred. It lacks features for interactive use like the ability to recall previous commands. It also lacks built-in arithmetic and logical expression handling. It is default shell for Solaris OS.For the Bourne shell the:Command full-path name is /bin/sh and /sbin/sh,\nNon-root user default prompt is $,\nRoot user default prompt is #. " }, { "code": null, "e": 26289, "s": 26274, "text": "Denoted as sh " }, { "code": null, "e": 26590, "s": 26289, "text": "It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is faster and more preferred. It lacks features for interactive use like the ability to recall previous commands. It also lacks built-in arithmetic and logical expression handling. It is default shell for Solaris OS." }, { "code": null, "e": 26616, "s": 26590, "text": "For the Bourne shell the:" }, { "code": null, "e": 26731, "s": 26616, "text": "Command full-path name is /bin/sh and /sbin/sh,\nNon-root user default prompt is $,\nRoot user default prompt is #. " }, { "code": null, "e": 27237, "s": 26731, "text": "The Korn ShellIt is denoted as ksh It Was written by David Korn at AT&T Bell LabsIt is a superset of the Bourne shell.So it supports everything in the Bourne shell.It has interactive features. It includes features like built-in arithmetic and C-like arrays, functions, and string-manipulation facilities.It is faster than C shell. It is compatible with script written for C shell.For the Korn shell the:Command full-path name is /bin/ksh,\nNon-root user default prompt is $,\nRoot user default prompt is #. " }, { "code": null, "e": 27259, "s": 27237, "text": "It is denoted as ksh " }, { "code": null, "e": 27605, "s": 27259, "text": "It Was written by David Korn at AT&T Bell LabsIt is a superset of the Bourne shell.So it supports everything in the Bourne shell.It has interactive features. It includes features like built-in arithmetic and C-like arrays, functions, and string-manipulation facilities.It is faster than C shell. It is compatible with script written for C shell." }, { "code": null, "e": 27629, "s": 27605, "text": "For the Korn shell the:" }, { "code": null, "e": 27732, "s": 27629, "text": "Command full-path name is /bin/ksh,\nNon-root user default prompt is $,\nRoot user default prompt is #. " }, { "code": null, "e": 28079, "s": 27732, "text": "GNU Bourne-Again Shell –Denoted as bash It is compatible to the Bourne shell. It includes features from Korn and Bourne shell.For the GNU Bourne-Again shell the:Command full-path name is /bin/bash,\nDefault prompt for a non-root user is bash-g.gg$ \n(g.ggindicates the shell version number like bash-3.50$),\nRoot user default prompt is bash-g.gg#. " }, { "code": null, "e": 28096, "s": 28079, "text": "Denoted as bash " }, { "code": null, "e": 28183, "s": 28096, "text": "It is compatible to the Bourne shell. It includes features from Korn and Bourne shell." }, { "code": null, "e": 28219, "s": 28183, "text": "For the GNU Bourne-Again shell the:" }, { "code": null, "e": 28405, "s": 28219, "text": "Command full-path name is /bin/bash,\nDefault prompt for a non-root user is bash-g.gg$ \n(g.ggindicates the shell version number like bash-3.50$),\nRoot user default prompt is bash-g.gg#. " }, { "code": null, "e": 28419, "s": 28405, "text": "aniketpaul446" }, { "code": null, "e": 28433, "s": 28419, "text": "linux-command" }, { "code": null, "e": 28439, "s": 28433, "text": "Shell" }, { "code": null, "e": 28450, "s": 28439, "text": "Linux-Unix" }, { "code": null, "e": 28548, "s": 28450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28583, "s": 28548, "text": "tar command in Linux with examples" }, { "code": null, "e": 28616, "s": 28583, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 28654, "s": 28616, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28690, "s": 28654, "text": "diff command in Linux with examples" }, { "code": null, "e": 28725, "s": 28690, "text": "Cat command in Linux with examples" }, { "code": null, "e": 28761, "s": 28725, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28798, "s": 28761, "text": "touch command in Linux with Examples" }, { "code": null, "e": 28842, "s": 28798, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 28878, "s": 28842, "text": "echo command in Linux with Examples" } ]
Convert a Queue to a List in Java
In order to convert a Queue to a List in Java, we can create an LinkedList and pass the Queue as an argument in the parameterized constructor of an ArrayList. This can be done as follows − Queue q = new LinkedList(); List l = new ArrayList(q); The quickest way is used to LinkedList in the first place which can be used both as a List and a Queue. This can be done as follows − Queue q = new LinkedList(); List l = (List) q; Let us see a program to convert a queue to a list − Live Demo import java.util.LinkedList; import java.util.List; import java.util.Queue; public class Example { public static void main(String[] args) { Queue q = new LinkedList(); q.add("Good"); q.add("Morning"); List l = (List) q; System.out.println(l); } } [Good, Morning]
[ { "code": null, "e": 1251, "s": 1062, "text": "In order to convert a Queue to a List in Java, we can create an LinkedList and pass the Queue as an argument in the parameterized constructor of an ArrayList. This can be done as follows −" }, { "code": null, "e": 1306, "s": 1251, "text": "Queue q = new LinkedList();\nList l = new ArrayList(q);" }, { "code": null, "e": 1440, "s": 1306, "text": "The quickest way is used to LinkedList in the first place which can be used both as a List and a Queue. This can be done as follows −" }, { "code": null, "e": 1487, "s": 1440, "text": "Queue q = new LinkedList();\nList l = (List) q;" }, { "code": null, "e": 1539, "s": 1487, "text": "Let us see a program to convert a queue to a list −" }, { "code": null, "e": 1550, "s": 1539, "text": " Live Demo" }, { "code": null, "e": 1833, "s": 1550, "text": "import java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\npublic class Example {\n public static void main(String[] args) {\n Queue q = new LinkedList();\n q.add(\"Good\");\n q.add(\"Morning\");\n List l = (List) q;\n System.out.println(l);\n }\n}" }, { "code": null, "e": 1849, "s": 1833, "text": "[Good, Morning]" } ]
How to find duplicates in an array using set() and filter() methods in JavaScript?
To remove duplicates in an array we have many logical methods, but advanced javascript has provided some methods so that the task of removing duplicates has become very simple. Some of those methods are set() and filter(). For better understanding lets' discuss each method individually. The important use of the set() method is that it only allows unique values. In other words, it will automatically remove duplicates and makes the task easy for us. The Set() method won't take any logical approach in removing duplicates. In the following example, the duplicates in the provided array have been removed without any logical approach by using set() method. Live Demo <html> <body> <script> var dupNames = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim']; var uniArr = [...new Set(dupNames)]; document.write("Before removing :" +" "+ dupNames); document.write("</br>"); document.write("After using set() method :" +" "+ uniArr); </script> </body> </html> Before removing : John,Ram,Rahim,Remo,Ram,Rahim After using set() method : John,Ram,Rahim,Remo In the following example, using filter() method each element is scrutinized whether it is repeated two or more times. If any element found repeated two or more times then only one of its value is permitted and displayed as shown in the output. Live Demo <html> <body> <script> var dupnam = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim']; var x = (dupname) => dupname.filter((v,i) => dupname.indexOf(v) === i) document.write("Before removing : " +" "+ dupname); document.write("</br>"); document.write("After filter() method :" +" "+x(dupname)); </script> </body> </html> Before removing : John,Ram,Rahim,Remo,Ram,Rahim After filter() method : John,Ram,Rahim,Remo
[ { "code": null, "e": 1350, "s": 1062, "text": "To remove duplicates in an array we have many logical methods, but advanced javascript has provided some methods so that the task of removing duplicates has become very simple. Some of those methods are set() and filter(). For better understanding lets' discuss each method individually." }, { "code": null, "e": 1587, "s": 1350, "text": "The important use of the set() method is that it only allows unique values. In other words, it will automatically remove duplicates and makes the task easy for us. The Set() method won't take any logical approach in removing duplicates." }, { "code": null, "e": 1721, "s": 1587, "text": "In the following example, the duplicates in the provided array have been removed without any logical approach by using set() method. " }, { "code": null, "e": 1731, "s": 1721, "text": "Live Demo" }, { "code": null, "e": 2033, "s": 1731, "text": "<html>\n<body>\n<script>\n var dupNames = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim'];\n var uniArr = [...new Set(dupNames)];\n document.write(\"Before removing :\" +\" \"+ dupNames);\n document.write(\"</br>\");\n document.write(\"After using set() method :\" +\" \"+ uniArr);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2128, "s": 2033, "text": "Before removing : John,Ram,Rahim,Remo,Ram,Rahim\nAfter using set() method : John,Ram,Rahim,Remo" }, { "code": null, "e": 2372, "s": 2128, "text": "In the following example, using filter() method each element is scrutinized whether it is repeated two or more times. If any element found repeated two or more times then only one of its value is permitted and displayed as shown in the output." }, { "code": null, "e": 2382, "s": 2372, "text": "Live Demo" }, { "code": null, "e": 2718, "s": 2382, "text": "<html>\n<body>\n<script>\n var dupnam = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim'];\n var x = (dupname) => dupname.filter((v,i) => dupname.indexOf(v) === i)\n document.write(\"Before removing : \" +\" \"+ dupname); \n document.write(\"</br>\");\n document.write(\"After filter() method :\" +\" \"+x(dupname));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2810, "s": 2718, "text": "Before removing : John,Ram,Rahim,Remo,Ram,Rahim\nAfter filter() method : John,Ram,Rahim,Remo" } ]
Web2py - Access Control
Almost every application needs to be able to authenticate users and set permissions. web2py comes with an extensive and customizable role-based access control mechanism.web2py. It also supports the protocols, such as CAS, OpenID, OAuth 1.0, LDAP, PAM, X509, and many more. web2py includes a mechanism known as Role Based Access Control mechanism (RBAC) which is an approach to restricting system access to authorized users. The web2py class that implements RBAC is called Auth. Look at the schema given below. Auth defines the following tables − auth_user stores users' name, email address, password, and status. auth_group stores groups or roles for users in a many-to-many structure auth_membership Stores the information of links users and groups in a many-to-many structure auth_permission The table links groups and permissions. auth_event logs changes in the other tables and successful access auth_cas It is used for Central Authentication Service There are two ways to customize Auth. To define a custom db.auth_user table from scratch. To define a custom db.auth_user table from scratch. Let web2py define the auth table. Let web2py define the auth table. Let us look at the last method of defining the auth table. In the db.py model, replace the following line − auth.define_tables() Replace it with the following code − auth.settings.extra_fields['auth_user'] = [ Field('phone_number',requires = IS_MATCH('\d{3}\-\d{3}\-\d{4}')), Field('address','text') ] auth.define_tables(username = True) The assumption is that each user consists of phone number, username and address. auth.settings.extra_fields is a dictionary of extra fields. The key is the name of the auth table to which to add the extra fields. The value is a list of extra fields. Here, we have added two extra fields, phone_number and address. username has to be treated in a special way, because it is involved in the authentication process, which is normally based on the email field. By passing the username argument to the following line, it is informed to web2py that we want the username field, and we want to use it for login instead of the email field. It acts like a primary key. auth.define_tables(username = True) The username is treated as a unique value. There may be cases when registration happens outside the normal registration form. It also happens so, that the new user is forced to login, to complete their registration. This can be done using a dummy field, complete_registration that is set to False by default, and is set to True when they update their profile. auth.settings.extra_fields['auth_user'] = [ Field('phone_number',requires = IS_MATCH('\d{3}\-\d{3}\-\d{4}'), comment = "i.e. 123-123-1234"), Field('address','text'), Field('complete_registration',default = False,update = True, writable = False, readable = False) ] auth.define_tables(username = True) This scenario may intend the new users, upon login, to complete their registration. In db.py, in the models folder, we can append the following code − if auth.user and not auth.user.complete_registration: if not (request.controller,request.function) == ('default','user'): redirect(URL('default','user/profile')) This will force the new users to edit their profile as per the requirements. It is the process of granting some access or giving permission of something to the users. In web2py once the new user is created or registered, a new group is created to contain the user. The role of the new user is conventionally termed as “user_[id]” where id is the unique identification of the user. The default value for the creation of the new group is − auth.settings.create_user_groups = "user_%(id)s" The creation of the groups among the users can be disabled by − auth.settings.create_user_groups = None Creation, granting access to particular members and permissions can be achieved programmatically with the help of appadmin also. Some of the implementations are listed as follows − auth.add_group('role', 'description') returns the id of the newly created group. auth.del_group(group_id) Deletes the group with the specified id auth.del_group(auth.id_group('user_7')) Deletes the user group with the given identification. auth.user_group(user_id) Returns the value of id of group uniquely associated for the given user. auth.add_membership(group_id, user_id) Returns the value of user_id for the given group_id auth.del_membership(group_id, user_id) Revokes access of the given member_id i.e. user_id from the given group. auth.has_membership(group_id, user_id, role) Checks whether user_id belongs to the given group. web2py provides an industry standard namely, Client Authentication Service – CAS for both client and server built-in web2py. It is a third party authentication tool. It is an open protocol for distributed authentication. The working of CAS is as follows − If the user visits the website, the protocol checks whether the user is authenticated. If the user visits the website, the protocol checks whether the user is authenticated. If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application. If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application. If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email. If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email. After successful registration, the user is authenticated with the key, which is used by CAS appliance. After successful registration, the user is authenticated with the key, which is used by CAS appliance. The key is used to get the credentials of user via HTTP request, which is set in the background. The key is used to get the credentials of user via HTTP request, which is set in the background. Print Add Notes Bookmark this page
[ { "code": null, "e": 2166, "s": 1893, "text": "Almost every application needs to be able to authenticate users and set permissions. web2py comes with an extensive and customizable role-based access control mechanism.web2py. It also supports the protocols, such as CAS, OpenID, OAuth 1.0, LDAP, PAM, X509, and many more." }, { "code": null, "e": 2371, "s": 2166, "text": "web2py includes a mechanism known as Role Based Access Control mechanism (RBAC) which is an approach to restricting system access to authorized users. The web2py class that implements RBAC is called Auth." }, { "code": null, "e": 2403, "s": 2371, "text": "Look at the schema given below." }, { "code": null, "e": 2439, "s": 2403, "text": "Auth defines the following tables −" }, { "code": null, "e": 2449, "s": 2439, "text": "auth_user" }, { "code": null, "e": 2506, "s": 2449, "text": "stores users' name, email address, password, and status." }, { "code": null, "e": 2517, "s": 2506, "text": "auth_group" }, { "code": null, "e": 2578, "s": 2517, "text": "stores groups or roles for users in a many-to-many structure" }, { "code": null, "e": 2594, "s": 2578, "text": "auth_membership" }, { "code": null, "e": 2671, "s": 2594, "text": "Stores the information of links users and groups in a many-to-many structure" }, { "code": null, "e": 2687, "s": 2671, "text": "auth_permission" }, { "code": null, "e": 2727, "s": 2687, "text": "The table links groups and permissions." }, { "code": null, "e": 2738, "s": 2727, "text": "auth_event" }, { "code": null, "e": 2793, "s": 2738, "text": "logs changes in the other tables and successful access" }, { "code": null, "e": 2802, "s": 2793, "text": "auth_cas" }, { "code": null, "e": 2848, "s": 2802, "text": "It is used for Central Authentication Service" }, { "code": null, "e": 2886, "s": 2848, "text": "There are two ways to customize Auth." }, { "code": null, "e": 2938, "s": 2886, "text": "To define a custom db.auth_user table from scratch." }, { "code": null, "e": 2990, "s": 2938, "text": "To define a custom db.auth_user table from scratch." }, { "code": null, "e": 3024, "s": 2990, "text": "Let web2py define the auth table." }, { "code": null, "e": 3058, "s": 3024, "text": "Let web2py define the auth table." }, { "code": null, "e": 3166, "s": 3058, "text": "Let us look at the last method of defining the auth table. In the db.py model, replace the following line −" }, { "code": null, "e": 3188, "s": 3166, "text": "auth.define_tables()\n" }, { "code": null, "e": 3225, "s": 3188, "text": "Replace it with the following code −" }, { "code": null, "e": 3404, "s": 3225, "text": "auth.settings.extra_fields['auth_user'] = [\n Field('phone_number',requires = IS_MATCH('\\d{3}\\-\\d{3}\\-\\d{4}')),\n Field('address','text')\n]\n\nauth.define_tables(username = True)" }, { "code": null, "e": 3485, "s": 3404, "text": "The assumption is that each user consists of phone number, username and address." }, { "code": null, "e": 3718, "s": 3485, "text": "auth.settings.extra_fields is a dictionary of extra fields. The key is the name of the auth table to which to add the extra fields. The value is a list of extra fields. Here, we have added two extra fields, phone_number and address." }, { "code": null, "e": 4063, "s": 3718, "text": "username has to be treated in a special way, because it is involved in the authentication process, which is normally based on the email field. By passing the username argument to the following line, it is informed to web2py that we want the username field, and we want to use it for login instead of the email field. It acts like a primary key." }, { "code": null, "e": 4100, "s": 4063, "text": "auth.define_tables(username = True)\n" }, { "code": null, "e": 4316, "s": 4100, "text": "The username is treated as a unique value. There may be cases when registration happens outside the normal registration form. It also happens so, that the new user is forced to login, to complete their registration." }, { "code": null, "e": 4460, "s": 4316, "text": "This can be done using a dummy field, complete_registration that is set to False by default, and is set to True when they update their profile." }, { "code": null, "e": 4777, "s": 4460, "text": "auth.settings.extra_fields['auth_user'] = [\n Field('phone_number',requires = IS_MATCH('\\d{3}\\-\\d{3}\\-\\d{4}'),\n comment = \"i.e. 123-123-1234\"),\n Field('address','text'),\n Field('complete_registration',default = False,update = True,\n writable = False, readable = False)\n]\n\nauth.define_tables(username = True)" }, { "code": null, "e": 4861, "s": 4777, "text": "This scenario may intend the new users, upon login, to complete their registration." }, { "code": null, "e": 4928, "s": 4861, "text": "In db.py, in the models folder, we can append the following code −" }, { "code": null, "e": 5093, "s": 4928, "text": "if auth.user and not auth.user.complete_registration:\nif not (request.controller,request.function) == ('default','user'):\n redirect(URL('default','user/profile'))" }, { "code": null, "e": 5170, "s": 5093, "text": "This will force the new users to edit their profile as per the requirements." }, { "code": null, "e": 5260, "s": 5170, "text": "It is the process of granting some access or giving permission of something to the users." }, { "code": null, "e": 5474, "s": 5260, "text": "In web2py once the new user is created or registered, a new group is created to contain the user. The role of the new user is conventionally termed as “user_[id]” where id is the unique identification of the user." }, { "code": null, "e": 5531, "s": 5474, "text": "The default value for the creation of the new group is −" }, { "code": null, "e": 5581, "s": 5531, "text": "auth.settings.create_user_groups = \"user_%(id)s\"\n" }, { "code": null, "e": 5645, "s": 5581, "text": "The creation of the groups among the users can be disabled by −" }, { "code": null, "e": 5686, "s": 5645, "text": "auth.settings.create_user_groups = None\n" }, { "code": null, "e": 5815, "s": 5686, "text": "Creation, granting access to particular members and permissions can be achieved programmatically with the help of appadmin also." }, { "code": null, "e": 5867, "s": 5815, "text": "Some of the implementations are listed as follows −" }, { "code": null, "e": 5905, "s": 5867, "text": "auth.add_group('role', 'description')" }, { "code": null, "e": 5948, "s": 5905, "text": "returns the id of the newly created group." }, { "code": null, "e": 5973, "s": 5948, "text": "auth.del_group(group_id)" }, { "code": null, "e": 6013, "s": 5973, "text": "Deletes the group with the specified id" }, { "code": null, "e": 6053, "s": 6013, "text": "auth.del_group(auth.id_group('user_7'))" }, { "code": null, "e": 6107, "s": 6053, "text": "Deletes the user group with the given identification." }, { "code": null, "e": 6132, "s": 6107, "text": "auth.user_group(user_id)" }, { "code": null, "e": 6205, "s": 6132, "text": "Returns the value of id of group uniquely associated for the given user." }, { "code": null, "e": 6244, "s": 6205, "text": "auth.add_membership(group_id, user_id)" }, { "code": null, "e": 6296, "s": 6244, "text": "Returns the value of user_id for the given group_id" }, { "code": null, "e": 6335, "s": 6296, "text": "auth.del_membership(group_id, user_id)" }, { "code": null, "e": 6408, "s": 6335, "text": "Revokes access of the given member_id i.e. user_id from the given group." }, { "code": null, "e": 6453, "s": 6408, "text": "auth.has_membership(group_id, user_id, role)" }, { "code": null, "e": 6504, "s": 6453, "text": "Checks whether user_id belongs to the given group." }, { "code": null, "e": 6670, "s": 6504, "text": "web2py provides an industry standard namely, Client Authentication Service – CAS for both client and server built-in web2py. It is a third party authentication tool." }, { "code": null, "e": 6760, "s": 6670, "text": "It is an open protocol for distributed authentication. The working of CAS is as follows −" }, { "code": null, "e": 6847, "s": 6760, "text": "If the user visits the website, the protocol checks whether the user is authenticated." }, { "code": null, "e": 6934, "s": 6847, "text": "If the user visits the website, the protocol checks whether the user is authenticated." }, { "code": null, "e": 7080, "s": 6934, "text": "If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application." }, { "code": null, "e": 7226, "s": 7080, "text": "If the user is not authenticated to the application, the protocol redirects to the page where the user can register or log in to the application." }, { "code": null, "e": 7359, "s": 7226, "text": "If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email." }, { "code": null, "e": 7492, "s": 7359, "text": "If the registration is completed, user receives an email. The registration is not complete until and unless user verifies the email." }, { "code": null, "e": 7595, "s": 7492, "text": "After successful registration, the user is authenticated with the key, which is used by CAS appliance." }, { "code": null, "e": 7698, "s": 7595, "text": "After successful registration, the user is authenticated with the key, which is used by CAS appliance." }, { "code": null, "e": 7795, "s": 7698, "text": "The key is used to get the credentials of user via HTTP request, which is set in the background." }, { "code": null, "e": 7892, "s": 7795, "text": "The key is used to get the credentials of user via HTTP request, which is set in the background." }, { "code": null, "e": 7899, "s": 7892, "text": " Print" }, { "code": null, "e": 7910, "s": 7899, "text": " Add Notes" } ]
AthenaHealth Interview Experience | On-Campus Virtual 2020 - GeeksforGeeks
15 Sep, 2020 College: M.S Ramaiah Institute of Technology, Bangalore Date: 26th August 2020 and 27th August 2020 Athena Health is a USA based IT company with the vision is to create a thriving ecosystem that delivers accessible, high-quality, and sustainable healthcare for all. The Company has visited our college with a star package and for the designation of Associate Member of Technical Staff for development. There were a total of 433 students registered for this on-campus recruitment drive. Only final year bachelor students were allowed to sit for this drive. Pre-Placement Talk: Like every other recruitment drive Athena health also conducted a virtual pre-placement talk which mainly focuses on the job description, Cost To Company, work culture, and vision of the company. Round 1 (MCQ & Coding): This round held on HackerRank and time duration for this round was 90mins. First question: 50 marks Second Question: 75 marks Coding Questions: The First Coding question of 50 marks was an easy level question that can be solved using multiple ways but due to time complexity constraint, one needs to solve this question in maximum 0(n) time complexity to pass all test cases. The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Example: Input: A[] = {100, 180, 260, 310, 40 ,535, 695} Output: 865 Explanation: We can buy stock on day 0, and sell it on day 3 and again buying on day 4 and sell it on day 6, which will give us maximum profit.The Second Coding Question of 75 marks also has several ways to solve the question but I solved it using Hashing Data Structure.Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. and output the count of all the distinct pairs. Example: Input: N=5 M=5 X=9 A[] = {1, 2, 4, 5, 7} B[]={5, 6, 3, 4, 8} Output: 3 Explanation: (1, 8), (4, 5), (5, 4) are the pairs which sum to 9. The First Coding question of 50 marks was an easy level question that can be solved using multiple ways but due to time complexity constraint, one needs to solve this question in maximum 0(n) time complexity to pass all test cases. The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Example: Input: A[] = {100, 180, 260, 310, 40 ,535, 695} Output: 865 Explanation: We can buy stock on day 0, and sell it on day 3 and again buying on day 4 and sell it on day 6, which will give us maximum profit. The First Coding question of 50 marks was an easy level question that can be solved using multiple ways but due to time complexity constraint, one needs to solve this question in maximum 0(n) time complexity to pass all test cases. The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Example: Input: A[] = {100, 180, 260, 310, 40 ,535, 695} Output: 865 Explanation: We can buy stock on day 0, and sell it on day 3 and again buying on day 4 and sell it on day 6, which will give us maximum profit. The Second Coding Question of 75 marks also has several ways to solve the question but I solved it using Hashing Data Structure.Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. and output the count of all the distinct pairs. Example: Input: N=5 M=5 X=9 A[] = {1, 2, 4, 5, 7} B[]={5, 6, 3, 4, 8} Output: 3 Explanation: (1, 8), (4, 5), (5, 4) are the pairs which sum to 9. The Second Coding Question of 75 marks also has several ways to solve the question but I solved it using Hashing Data Structure. Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. and output the count of all the distinct pairs. Example: Input: N=5 M=5 X=9 A[] = {1, 2, 4, 5, 7} B[]={5, 6, 3, 4, 8} Output: 3 Explanation: (1, 8), (4, 5), (5, 4) are the pairs which sum to 9. Around 50 Students out of 433 students were shortlisted for the next round. Round 2 (Technical Interview): After the first round, all shortlisted candidates received a codepair meeting link on their registered email. The interview was virtual due to the COVID-19 pandemic and was conducted on codepair platform of HackerRank specially designed for virtual interviews. My interview was in the first batch of interview sessions because they call students after sorting them alphabetically on the basis of their name. The interviewer was very friendly, asked me to introduce myself, asked me some questions related to my resume, and directly moved on to the technical aspect, some questions which he asked were: What do you mean by database transaction and what is ACID properties? I explained it Which is your preferred programming language and why? I told JavaWhy do you like java and not C/C++? I told because I don’t like the concept of Pointers and in java, we don’t use pointers instead we use objects in java and I find myself more comfortable with objects.How objects removed the concept of pointers? I told everything about the objects and explain in properly.What is the difference between Abstract class and Interface in java? Explain External and Internal fragmentation occurs during the dynamic allocation of memory? What do you mean by database transaction and what is ACID properties? I explained it Which is your preferred programming language and why? I told Java Why do you like java and not C/C++? I told because I don’t like the concept of Pointers and in java, we don’t use pointers instead we use objects in java and I find myself more comfortable with objects. How objects removed the concept of pointers? I told everything about the objects and explain in properly. What is the difference between Abstract class and Interface in java? Explain External and Internal fragmentation occurs during the dynamic allocation of memory? After this, he gave me a competitive programming question and asked me to solve it. He asked me the same 75 marks question asked in the coding round with some minor changes and asked me to explain the algorithm and code the most optimized solution for the same. As codepair platform contains a whiteboard and java editor, I explained the algorithm verbally with the help of an example and code the same on the editor, and fortunately, it works and passes all the test cases of random input which he gave. Consider a string S and text T. Output the smallest window in the string S having all characters of the text T. Both the string S and text T contains lowercase English alphabets.Example: Is the smallest substring in the given string S which contains every character of T. (ahtenahealth) Input: S = athenahealth T=nlt Output:"nahealt" Consider a string S and text T. Output the smallest window in the string S having all characters of the text T. Both the string S and text T contains lowercase English alphabets. Example: Is the smallest substring in the given string S which contains every character of T. (ahtenahealth) Input: S = athenahealth T=nlt Output:"nahealt" PS: I had solved this question before more than once as it is a standard hashing question, so I was very confident and excited too I told him there can be two approaches to solve this question the first one is traversing both S and T using two for loops and checking concurrently which will take 0(n2) time complexity, so I would like to go with a more efficient method using hashing data structure which I guess would take 0(nlogn) time complexity. He asked me to explain the algorithm on the whiteboard , as soon as I explained the algorithm he did some minor changes like added duplicates characters in T and then asked for my approach and code. fortunately, I got my code correct and it worked for the random input he gave. (The interviewer was very friendly and helping me while I was typing code). After that, he wanted to check my logical reasoning and gave me a mathematical series and asked me to find the general mathematical pattern and code the same on the editor using java. While I was coding he asked me, in java why do we write the main function as public static void main(String args[]) Then he asked me “do you have any questions?”, I asked him some questions related to Athenahealth, job description and things on which I should work, he was very cooperative and gave a very positive reply to all the questions. NOTE: Interviewer always focuses on the problem-solving approach of an interviewee, they also give hints and help you in solving the problem with appropriate algorithms, just don’t fake yourself an interview and don’t make excuses. Around 21:00, all the shortlisted students got a Microsoft Team meeting link on their registered email for Managerial Round which was conducted the very next day. They Shortlisted around 15 students for the Managerial round. Round 3 (Managerial Round): Managerial Round is conducted to make the decision of recruiting a person more rigid and perfect, All the students who are shortlisted till this round are a capable and good fit for the job profile. In this round, the interviewer will probably have some feedback for you. This round of mine started with the standard interview question “Tell me about Yourself”? This is the basic format for an IT fresher to answer this question with confidence and create a good impression on the interviewer. (One can also mention their CGPA in this answer but it depends on individual choice) Basic format to answer Tell me about yourself (for IT freshers) Moving on, He went through my projects mentioned in my resume and asked me to explain my project’s ObjectiveTechnologies and libraries used.Challenges faced. Rectification and solution to those challenges.The outcome of the project and future endeavors of this project.A number of members in my team and what was my contribution to the project.How did we manage to work as a team during this pandemic for this project as all of us were working from our home? Objective Technologies and libraries used. Challenges faced. Rectification and solution to those challenges. The outcome of the project and future endeavors of this project. A number of members in my team and what was my contribution to the project. How did we manage to work as a team during this pandemic for this project as all of us were working from our home? He asked me some normal technical questions related to the database and connections of the project in between while I was explaining above mentioned points. After that, He again went through my resume and asked me about the Entrepreneurship Development Center (E-cell) of our college as I was the core member of the club, He also asked questions regarding the work we do, events we organize and how do we work as a team , just after that he gave me a situation related to management, teamwork and asked me what I will do in that situation. Then he asked me “Do you have any questions”? I asked him some questions related to the products of Athena health and the technologies used to create those products, I also asked him regarding the job role and also gave one suggestion for the products of Athenahealth. He replied to all the answers in a very polite and positive manner and gave feedback for my project as well. In Managerial Round, They had also asked puzzles to some of my friends but fortunately, he did not ask any puzzle to me Note: Before going for this round, go through your projects and all its technical aspects, one should know everything about the things they are mentioning in their resume because the interviewer can ask anything but not beyond your resume. Prepare well and communicate with confidence and smile. After around 35 minutes of my Managerial Round, I received one more Microsoft Team meeting link for HR Round on my email. Round 4 (HR Round): Every company conducts an HR Round to judge your personality, behavior, your weakness, your strength, your background, your capability to handle the role and to make sure that you are the right fit for the job. The HR Round is usually the last round in the recruitment process of a company. This round of mine started with the question “What do you know about Athenahealth and its working ?” I started with the vision of the company and then mentioned some of its products and told everything I knew about the company. After that, she went through my resume and asked lots of questions related to my education, my family, my certificates, my internships, my extracurricular activities, and skills, etc. Some most important questions HR asked me were: Do you have plans for higher studies?Do you have any job location preference?What are your long term plans?Why should we hire you? Etc. Do you have plans for higher studies? Do you have any job location preference? What are your long term plans? Why should we hire you? Etc. After that, she explained to me everything regarding the CTC breakup, benefits, and perks of the company, my job role description, and the technologies that they are working on. She also talked about future opportunities and work culture in AthenaHealth. Then she asked me “Do you have any questions”? I asked some questions related to the work culture and challenges faced by the company during the COVID-19 pandemic. She was very kind and professional and gave a very positive response to all my questions. One should always go through the website or LinkedIn account of a company and should gather information about the company’s vision, working, products, etc. before going for an HR interview. One should always prepare himself before going for this round and should have a justified reason/story for each and every answer he gives. Announcement of Final Selected Students: Platform was Microsoft Team. Around 19:00, All the final selected students received a Microsoft Team Meeting Link. They selected 6 students, and I was one of them :-)). The meeting was very professional, the full recruiting team was there, and they were congratulating all the selected students. The vibe was very pleasant and the environment was friendly. Overall it was a very nice experience and things went very smoothly and punctually. Important Note: One should start preparing for placements prior to the placement season begins and should mostly focus on Competitive Programming, Data Structures, and Algorithms if they are aiming for getting placed in any IT Giants. One should always brush up the concept of technical subjects such as DBMS, Operating System, Computer Networks, and OOPS. Basic aptitude and logical reasoning should be practiced. One can practice competitive programming on a platform such as GeeksforGeeks practice, InterviewBit, HackerRank, etc. Always stay confident and believe in yourself. All the best for all your future endeavors and happy coding. Athena-Health Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN Persistent Systems Interview Experience (Martian Program) Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Zoho Interview | Set 1 (On-Campus) Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1
[ { "code": null, "e": 25206, "s": 25178, "text": "\n15 Sep, 2020" }, { "code": null, "e": 25307, "s": 25206, "text": "College: M.S Ramaiah Institute of Technology, Bangalore Date: 26th August 2020 and 27th August 2020 " }, { "code": null, "e": 25764, "s": 25307, "text": "Athena Health is a USA based IT company with the vision is to create a thriving ecosystem that delivers accessible, high-quality, and sustainable healthcare for all. The Company has visited our college with a star package and for the designation of Associate Member of Technical Staff for development. There were a total of 433 students registered for this on-campus recruitment drive. Only final year bachelor students were allowed to sit for this drive. " }, { "code": null, "e": 25982, "s": 25764, "text": "Pre-Placement Talk: Like every other recruitment drive Athena health also conducted a virtual pre-placement talk which mainly focuses on the job description, Cost To Company, work culture, and vision of the company. " }, { "code": null, "e": 26081, "s": 25982, "text": "Round 1 (MCQ & Coding): This round held on HackerRank and time duration for this round was 90mins." }, { "code": null, "e": 26107, "s": 26081, "text": "First question: 50 marks " }, { "code": null, "e": 26133, "s": 26107, "text": "Second Question: 75 marks" }, { "code": null, "e": 26151, "s": 26133, "text": "Coding Questions:" }, { "code": null, "e": 27302, "s": 26151, "text": "The First Coding question of 50 marks was an easy level question that can be solved using multiple ways but due to time complexity constraint, one needs to solve this question in maximum 0(n) time complexity to pass all test cases. The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Example: Input: A[] = {100, 180, 260, 310, 40 ,535, 695} \nOutput: 865 \nExplanation: We can buy stock on day 0, and sell it on\n day 3 and again buying on day 4 and sell it \n on day 6, which will give us maximum profit.The Second Coding Question of 75 marks also has several ways to solve the question but I solved it using Hashing Data Structure.Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. and output the count of all the distinct pairs. Example: Input: N=5 \n M=5 \n X=9 \n A[] = {1, 2, 4, 5, 7} \n B[]={5, 6, 3, 4, 8} \nOutput: 3 \nExplanation: (1, 8), (4, 5), (5, 4) are the pairs which sum to 9." }, { "code": null, "e": 27950, "s": 27302, "text": "The First Coding question of 50 marks was an easy level question that can be solved using multiple ways but due to time complexity constraint, one needs to solve this question in maximum 0(n) time complexity to pass all test cases. The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Example: Input: A[] = {100, 180, 260, 310, 40 ,535, 695} \nOutput: 865 \nExplanation: We can buy stock on day 0, and sell it on\n day 3 and again buying on day 4 and sell it \n on day 6, which will give us maximum profit." }, { "code": null, "e": 28183, "s": 27950, "text": "The First Coding question of 50 marks was an easy level question that can be solved using multiple ways but due to time complexity constraint, one needs to solve this question in maximum 0(n) time complexity to pass all test cases. " }, { "code": null, "e": 28358, "s": 28183, "text": "The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. " }, { "code": null, "e": 28368, "s": 28358, "text": "Example: " }, { "code": null, "e": 28601, "s": 28368, "text": "Input: A[] = {100, 180, 260, 310, 40 ,535, 695} \nOutput: 865 \nExplanation: We can buy stock on day 0, and sell it on\n day 3 and again buying on day 4 and sell it \n on day 6, which will give us maximum profit." }, { "code": null, "e": 29105, "s": 28601, "text": "The Second Coding Question of 75 marks also has several ways to solve the question but I solved it using Hashing Data Structure.Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. and output the count of all the distinct pairs. Example: Input: N=5 \n M=5 \n X=9 \n A[] = {1, 2, 4, 5, 7} \n B[]={5, 6, 3, 4, 8} \nOutput: 3 \nExplanation: (1, 8), (4, 5), (5, 4) are the pairs which sum to 9." }, { "code": null, "e": 29234, "s": 29105, "text": "The Second Coding Question of 75 marks also has several ways to solve the question but I solved it using Hashing Data Structure." }, { "code": null, "e": 29431, "s": 29234, "text": "Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. and output the count of all the distinct pairs. " }, { "code": null, "e": 29441, "s": 29431, "text": "Example: " }, { "code": null, "e": 29612, "s": 29441, "text": "Input: N=5 \n M=5 \n X=9 \n A[] = {1, 2, 4, 5, 7} \n B[]={5, 6, 3, 4, 8} \nOutput: 3 \nExplanation: (1, 8), (4, 5), (5, 4) are the pairs which sum to 9." }, { "code": null, "e": 29691, "s": 29612, "text": " Around 50 Students out of 433 students were shortlisted for the next round. " }, { "code": null, "e": 30132, "s": 29691, "text": "Round 2 (Technical Interview): After the first round, all shortlisted candidates received a codepair meeting link on their registered email. The interview was virtual due to the COVID-19 pandemic and was conducted on codepair platform of HackerRank specially designed for virtual interviews. My interview was in the first batch of interview sessions because they call students after sorting them alphabetically on the basis of their name. " }, { "code": null, "e": 30327, "s": 30132, "text": "The interviewer was very friendly, asked me to introduce myself, asked me some questions related to my resume, and directly moved on to the technical aspect, some questions which he asked were: " }, { "code": null, "e": 30946, "s": 30327, "text": "What do you mean by database transaction and what is ACID properties? I explained it Which is your preferred programming language and why? I told JavaWhy do you like java and not C/C++? I told because I don’t like the concept of Pointers and in java, we don’t use pointers instead we use objects in java and I find myself more comfortable with objects.How objects removed the concept of pointers? I told everything about the objects and explain in properly.What is the difference between Abstract class and Interface in java? Explain External and Internal fragmentation occurs during the dynamic allocation of memory?" }, { "code": null, "e": 31032, "s": 30946, "text": "What do you mean by database transaction and what is ACID properties? I explained it " }, { "code": null, "e": 31099, "s": 31032, "text": "Which is your preferred programming language and why? I told Java" }, { "code": null, "e": 31302, "s": 31099, "text": "Why do you like java and not C/C++? I told because I don’t like the concept of Pointers and in java, we don’t use pointers instead we use objects in java and I find myself more comfortable with objects." }, { "code": null, "e": 31408, "s": 31302, "text": "How objects removed the concept of pointers? I told everything about the objects and explain in properly." }, { "code": null, "e": 31478, "s": 31408, "text": "What is the difference between Abstract class and Interface in java? " }, { "code": null, "e": 31570, "s": 31478, "text": "Explain External and Internal fragmentation occurs during the dynamic allocation of memory?" }, { "code": null, "e": 31656, "s": 31570, "text": "After this, he gave me a competitive programming question and asked me to solve it. " }, { "code": null, "e": 31834, "s": 31656, "text": "He asked me the same 75 marks question asked in the coding round with some minor changes and asked me to explain the algorithm and code the most optimized solution for the same." }, { "code": null, "e": 32078, "s": 31834, "text": "As codepair platform contains a whiteboard and java editor, I explained the algorithm verbally with the help of an example and code the same on the editor, and fortunately, it works and passes all the test cases of random input which he gave. " }, { "code": null, "e": 32422, "s": 32078, "text": "Consider a string S and text T. Output the smallest window in the string S having all characters of the text T. Both the string S and text T contains lowercase English alphabets.Example: Is the smallest substring in the given string S which contains every character of T. (ahtenahealth) Input: S = athenahealth \n T=nlt \nOutput:\"nahealt\" " }, { "code": null, "e": 32601, "s": 32422, "text": "Consider a string S and text T. Output the smallest window in the string S having all characters of the text T. Both the string S and text T contains lowercase English alphabets." }, { "code": null, "e": 32711, "s": 32601, "text": "Example: Is the smallest substring in the given string S which contains every character of T. (ahtenahealth) " }, { "code": null, "e": 32768, "s": 32711, "text": "Input: S = athenahealth \n T=nlt \nOutput:\"nahealt\" " }, { "code": null, "e": 32901, "s": 32768, "text": "PS: I had solved this question before more than once as it is a standard hashing question, so I was very confident and excited too " }, { "code": null, "e": 33221, "s": 32901, "text": "I told him there can be two approaches to solve this question the first one is traversing both S and T using two for loops and checking concurrently which will take 0(n2) time complexity, so I would like to go with a more efficient method using hashing data structure which I guess would take 0(nlogn) time complexity. " }, { "code": null, "e": 33575, "s": 33221, "text": "He asked me to explain the algorithm on the whiteboard , as soon as I explained the algorithm he did some minor changes like added duplicates characters in T and then asked for my approach and code. fortunately, I got my code correct and it worked for the random input he gave. (The interviewer was very friendly and helping me while I was typing code)." }, { "code": null, "e": 33762, "s": 33578, "text": "After that, he wanted to check my logical reasoning and gave me a mathematical series and asked me to find the general mathematical pattern and code the same on the editor using java." }, { "code": null, "e": 33840, "s": 33762, "text": "While I was coding he asked me, in java why do we write the main function as " }, { "code": null, "e": 33879, "s": 33840, "text": "public static void main(String args[])" }, { "code": null, "e": 34108, "s": 33879, "text": " Then he asked me “do you have any questions?”, I asked him some questions related to Athenahealth, job description and things on which I should work, he was very cooperative and gave a very positive reply to all the questions. " }, { "code": null, "e": 34341, "s": 34108, "text": "NOTE: Interviewer always focuses on the problem-solving approach of an interviewee, they also give hints and help you in solving the problem with appropriate algorithms, just don’t fake yourself an interview and don’t make excuses. " }, { "code": null, "e": 34569, "s": 34341, "text": "Around 21:00, all the shortlisted students got a Microsoft Team meeting link on their registered email for Managerial Round which was conducted the very next day. They Shortlisted around 15 students for the Managerial round. " }, { "code": null, "e": 34960, "s": 34569, "text": "Round 3 (Managerial Round): Managerial Round is conducted to make the decision of recruiting a person more rigid and perfect, All the students who are shortlisted till this round are a capable and good fit for the job profile. In this round, the interviewer will probably have some feedback for you. This round of mine started with the standard interview question “Tell me about Yourself”? " }, { "code": null, "e": 35178, "s": 34960, "text": "This is the basic format for an IT fresher to answer this question with confidence and create a good impression on the interviewer. (One can also mention their CGPA in this answer but it depends on individual choice) " }, { "code": null, "e": 35243, "s": 35178, "text": "Basic format to answer Tell me about yourself (for IT freshers)" }, { "code": null, "e": 35344, "s": 35243, "text": "Moving on, He went through my projects mentioned in my resume and asked me to explain my project’s " }, { "code": null, "e": 35704, "s": 35344, "text": "ObjectiveTechnologies and libraries used.Challenges faced. Rectification and solution to those challenges.The outcome of the project and future endeavors of this project.A number of members in my team and what was my contribution to the project.How did we manage to work as a team during this pandemic for this project as all of us were working from our home?" }, { "code": null, "e": 35714, "s": 35704, "text": "Objective" }, { "code": null, "e": 35747, "s": 35714, "text": "Technologies and libraries used." }, { "code": null, "e": 35766, "s": 35747, "text": "Challenges faced. " }, { "code": null, "e": 35814, "s": 35766, "text": "Rectification and solution to those challenges." }, { "code": null, "e": 35879, "s": 35814, "text": "The outcome of the project and future endeavors of this project." }, { "code": null, "e": 35955, "s": 35879, "text": "A number of members in my team and what was my contribution to the project." }, { "code": null, "e": 36070, "s": 35955, "text": "How did we manage to work as a team during this pandemic for this project as all of us were working from our home?" }, { "code": null, "e": 36228, "s": 36070, "text": "He asked me some normal technical questions related to the database and connections of the project in between while I was explaining above mentioned points. " }, { "code": null, "e": 36612, "s": 36228, "text": "After that, He again went through my resume and asked me about the Entrepreneurship Development Center (E-cell) of our college as I was the core member of the club, He also asked questions regarding the work we do, events we organize and how do we work as a team , just after that he gave me a situation related to management, teamwork and asked me what I will do in that situation. " }, { "code": null, "e": 36659, "s": 36612, "text": "Then he asked me “Do you have any questions”? " }, { "code": null, "e": 36993, "s": 36659, "text": "I asked him some questions related to the products of Athena health and the technologies used to create those products, I also asked him regarding the job role and also gave one suggestion for the products of Athenahealth. He replied to all the answers in a very polite and positive manner and gave feedback for my project as well. " }, { "code": null, "e": 37115, "s": 36993, "text": "In Managerial Round, They had also asked puzzles to some of my friends but fortunately, he did not ask any puzzle to me " }, { "code": null, "e": 37412, "s": 37115, "text": "Note: Before going for this round, go through your projects and all its technical aspects, one should know everything about the things they are mentioning in their resume because the interviewer can ask anything but not beyond your resume. Prepare well and communicate with confidence and smile. " }, { "code": null, "e": 37536, "s": 37412, "text": "After around 35 minutes of my Managerial Round, I received one more Microsoft Team meeting link for HR Round on my email. " }, { "code": null, "e": 37847, "s": 37536, "text": "Round 4 (HR Round): Every company conducts an HR Round to judge your personality, behavior, your weakness, your strength, your background, your capability to handle the role and to make sure that you are the right fit for the job. The HR Round is usually the last round in the recruitment process of a company." }, { "code": null, "e": 38076, "s": 37847, "text": "This round of mine started with the question “What do you know about Athenahealth and its working ?” I started with the vision of the company and then mentioned some of its products and told everything I knew about the company. " }, { "code": null, "e": 38309, "s": 38076, "text": "After that, she went through my resume and asked lots of questions related to my education, my family, my certificates, my internships, my extracurricular activities, and skills, etc. Some most important questions HR asked me were: " }, { "code": null, "e": 38445, "s": 38309, "text": "Do you have plans for higher studies?Do you have any job location preference?What are your long term plans?Why should we hire you? Etc." }, { "code": null, "e": 38483, "s": 38445, "text": "Do you have plans for higher studies?" }, { "code": null, "e": 38524, "s": 38483, "text": "Do you have any job location preference?" }, { "code": null, "e": 38555, "s": 38524, "text": "What are your long term plans?" }, { "code": null, "e": 38584, "s": 38555, "text": "Why should we hire you? Etc." }, { "code": null, "e": 38840, "s": 38584, "text": "After that, she explained to me everything regarding the CTC breakup, benefits, and perks of the company, my job role description, and the technologies that they are working on. She also talked about future opportunities and work culture in AthenaHealth. " }, { "code": null, "e": 39096, "s": 38840, "text": "Then she asked me “Do you have any questions”? I asked some questions related to the work culture and challenges faced by the company during the COVID-19 pandemic. She was very kind and professional and gave a very positive response to all my questions. " }, { "code": null, "e": 39286, "s": 39096, "text": "One should always go through the website or LinkedIn account of a company and should gather information about the company’s vision, working, products, etc. before going for an HR interview." }, { "code": null, "e": 39425, "s": 39286, "text": "One should always prepare himself before going for this round and should have a justified reason/story for each and every answer he gives." }, { "code": null, "e": 39636, "s": 39425, "text": "Announcement of Final Selected Students: Platform was Microsoft Team. Around 19:00, All the final selected students received a Microsoft Team Meeting Link. They selected 6 students, and I was one of them :-)). " }, { "code": null, "e": 39910, "s": 39636, "text": "The meeting was very professional, the full recruiting team was there, and they were congratulating all the selected students. The vibe was very pleasant and the environment was friendly. Overall it was a very nice experience and things went very smoothly and punctually. " }, { "code": null, "e": 39926, "s": 39910, "text": "Important Note:" }, { "code": null, "e": 40145, "s": 39926, "text": "One should start preparing for placements prior to the placement season begins and should mostly focus on Competitive Programming, Data Structures, and Algorithms if they are aiming for getting placed in any IT Giants." }, { "code": null, "e": 40267, "s": 40145, "text": "One should always brush up the concept of technical subjects such as DBMS, Operating System, Computer Networks, and OOPS." }, { "code": null, "e": 40325, "s": 40267, "text": "Basic aptitude and logical reasoning should be practiced." }, { "code": null, "e": 40443, "s": 40325, "text": "One can practice competitive programming on a platform such as GeeksforGeeks practice, InterviewBit, HackerRank, etc." }, { "code": null, "e": 40490, "s": 40443, "text": "Always stay confident and believe in yourself." }, { "code": null, "e": 40551, "s": 40490, "text": "All the best for all your future endeavors and happy coding." }, { "code": null, "e": 40565, "s": 40551, "text": "Athena-Health" }, { "code": null, "e": 40575, "s": 40565, "text": "Marketing" }, { "code": null, "e": 40585, "s": 40575, "text": "On-Campus" }, { "code": null, "e": 40607, "s": 40585, "text": "Interview Experiences" }, { "code": null, "e": 40705, "s": 40607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40755, "s": 40705, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 40814, "s": 40755, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 40852, "s": 40814, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 40888, "s": 40852, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 40946, "s": 40888, "text": "Persistent Systems Interview Experience (Martian Program)" }, { "code": null, "e": 40992, "s": 40946, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 41057, "s": 40992, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" }, { "code": null, "e": 41092, "s": 41057, "text": "Zoho Interview | Set 1 (On-Campus)" }, { "code": null, "e": 41142, "s": 41092, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" } ]
Comparator Interface in Java with Examples - GeeksforGeeks
21 Dec, 2021 A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2. Syntax: public int compare(Object obj1, Object obj2): Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name, address, DOB, etc, and we need to sort the array based on Roll no or name? Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll No. and Name. Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else. Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator. public void sort(List list, ComparatorClass c) To sort a given List, ComparatorClass must implement a Comparator interface. Internally the Sort method does call Compare method of the classes it is sorting. To compare two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than, equal, or greater to the other. It uses this result to then determine if they should be swapped for their sort. Example Java // Java Program to Demonstrate Working of// Comparator Interface // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// A class to represent a Studentclass Student { // Attributes of a student int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current instance itself this.rollno = rollno; this.name = name; this.address = address; } // Method of Student class // To print student details in main() public String toString() { // Returning attributes of Student return this.rollno + " " + this.name + " " + this.address; }} // Class 2// Helper class implementing Comparator interfaceclass Sortbyroll implements Comparator<Student> { // Method // Sorting in ascending order of roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Helper class implementing Comparator interfaceclass Sortbyname implements Comparator<Student> { // Method // Sorting in ascending order of name public int compare(Student a, Student b) { return a.name.compareTo(b.name); }} // Class 4// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of Student type ArrayList<Student> ar = new ArrayList<Student>(); // Adding entries in above List // using add() method ar.add(new Student(111, "Mayank", "london")); ar.add(new Student(131, "Anshul", "nyc")); ar.add(new Student(121, "Solanki", "jaipur")); ar.add(new Student(101, "Aggarwal", "Hongkong")); // Display message on console for better readability System.out.println("Unsorted"); // Iterating over entries to print them for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); // Sorting student entries by roll number Collections.sort(ar, new Sortbyroll()); // Display message on console for better readability System.out.println("\nSorted by rollno"); // Again iterating over entries to print them for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); // Sorting student entries by name Collections.sort(ar, new Sortbyname()); // Display message on console for better readability System.out.println("\nSorted by name"); // // Again iterating over entries to print them for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); }} Unsorted 111 Mayank london 131 Anshul nyc 121 Solanki jaipur 101 Aggarwal Hongkong Sorted by rollno 101 Aggarwal Hongkong 111 Mayank london 121 Solanki jaipur 131 Anshul nyc Sorted by name 101 Aggarwal Hongkong 131 Anshul nyc 111 Mayank london 121 Solanki jaipur By changing the return value inside the compare method, you can sort in any order that you wish to, for example: For descending order just change the positions of ‘a’ and ‘b’ in the above compare method. In the previous example, we have discussed how to sort the list of objects on the basis of a single field using Comparable and Comparator interface But, what if we have a requirement to sort ArrayList objects in accordance with more than one field like firstly, sort according to the student name and secondly, sort according to student age. Example Java // Java Program to Demonstrate Working of// Comparator Interface Via More than One Field // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Iterator;import java.util.List; // Class 1// Helper class representing a Studentclass Student { // Attributes of student String Name; int Age; // Parameterized constructor public Student(String Name, Integer Age) { // This keyword refers to current instance itself this.Name = Name; this.Age = Age; } // Getter setter methods public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public Integer getAge() { return Age; } public void setAge(Integer Age) { this.Age = Age; } // Method // Overriding toString() method @Override public String toString() { return "Customer{" + "Name=" + Name + ", Age=" + Age + '}'; } // Class 2 // Helper class implementing Comparator interface static class CustomerSortingComparator implements Comparator<Student> { // Method 1 // To compare customers @Override public int compare(Student customer1, Student customer2) { // Comparing customers int NameCompare = customer1.getName().compareTo( customer2.getName()); int AgeCompare = customer1.getAge().compareTo( customer2.getAge()); // 2nd level comparison return (NameCompare == 0) ? AgeCompare : NameCompare; } } // Method 2 // Main driver method public static void main(String[] args) { // Create an empty ArrayList // to store Student List<Student> al = new ArrayList<>(); // Create customer objects // using constructor initialization Student obj1 = new Student("Ajay", 27); Student obj2 = new Student("Sneha", 23); Student obj3 = new Student("Simran", 37); Student obj4 = new Student("Ajay", 22); Student obj5 = new Student("Ajay", 29); Student obj6 = new Student("Sneha", 22); // Adding customer objects to ArrayList // using add() method al.add(obj1); al.add(obj2); al.add(obj3); al.add(obj4); al.add(obj5); al.add(obj6); // Iterating using Iterator // before Sorting ArrayList Iterator<Student> custIterator = al.iterator(); // Display message System.out.println("Before Sorting:\n"); // Holds true till there is single element // remaining in List while (custIterator.hasNext()) { // Iterating using next() method System.out.println(custIterator.next()); } // Sorting using sort method of Collections class Collections.sort(al, new CustomerSortingComparator()); // Display message only System.out.println("\n\nAfter Sorting:\n"); // Iterating using enhanced for-loop // after Sorting ArrayList for (Student customer : al) { System.out.println(customer); } }} Before Sorting: Customer{Name=Ajay, Age=27} Customer{Name=Sneha, Age=23} Customer{Name=Simran, Age=37} Customer{Name=Ajay, Age=22} Customer{Name=Ajay, Age=29} Customer{Name=Sneha, Age=22} After Sorting: Customer{Name=Ajay, Age=22} Customer{Name=Ajay, Age=27} Customer{Name=Ajay, Age=29} Customer{Name=Simran, Age=37} Customer{Name=Sneha, Age=22} Customer{Name=Sneha, Age=23} This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji gfg_user deepam vaibhavchotani001 amit98 aviroopbasu2012 sumitgumber28 simranarora5sos Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java How to add an element to an Array in Java?
[ { "code": null, "e": 28952, "s": 28924, "text": "\n21 Dec, 2021" }, { "code": null, "e": 29147, "s": 28952, "text": "A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. Following function compare obj1 with obj2." }, { "code": null, "e": 29156, "s": 29147, "text": "Syntax: " }, { "code": null, "e": 29202, "s": 29156, "text": "public int compare(Object obj1, Object obj2):" }, { "code": null, "e": 29373, "s": 29202, "text": "Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name, address, DOB, etc, and we need to sort the array based on Roll no or name?" }, { "code": null, "e": 29581, "s": 29373, "text": "Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll No. and Name." }, { "code": null, "e": 29959, "s": 29581, "text": "Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else." }, { "code": null, "e": 30077, "s": 29959, "text": "Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator. " }, { "code": null, "e": 30124, "s": 30077, "text": "public void sort(List list, ComparatorClass c)" }, { "code": null, "e": 30201, "s": 30124, "text": "To sort a given List, ComparatorClass must implement a Comparator interface." }, { "code": null, "e": 30510, "s": 30201, "text": "Internally the Sort method does call Compare method of the classes it is sorting. To compare two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than, equal, or greater to the other. It uses this result to then determine if they should be swapped for their sort." }, { "code": null, "e": 30518, "s": 30510, "text": "Example" }, { "code": null, "e": 30523, "s": 30518, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of// Comparator Interface // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Class 1// A class to represent a Studentclass Student { // Attributes of a student int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current instance itself this.rollno = rollno; this.name = name; this.address = address; } // Method of Student class // To print student details in main() public String toString() { // Returning attributes of Student return this.rollno + \" \" + this.name + \" \" + this.address; }} // Class 2// Helper class implementing Comparator interfaceclass Sortbyroll implements Comparator<Student> { // Method // Sorting in ascending order of roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Helper class implementing Comparator interfaceclass Sortbyname implements Comparator<Student> { // Method // Sorting in ascending order of name public int compare(Student a, Student b) { return a.name.compareTo(b.name); }} // Class 4// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of Student type ArrayList<Student> ar = new ArrayList<Student>(); // Adding entries in above List // using add() method ar.add(new Student(111, \"Mayank\", \"london\")); ar.add(new Student(131, \"Anshul\", \"nyc\")); ar.add(new Student(121, \"Solanki\", \"jaipur\")); ar.add(new Student(101, \"Aggarwal\", \"Hongkong\")); // Display message on console for better readability System.out.println(\"Unsorted\"); // Iterating over entries to print them for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); // Sorting student entries by roll number Collections.sort(ar, new Sortbyroll()); // Display message on console for better readability System.out.println(\"\\nSorted by rollno\"); // Again iterating over entries to print them for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); // Sorting student entries by name Collections.sort(ar, new Sortbyname()); // Display message on console for better readability System.out.println(\"\\nSorted by name\"); // // Again iterating over entries to print them for (int i = 0; i < ar.size(); i++) System.out.println(ar.get(i)); }}", "e": 33215, "s": 30523, "text": null }, { "code": null, "e": 33480, "s": 33215, "text": "Unsorted\n111 Mayank london\n131 Anshul nyc\n121 Solanki jaipur\n101 Aggarwal Hongkong\n\nSorted by rollno\n101 Aggarwal Hongkong\n111 Mayank london\n121 Solanki jaipur\n131 Anshul nyc\n\nSorted by name\n101 Aggarwal Hongkong\n131 Anshul nyc\n111 Mayank london\n121 Solanki jaipur" }, { "code": null, "e": 33684, "s": 33480, "text": "By changing the return value inside the compare method, you can sort in any order that you wish to, for example: For descending order just change the positions of ‘a’ and ‘b’ in the above compare method." }, { "code": null, "e": 34026, "s": 33684, "text": "In the previous example, we have discussed how to sort the list of objects on the basis of a single field using Comparable and Comparator interface But, what if we have a requirement to sort ArrayList objects in accordance with more than one field like firstly, sort according to the student name and secondly, sort according to student age." }, { "code": null, "e": 34034, "s": 34026, "text": "Example" }, { "code": null, "e": 34039, "s": 34034, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of// Comparator Interface Via More than One Field // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Iterator;import java.util.List; // Class 1// Helper class representing a Studentclass Student { // Attributes of student String Name; int Age; // Parameterized constructor public Student(String Name, Integer Age) { // This keyword refers to current instance itself this.Name = Name; this.Age = Age; } // Getter setter methods public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public Integer getAge() { return Age; } public void setAge(Integer Age) { this.Age = Age; } // Method // Overriding toString() method @Override public String toString() { return \"Customer{\" + \"Name=\" + Name + \", Age=\" + Age + '}'; } // Class 2 // Helper class implementing Comparator interface static class CustomerSortingComparator implements Comparator<Student> { // Method 1 // To compare customers @Override public int compare(Student customer1, Student customer2) { // Comparing customers int NameCompare = customer1.getName().compareTo( customer2.getName()); int AgeCompare = customer1.getAge().compareTo( customer2.getAge()); // 2nd level comparison return (NameCompare == 0) ? AgeCompare : NameCompare; } } // Method 2 // Main driver method public static void main(String[] args) { // Create an empty ArrayList // to store Student List<Student> al = new ArrayList<>(); // Create customer objects // using constructor initialization Student obj1 = new Student(\"Ajay\", 27); Student obj2 = new Student(\"Sneha\", 23); Student obj3 = new Student(\"Simran\", 37); Student obj4 = new Student(\"Ajay\", 22); Student obj5 = new Student(\"Ajay\", 29); Student obj6 = new Student(\"Sneha\", 22); // Adding customer objects to ArrayList // using add() method al.add(obj1); al.add(obj2); al.add(obj3); al.add(obj4); al.add(obj5); al.add(obj6); // Iterating using Iterator // before Sorting ArrayList Iterator<Student> custIterator = al.iterator(); // Display message System.out.println(\"Before Sorting:\\n\"); // Holds true till there is single element // remaining in List while (custIterator.hasNext()) { // Iterating using next() method System.out.println(custIterator.next()); } // Sorting using sort method of Collections class Collections.sort(al, new CustomerSortingComparator()); // Display message only System.out.println(\"\\n\\nAfter Sorting:\\n\"); // Iterating using enhanced for-loop // after Sorting ArrayList for (Student customer : al) { System.out.println(customer); } }}", "e": 37296, "s": 34039, "text": null }, { "code": null, "e": 37675, "s": 37296, "text": "Before Sorting:\n\nCustomer{Name=Ajay, Age=27}\nCustomer{Name=Sneha, Age=23}\nCustomer{Name=Simran, Age=37}\nCustomer{Name=Ajay, Age=22}\nCustomer{Name=Ajay, Age=29}\nCustomer{Name=Sneha, Age=22}\n\n\nAfter Sorting:\n\nCustomer{Name=Ajay, Age=22}\nCustomer{Name=Ajay, Age=27}\nCustomer{Name=Ajay, Age=29}\nCustomer{Name=Simran, Age=37}\nCustomer{Name=Sneha, Age=22}\nCustomer{Name=Sneha, Age=23}" }, { "code": null, "e": 38070, "s": 37675, "text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38080, "s": 38070, "text": "Rajput-Ji" }, { "code": null, "e": 38089, "s": 38080, "text": "gfg_user" }, { "code": null, "e": 38096, "s": 38089, "text": "deepam" }, { "code": null, "e": 38114, "s": 38096, "text": "vaibhavchotani001" }, { "code": null, "e": 38121, "s": 38114, "text": "amit98" }, { "code": null, "e": 38137, "s": 38121, "text": "aviroopbasu2012" }, { "code": null, "e": 38151, "s": 38137, "text": "sumitgumber28" }, { "code": null, "e": 38167, "s": 38151, "text": "simranarora5sos" }, { "code": null, "e": 38172, "s": 38167, "text": "Java" }, { "code": null, "e": 38177, "s": 38172, "text": "Java" }, { "code": null, "e": 38275, "s": 38177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38319, "s": 38275, "text": "Split() String method in Java with examples" }, { "code": null, "e": 38355, "s": 38319, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 38380, "s": 38355, "text": "Reverse a string in Java" }, { "code": null, "e": 38412, "s": 38380, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 38443, "s": 38412, "text": "How to iterate any Map in Java" }, { "code": null, "e": 38458, "s": 38443, "text": "Stream In Java" }, { "code": null, "e": 38482, "s": 38458, "text": "Singleton Class in Java" }, { "code": null, "e": 38510, "s": 38482, "text": "Initializing a List in Java" }, { "code": null, "e": 38556, "s": 38510, "text": "Different ways of Reading a text file in Java" } ]
Python - Move a column to the first position in Pandas DataFrame?
Use pop() to pop the column and insert it using the insert() methodi.e. moving a column. At first, create a DataFrame with 3 columns − dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } ) Move column "Roll Number" to 1st position by first popping the column out − shiftPos = dataFrame.pop("Roll Number") Insert column on the 1st position − dataFrame.insert(0, "Roll Number", shiftPos) Following is the code − import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } ) print"DataFrame ...\n",dataFrame # move column "Roll Number" to 1st position shiftPos = dataFrame.pop("Roll Number") # insert column on the 1st position dataFrame.insert(0, "Roll Number", shiftPos) print"\nUpdated DataFrame after moving a column to the first position...\n",dataFrame This will produce the following output − DataFrame ... Result Roll Number Student 0 Pass 5 Jack 1 Fail 10 Robin 2 Pass 3 Ted 3 Fail 8 Marc 4 Pass 2 Scarlett 5 Pass 9 Kat 6 Pass 6 John Updated DataFrame after moving a column to the first position... Roll Number Result Student 0 5 Pass Jack 1 10 Fail Robin 2 3 Pass Ted 3 8 Fail Marc 4 2 Pass Scarlett 5 9 Pass Kat 6 6 Pass John
[ { "code": null, "e": 1197, "s": 1062, "text": "Use pop() to pop the column and insert it using the insert() methodi.e. moving a column. At first, create a DataFrame with 3 columns −" }, { "code": null, "e": 1420, "s": 1197, "text": "dataFrame = pd.DataFrame(\n {\n \"Student\": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],\"Result\": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],\"Roll Number\": [ 5, 10, 3, 8, 2, 9, 6]\n }\n)\n\n" }, { "code": null, "e": 1496, "s": 1420, "text": "Move column \"Roll Number\" to 1st position by first popping the column out −" }, { "code": null, "e": 1536, "s": 1496, "text": "shiftPos = dataFrame.pop(\"Roll Number\")" }, { "code": null, "e": 1572, "s": 1536, "text": "Insert column on the 1st position −" }, { "code": null, "e": 1618, "s": 1572, "text": "dataFrame.insert(0, \"Roll Number\", shiftPos)\n" }, { "code": null, "e": 1642, "s": 1618, "text": "Following is the code −" }, { "code": null, "e": 2191, "s": 1642, "text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Student\": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],\"Result\": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],\"Roll Number\": [ 5, 10, 3, 8, 2, 9, 6]\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# move column \"Roll Number\" to 1st position\nshiftPos = dataFrame.pop(\"Roll Number\")\n\n# insert column on the 1st position\ndataFrame.insert(0, \"Roll Number\", shiftPos)\n\nprint\"\\nUpdated DataFrame after moving a column to the first position...\\n\",dataFrame" }, { "code": null, "e": 2232, "s": 2191, "text": "This will produce the following output −" }, { "code": null, "e": 2856, "s": 2232, "text": "DataFrame ...\n Result Roll Number Student\n0 Pass 5 Jack\n1 Fail 10 Robin\n2 Pass 3 Ted\n3 Fail 8 Marc\n4 Pass 2 Scarlett\n5 Pass 9 Kat\n6 Pass 6 John\n\nUpdated DataFrame after moving a column to the first position...\n Roll Number Result Student\n0 5 Pass Jack\n1 10 Fail Robin\n2 3 Pass Ted\n3 8 Fail Marc\n4 2 Pass Scarlett\n5 9 Pass Kat\n6 6 Pass John" } ]
How to use shapiro wilk test to check normality of an R data frame column?
To apply shapiro wilk test for normality on vectors, we just simply name the vector inside shapiro.test function but if we want to do the same for an R data frame column then the column will have to specify the column in a proper way. For example, if the data frame name is df and the column name is x then the function will work as shapiro.test(df$x). Live Demo x1<-rnorm(1000,1.5) df1<-data.frame(x1) shapiro.test(df1$x1) Shapiro-Wilk normality test data: df1$x1 W = 0.99886, p-value = 0.792 Live Demo x2<-runif(1000,2,10) df2<-data.frame(x2) shapiro.test(df2$x2) Shapiro-Wilk normality test data: df2$x2 W = 0.9581, p-value = 2.562e-16 Live Demo x3<-rpois(4000,2) df3<-data.frame(x3) shapiro.test(df3$x3) Shapiro-Wilk normality test data: df3$x3 W = 0.91894, p-value < 2.2e-16 Live Demo x4<-rpois(4000,5) df4<-data.frame(x4) shapiro.test(df4$x4) Shapiro-Wilk normality test data: df4$x4 W = 0.97092, p-value < 2.2e-16 Live Demo x5<-sample(1:5,5000,replace=TRUE) df5<-data.frame(x5) shapiro.test(df5$x5) Shapiro-Wilk normality test data: df5$x5 W = 0.88902, p-value < 2.2e-16 Live Demo x6<-sample(1:10,5000,replace=TRUE) df6<-data.frame(x6) shapiro.test(df6$x6) Shapiro-Wilk normality test data: df6$x6 W = 0.93373, p-value < 2.2e-16 Live Demo x7<-sample(1:100,5000,replace=TRUE) df7<-data.frame(x7) shapiro.test(df7$x7) Shapiro-Wilk normality test data: df7$x7 W = 0.9556, p-value < 2.2e-16 Live Demo x8<-sample(2500:3500,5000,replace=TRUE) df8<-data.frame(x8) shapiro.test(df8$x8) Shapiro-Wilk normality test data: df8$x8 W = 0.95117, p-value < 2.2e-16 Live Demo x9<-rbinom(5000,10,0.5) df9<-data.frame(x9) hapiro.test(df9$x9) Shapiro-Wilk normality test data: df9$x9 W = 0.96629, p-value < 2.2e-16 Live Demo x10<-rbinom(5000,1000,0.5) df10<-data.frame(x10) shapiro.test(df10$x10) Shapiro-Wilk normality test data: df10$x10 W = 0.9993, p-value = 0.04748
[ { "code": null, "e": 1415, "s": 1062, "text": "To apply shapiro wilk test for normality on vectors, we just simply name the vector inside shapiro.test function but if we want to do the same for an R data frame column then the column will have to specify the column in a proper way. For example, if the data frame name is df and the column name is x then the function will work as shapiro.test(df$x)." }, { "code": null, "e": 1426, "s": 1415, "text": " Live Demo" }, { "code": null, "e": 1487, "s": 1426, "text": "x1<-rnorm(1000,1.5)\ndf1<-data.frame(x1)\nshapiro.test(df1$x1)" }, { "code": null, "e": 1560, "s": 1487, "text": " Shapiro-Wilk normality test\ndata: df1$x1\nW = 0.99886, p-value = 0.792" }, { "code": null, "e": 1571, "s": 1560, "text": " Live Demo" }, { "code": null, "e": 1633, "s": 1571, "text": "x2<-runif(1000,2,10)\ndf2<-data.frame(x2)\nshapiro.test(df2$x2)" }, { "code": null, "e": 1709, "s": 1633, "text": " Shapiro-Wilk normality test\ndata: df2$x2\nW = 0.9581, p-value = 2.562e-16" }, { "code": null, "e": 1720, "s": 1709, "text": " Live Demo" }, { "code": null, "e": 1779, "s": 1720, "text": "x3<-rpois(4000,2)\ndf3<-data.frame(x3)\nshapiro.test(df3$x3)" }, { "code": null, "e": 1854, "s": 1779, "text": " Shapiro-Wilk normality test\ndata: df3$x3\nW = 0.91894, p-value < 2.2e-16" }, { "code": null, "e": 1865, "s": 1854, "text": " Live Demo" }, { "code": null, "e": 1924, "s": 1865, "text": "x4<-rpois(4000,5)\ndf4<-data.frame(x4)\nshapiro.test(df4$x4)" }, { "code": null, "e": 1999, "s": 1924, "text": " Shapiro-Wilk normality test\ndata: df4$x4\nW = 0.97092, p-value < 2.2e-16" }, { "code": null, "e": 2010, "s": 1999, "text": " Live Demo" }, { "code": null, "e": 2085, "s": 2010, "text": "x5<-sample(1:5,5000,replace=TRUE)\ndf5<-data.frame(x5)\nshapiro.test(df5$x5)" }, { "code": null, "e": 2160, "s": 2085, "text": " Shapiro-Wilk normality test\ndata: df5$x5\nW = 0.88902, p-value < 2.2e-16" }, { "code": null, "e": 2171, "s": 2160, "text": " Live Demo" }, { "code": null, "e": 2247, "s": 2171, "text": "x6<-sample(1:10,5000,replace=TRUE)\ndf6<-data.frame(x6)\nshapiro.test(df6$x6)" }, { "code": null, "e": 2322, "s": 2247, "text": " Shapiro-Wilk normality test\ndata: df6$x6\nW = 0.93373, p-value < 2.2e-16" }, { "code": null, "e": 2333, "s": 2322, "text": " Live Demo" }, { "code": null, "e": 2410, "s": 2333, "text": "x7<-sample(1:100,5000,replace=TRUE)\ndf7<-data.frame(x7)\nshapiro.test(df7$x7)" }, { "code": null, "e": 2484, "s": 2410, "text": " Shapiro-Wilk normality test\ndata: df7$x7\nW = 0.9556, p-value < 2.2e-16" }, { "code": null, "e": 2495, "s": 2484, "text": " Live Demo" }, { "code": null, "e": 2576, "s": 2495, "text": "x8<-sample(2500:3500,5000,replace=TRUE)\ndf8<-data.frame(x8)\nshapiro.test(df8$x8)" }, { "code": null, "e": 2651, "s": 2576, "text": " Shapiro-Wilk normality test\ndata: df8$x8\nW = 0.95117, p-value < 2.2e-16" }, { "code": null, "e": 2662, "s": 2651, "text": " Live Demo" }, { "code": null, "e": 2726, "s": 2662, "text": "x9<-rbinom(5000,10,0.5)\ndf9<-data.frame(x9)\nhapiro.test(df9$x9)" }, { "code": null, "e": 2801, "s": 2726, "text": " Shapiro-Wilk normality test\ndata: df9$x9\nW = 0.96629, p-value < 2.2e-16" }, { "code": null, "e": 2812, "s": 2801, "text": " Live Demo" }, { "code": null, "e": 2884, "s": 2812, "text": "x10<-rbinom(5000,1000,0.5)\ndf10<-data.frame(x10)\nshapiro.test(df10$x10)" }, { "code": null, "e": 2960, "s": 2884, "text": " Shapiro-Wilk normality test\ndata: df10$x10\nW = 0.9993, p-value = 0.04748" } ]
Recursively remove all adjacent duplicates | Practice | GeeksforGeeks
Given a string s, remove all its adjacent duplicate characters recursively. Example 1: Input: S = "geeksforgeek" Output: "gksforgk" Explanation: g(ee)ksforg(ee)k -> gksforgk Example 2: Input: S = "abccbccba" Output: "" Explanation: ab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->""(empty string) Your Task: You don't need to read input or print anything. Your task is to complete the function rremove() which takes the string S as input parameter and returns the resultant string. Note: For some test cases, the resultant string would be an empty string. For that case, the function should return the empty string only. Expected Time Complexity: O(|S|) Expected Auxiliary Space: O(|S|) Constraints: 1<=|S|<=105 +1 shreyank3453 days ago my code: string res=""; int k=0; while(s[k]){ if(s[k]!=s[k+1]){ res.push_back(s[k]); ++k; } if(s[k+1] && s[k]==s[k+1]){ while(s[k+1] && s[k]==s[k+1]){ ++k; } ++k; } } if(res==s){ return res; } else{ return remove(res); } 0 vishaldasani4 days ago string remove(string s){ // code here int i=0,n=s.size(); string temp; while(i<n) { int j=i+1; while(s[i]==s[j]&&j<n) j++; if(j==i+1)temp+=s[i]; i=j; } if(s.size()==temp.size()) return temp; else return remove(temp); } 0 mohankumarit20014 days ago class Solution{ string rem(string &s){ string res = ""; int i=0,j=0; while(i<s.size()){ j=i+1; while(j<s.size() && s[i]==s[j])j++; if(i+1==j){ res.push_back(s[i]); i++; } else i=j; } if(s!=res)return rem(res); return res; } public: string remove(string &s){ // code here return rem(s); } }; +1 siddhant4583agarwalPremium4 days ago if(s.size()==0||s.size()==1){ return s; } string temp; if(s[0]!=s[1]){ temp.push_back(s[0]); } for(int i=1;i<s.size()-1;i++){ if(s[i]!=s[i+1] && s[i]!=s[i-1]){ temp.push_back(s[i]); } } if(s[s.size()-1]!=s[s.size()-2]){ temp.push_back(s[s.size()-1]); } // cout<<temp<<endl; if(temp==s){ return temp; } else{ return remove(temp); } 0 shalini21sirothiya4 days ago //c++ string remove(string s){ while(1){ string temp; int i=0;int n=s.length(); while(i<n){ int j=i+1; while(s[i]==s[j] && j<n){ j++; } if(j==i+1)temp+=s[i]; i=j; } if(s.size()==temp.size())break; s=temp; } return s; } 0 nikhilgoyalmp4 days ago Easy C++ solution Space Complexity O(1) Time complexity O(|S|) class Solution{public: string remove(string s) { int i,count=0; for(i=0;i<s.length();i++) { if(s[i]==s[i+1]) { int j=i; while(s[i+1]==s[i]) { i++; } s.erase(j,i+1-j); i=i-(i-j)-1; count++; } } if(count==0) {return s;} else {return remove(s);} }}; +1 yashchawla1164 days ago Simple To Understand And Easy To Implement. https://yashboss116.blogspot.com/2022/04/recursively-remove-all-adjacent.html Approach Explained With Complexities Mentioned. 0 gupta2411sumit4 days ago bool contains(string s) { for( int i = 1 ; i<s.length() ; i++) { if(s[i]==s[i-1]) { return true ; } } return false ; } string remove(string s){ // code here string ans = "" ; int i = 0 ; for( i = 0 ; i<s.length()-1 ; i++) { if(s[i] ==s[i+1]) { while(s[i]==s[i+1]) i++ ; } else{ ans += s[i] ; } } if(s[i]!=s[i+1]) { ans += s[i] ; ; } if(contains(ans)) { return remove(ans) ; } else{ return ans ; } // return ans ; }}; +1 niteshv7114 days ago c++ string ans; int len = s.length(); if(s[0] != s[1]) ans.push_back(s[0]); bool flag = 0; for(int i = 1; i < len; i++){ while(s[i] == s[i+1]){ flag = 1; i++; } if(i > 0 && s[i] != s[i-1]) ans.push_back(s[i]); } if(flag == 0) return ans; return remove(ans); 0 cyanglass4 days ago Simple Short & Straight Approach || Python handle the edge case of length 1 Iterate over the string and Form a new string when adjacent unique found keep check of any duplicate encountered, if yes, invoke recursion with new string if no duplicate found, return the new string def remove (self, S): if len(S)==1: return S news,flag="",False for i in range(0,len(S)-1): if S[i]!=S[i+1]: if (i>0 and S[i-1]!=S[i]) or i==0: news+=S[i] if i==len(S)-2: #when last char is unique news+=S[i+1] continue flag=True if flag: return self.remove(news) else: return news We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 315, "s": 238, "text": "Given a string s, remove all its adjacent duplicate characters recursively. " }, { "code": null, "e": 326, "s": 315, "text": "Example 1:" }, { "code": null, "e": 414, "s": 326, "text": "Input:\nS = \"geeksforgeek\"\nOutput: \"gksforgk\"\nExplanation: \ng(ee)ksforg(ee)k -> gksforgk" }, { "code": null, "e": 426, "s": 414, "text": "\nExample 2:" }, { "code": null, "e": 533, "s": 426, "text": "Input: \nS = \"abccbccba\"\nOutput: \"\"\nExplanation: \nab(cc)b(cc)ba->abbba->a(bbb)a->aa->(aa)->\"\"(empty string)" }, { "code": null, "e": 858, "s": 533, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function rremove() which takes the string S as input parameter and returns the resultant string.\nNote: For some test cases, the resultant string would be an empty string. For that case, the function should return the empty string only." }, { "code": null, "e": 925, "s": 858, "text": "\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)" }, { "code": null, "e": 951, "s": 925, "text": "\nConstraints:\n1<=|S|<=105" }, { "code": null, "e": 954, "s": 951, "text": "+1" }, { "code": null, "e": 976, "s": 954, "text": "shreyank3453 days ago" }, { "code": null, "e": 985, "s": 976, "text": "my code:" }, { "code": null, "e": 1383, "s": 985, "text": "string res=\"\"; int k=0; while(s[k]){ if(s[k]!=s[k+1]){ res.push_back(s[k]); ++k; } if(s[k+1] && s[k]==s[k+1]){ while(s[k+1] && s[k]==s[k+1]){ ++k; } ++k; } } if(res==s){ return res; } else{ return remove(res); }" }, { "code": null, "e": 1385, "s": 1383, "text": "0" }, { "code": null, "e": 1408, "s": 1385, "text": "vishaldasani4 days ago" }, { "code": null, "e": 1726, "s": 1408, "text": "string remove(string s){ // code here int i=0,n=s.size(); string temp; while(i<n) { int j=i+1; while(s[i]==s[j]&&j<n) j++; if(j==i+1)temp+=s[i]; i=j; } if(s.size()==temp.size()) return temp; else return remove(temp); }" }, { "code": null, "e": 1728, "s": 1726, "text": "0" }, { "code": null, "e": 1755, "s": 1728, "text": "mohankumarit20014 days ago" }, { "code": null, "e": 2218, "s": 1755, "text": "class Solution{\n string rem(string &s){\n string res = \"\";\n int i=0,j=0;\n while(i<s.size()){\n j=i+1;\n while(j<s.size() && s[i]==s[j])j++;\n if(i+1==j){\n res.push_back(s[i]);\n i++;\n }\n else i=j;\n }\n if(s!=res)return rem(res);\n return res;\n }\npublic:\n string remove(string &s){\n // code here\n return rem(s);\n }\n};" }, { "code": null, "e": 2221, "s": 2218, "text": "+1" }, { "code": null, "e": 2258, "s": 2221, "text": "siddhant4583agarwalPremium4 days ago" }, { "code": null, "e": 2288, "s": 2258, "text": "if(s.size()==0||s.size()==1){" }, { "code": null, "e": 2310, "s": 2288, "text": " return s;" }, { "code": null, "e": 2320, "s": 2310, "text": " }" }, { "code": null, "e": 2341, "s": 2320, "text": " string temp;" }, { "code": null, "e": 2365, "s": 2341, "text": " if(s[0]!=s[1]){" }, { "code": null, "e": 2399, "s": 2365, "text": " temp.push_back(s[0]);" }, { "code": null, "e": 2409, "s": 2399, "text": " }" }, { "code": null, "e": 2448, "s": 2409, "text": " for(int i=1;i<s.size()-1;i++){" }, { "code": null, "e": 2494, "s": 2448, "text": " if(s[i]!=s[i+1] && s[i]!=s[i-1]){" }, { "code": null, "e": 2532, "s": 2494, "text": " temp.push_back(s[i]);" }, { "code": null, "e": 2546, "s": 2532, "text": " }" }, { "code": null, "e": 2556, "s": 2546, "text": " }" }, { "code": null, "e": 2598, "s": 2556, "text": " if(s[s.size()-1]!=s[s.size()-2]){" }, { "code": null, "e": 2641, "s": 2598, "text": " temp.push_back(s[s.size()-1]);" }, { "code": null, "e": 2651, "s": 2641, "text": " }" }, { "code": null, "e": 2680, "s": 2651, "text": " // cout<<temp<<endl;" }, { "code": null, "e": 2701, "s": 2680, "text": " if(temp==s){" }, { "code": null, "e": 2726, "s": 2701, "text": " return temp;" }, { "code": null, "e": 2736, "s": 2726, "text": " }" }, { "code": null, "e": 2750, "s": 2736, "text": " else{" }, { "code": null, "e": 2783, "s": 2750, "text": " return remove(temp);" }, { "code": null, "e": 2793, "s": 2783, "text": " }" }, { "code": null, "e": 2795, "s": 2793, "text": "0" }, { "code": null, "e": 2824, "s": 2795, "text": "shalini21sirothiya4 days ago" }, { "code": null, "e": 2830, "s": 2824, "text": "//c++" }, { "code": null, "e": 3157, "s": 2830, "text": " string remove(string s){ while(1){ string temp; int i=0;int n=s.length(); while(i<n){ int j=i+1; while(s[i]==s[j] && j<n){ j++; } if(j==i+1)temp+=s[i]; i=j; } if(s.size()==temp.size())break; s=temp; } return s; }" }, { "code": null, "e": 3159, "s": 3157, "text": "0" }, { "code": null, "e": 3183, "s": 3159, "text": "nikhilgoyalmp4 days ago" }, { "code": null, "e": 3202, "s": 3183, "text": "Easy C++ solution " }, { "code": null, "e": 3224, "s": 3202, "text": "Space Complexity O(1)" }, { "code": null, "e": 3247, "s": 3224, "text": "Time complexity O(|S|)" }, { "code": null, "e": 3694, "s": 3247, "text": "class Solution{public: string remove(string s) { int i,count=0; for(i=0;i<s.length();i++) { if(s[i]==s[i+1]) { int j=i; while(s[i+1]==s[i]) { i++; } s.erase(j,i+1-j); i=i-(i-j)-1; count++; } } if(count==0) {return s;} else {return remove(s);} }};" }, { "code": null, "e": 3697, "s": 3694, "text": "+1" }, { "code": null, "e": 3721, "s": 3697, "text": "yashchawla1164 days ago" }, { "code": null, "e": 3765, "s": 3721, "text": "Simple To Understand And Easy To Implement." }, { "code": null, "e": 3845, "s": 3767, "text": "https://yashboss116.blogspot.com/2022/04/recursively-remove-all-adjacent.html" }, { "code": null, "e": 3895, "s": 3847, "text": "Approach Explained With Complexities Mentioned." }, { "code": null, "e": 3899, "s": 3897, "text": "0" }, { "code": null, "e": 3924, "s": 3899, "text": "gupta2411sumit4 days ago" }, { "code": null, "e": 4709, "s": 3924, "text": " bool contains(string s) { for( int i = 1 ; i<s.length() ; i++) { if(s[i]==s[i-1]) { return true ; } } return false ; } string remove(string s){ // code here string ans = \"\" ; int i = 0 ; for( i = 0 ; i<s.length()-1 ; i++) { if(s[i] ==s[i+1]) { while(s[i]==s[i+1]) i++ ; } else{ ans += s[i] ; } } if(s[i]!=s[i+1]) { ans += s[i] ; ; } if(contains(ans)) { return remove(ans) ; } else{ return ans ; } // return ans ; }};" }, { "code": null, "e": 4712, "s": 4709, "text": "+1" }, { "code": null, "e": 4733, "s": 4712, "text": "niteshv7114 days ago" }, { "code": null, "e": 5156, "s": 4733, "text": "c++ \nstring ans;\n int len = s.length();\n if(s[0] != s[1])\n ans.push_back(s[0]);\n bool flag = 0;\n for(int i = 1; i < len; i++){\n while(s[i] == s[i+1]){\n flag = 1;\n i++;\n }\n if(i > 0 && s[i] != s[i-1])\n ans.push_back(s[i]);\n }\n if(flag == 0)\n return ans;\n return remove(ans);" }, { "code": null, "e": 5158, "s": 5156, "text": "0" }, { "code": null, "e": 5178, "s": 5158, "text": "cyanglass4 days ago" }, { "code": null, "e": 5221, "s": 5178, "text": "Simple Short & Straight Approach || Python" }, { "code": null, "e": 5256, "s": 5223, "text": "handle the edge case of length 1" }, { "code": null, "e": 5329, "s": 5256, "text": "Iterate over the string and Form a new string when adjacent unique found" }, { "code": null, "e": 5411, "s": 5329, "text": "keep check of any duplicate encountered, if yes, invoke recursion with new string" }, { "code": null, "e": 5456, "s": 5411, "text": "if no duplicate found, return the new string" }, { "code": null, "e": 5887, "s": 5458, "text": "def remove (self, S):\n\t\tif len(S)==1:\n\t\t return S\n\t news,flag=\"\",False\n\t for i in range(0,len(S)-1):\n\t if S[i]!=S[i+1]:\n\t if (i>0 and S[i-1]!=S[i]) or i==0:\n\t news+=S[i]\n\t if i==len(S)-2: #when last char is unique\n\t news+=S[i+1]\n\t continue\n\t \n\t flag=True\n\t if flag:\n\t return self.remove(news)\n\t else:\n\t return news" }, { "code": null, "e": 6033, "s": 5887, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6069, "s": 6033, "text": " Login to access your submissions. " }, { "code": null, "e": 6079, "s": 6069, "text": "\nProblem\n" }, { "code": null, "e": 6089, "s": 6079, "text": "\nContest\n" }, { "code": null, "e": 6152, "s": 6089, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6300, "s": 6152, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6508, "s": 6300, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6614, "s": 6508, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What does colon ':' operator do in Python?
The : symbol is used for more than one purpose in Python As slice operator with sequence − The − operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice. Both operands are optional. If first operand is omitted, it is 0 by default. If second is omitted, it is set to end of sequence. >>> a=[1,2,3,4,5] >>> a[1:3] [2, 3] >>> a[:3] [1, 2, 3] >>> a[2:] [3, 4, 5] >>> s='computer' >>> s[:3] 'com' >>> s[3:6] 'put' The − symbol is also used to start an indent suite of statements in case of if, while, for, def and class statements if expr: stmt while expr: stmt1 stmt2 for x in sequence: stmt1 stmt2 def function1(): stmt1 stmt2
[ { "code": null, "e": 1119, "s": 1062, "text": "The : symbol is used for more than one purpose in Python" }, { "code": null, "e": 1153, "s": 1119, "text": "As slice operator with sequence −" }, { "code": null, "e": 1463, "s": 1153, "text": "The − operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice. Both operands are optional. If first operand is omitted, it is 0 by default. If second is omitted, it is set to end of sequence." }, { "code": null, "e": 1589, "s": 1463, "text": ">>> a=[1,2,3,4,5]\n>>> a[1:3]\n[2, 3]\n>>> a[:3]\n[1, 2, 3]\n>>> a[2:]\n[3, 4, 5]\n>>> s='computer'\n>>> s[:3]\n'com'\n>>> s[3:6]\n'put'" }, { "code": null, "e": 1706, "s": 1589, "text": "The − symbol is also used to start an indent suite of statements in case of if, while, for, def and class statements" }, { "code": null, "e": 1723, "s": 1706, "text": "if expr:\n stmt" }, { "code": null, "e": 1753, "s": 1723, "text": "while expr:\n stmt1\n stmt2" }, { "code": null, "e": 1790, "s": 1753, "text": "for x in sequence:\n stmt1\n stmt2" }, { "code": null, "e": 1826, "s": 1790, "text": "def function1():\n stmt1\n stmt2" } ]
Spiral Pattern - GeeksforGeeks
22 Apr, 2021 Given a number N, the task is to print the following pattern:- Examples: Input : N = 4 Output : 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 Input : N = 2 Output : 2 2 2 2 1 2 2 2 2 Approach 1: The common observation is that the square thus formed will be of size (2*N-1)x(2*N-1). Fill the first row and column, last row and column with N, and then gradually decrease N and fill the remaining rows and columns similarly. Decrease N every time after filling 2 rows and 2 columns. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to print the// spiral pattern#include <bits/stdc++.h>using namespace std; // Function to print the patternvoid pattern(int value){ // Declare a square matrix int row = 2 * value - 1; int column = 2 * value - 1; int arr[row][column]; int i, j, k; for (k = 0; k < value; k++) { // store the first row // from 1st column to last column j = k; while (j < column - k) { arr[k][j] = value - k; j++; } // store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // store the last row // from last column to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1][j] = value - k; j--; } // store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i][k] = value - k; i--; } } // print the pattern for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { cout << arr[i][j] << " "; } cout << endl; }} // Driver codeint main(){ int n = 5; pattern(n); return 0;} // Java program to print// the spiral patternclass GFG { // Function to print the pattern static void pattern(int value) { // Declare a square matrix int row = 2 * value - 1; int column = 2 * value - 1; int[][] arr = new int[row][column]; int i, j, k; for (k = 0; k < value; k++) { // store the first row // from 1st column to last column j = k; while (j < column - k) { arr[k][j] = value - k; j++; } // store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // store the last row // from last column // to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1][j] = value - k; j--; } // store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i][k] = value - k; i--; } } // print the pattern for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } // Driver code public static void main(String[] args) { int n = 5; pattern(n); }} // This code is contributed// by ChitraNayal # Python3 program to print# the spiral pattern # Function to print the patterndef pattern(value): # Declare a square matrix row = 2 * value - 1 column = 2 * value - 1 arr = [[0 for i in range(row)] for j in range (column)] for k in range( value): # store the first row # from 1st column to # last column j = k while (j < column - k): arr[k][j] = value - k j += 1 # store the last column # from top to bottom i = k + 1 while (i < row - k): arr[i][row - 1 - k] = value - k i += 1 # store the last row # from last column # to 1st column j = column - k - 2 while j >= k : arr[column - k - 1][j] = value - k j -= 1 # store the first column # from bottom to top i = row - k - 2 while i > k : arr[i][k] = value - k i -= 1 # print the pattern for i in range(row): for j in range(column): print(arr[i][j], end = " ") print() # Driver codeif __name__ == "__main__": n = 5 pattern(n) # This code is contributed# by ChitraNayal // C# program to print// the spiral patternusing System; class GFG { // Function to print the pattern static void pattern(int value) { // Declare a square matrix int row = 2 * value - 1; int column = 2 * value - 1; int[, ] arr = new int[row, column]; int i, j, k; for (k = 0; k < value; k++) { // store the first row // from 1st column to // last column j = k; while (j < column - k) { arr[k, j] = value - k; j++; } // store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i, row - 1 - k] = value - k; i++; } // store the last row // from last column // to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1, j] = value - k; j--; } // store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i, k] = value - k; i--; } } // print the pattern for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { Console.Write(arr[i, j] + " "); } Console.Write("\n"); } } // Driver code public static void Main() { int n = 5; pattern(n); }} // This code is contributed// by ChitraNayal <?php// PHP program to print// the spiral pattern // Function to print the patternfunction pattern($value){ // Declare a square matrix $row = 2 * $value - 1; $column = 2 * $value - 1; $arr = array(array()); for ($k = 0; $k < $value; $k++) { // store the first row // from 1st column to // last column $j = $k; while ($j < $column - $k) { $arr[$k][$j] = $value - $k; $j++; } // store the last column // from top to bottom $i = $k + 1; while ($i < $row - $k) { $arr[$i][$row - 1 - $k] = $value - $k; $i++; } // store the last row // from last column // to 1st column $j = $column - $k - 2; while ($j >= $k) { $arr[$column - $k - 1][$j] = $value - $k; $j--; } // store the first column // from bottom to top $i = $row - $k - 2; while ($i > $k) { $arr[$i][$k] = $value - $k; $i--; } } // print the pattern for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { echo $arr[$i][$j] . " "; } echo "\n"; }} // Driver code$n = 5;pattern($n); // This code is contributed// by ChitraNayal?> <script> // Javascript program to print the// spiral pattern // Function to print the patternfunction pattern(value){ // Declare a square matrix let row = 2 * value - 1; let column = 2 * value - 1; let arr = new Array(row); for(let i = 0; i < row; i++) { arr[i] = new Array(column); } let i, j, k; for(k = 0; k < value; k++) { // Store the first row // from 1st column to last column j = k; while (j < column - k) { arr[k][j] = value - k; j++; } // Store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // Store the last row // from last column to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1][j] = value - k; j--; } // Store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i][k] = value - k; i--; } } // Print the pattern for(i = 0; i < row; i++) { for(j = 0; j < column; j++) { document.write(arr[i][j] + " "); } document.write("<br>"); }} // Driver codelet n = 5; pattern(n); // This code is contributed by subham348 </script> 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 5 5 4 3 3 3 3 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 2 1 2 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 3 3 3 3 4 5 5 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 Approach 2: Starting the indexing from i = 1 and j = 1, it can be observed that every value of the required matrix will be max(abs(i – n), abs(j – n)) + 1. Below is the implementation of the above approach: C++14 C Java Python3 C# Javascript // C++ implementation of the approach#include <algorithm>#include <iostream>using namespace std; // Function to print the required patternvoid pattern(int n){ // Calculating boundary size int p = 2 * n - 1; for (int i = 1; i <= p; i++) { for (int j = 1; j <= p; j++) { // Printing the values cout << max(abs(i - n), abs(j - n)) + 1 << " "; } cout << endl; }} // Driver codeint main(){ int n = 5; pattern(n); return 0;}// This code is contributed by : Vivek kothari // C implementation of the approach#include <stdio.h>#include <stdlib.h> // Function Declarationint max(int, int); // Function to print the required patternvoid pattern(int n){ // Calculating boundary size int size = 2 * n - 1; for(int i = 1; i <= size; i++) { for(int j = 1; j <= size; j++) { // Printing the values printf("%d ", max(abs(i - n), abs(j - n)) + 1); } printf("\n"); }} // Function to return maximum valueint max(int val1, int val2){ if (val1 > val2) return val1; return val2;} // Driver codeint main(){ int n = 5; pattern(n); return 0;} // This code is contributed by Yuvaraj R // Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // Function to print the required patternpublic static void pattern(int n){ // Calculating boundary size int size = 2 * n - 1; for(int i = 1; i <= size; i++) { for(int j = 1; j <= size; j++) { // Printing the values System.out.print(Math.max( Math.abs(i - n), Math.abs(j - n)) + 1 + " "); } System.out.println(); }} // Driver codepublic static void main(String[] args){ int n = 5; pattern(n);}} // This code is contributed by Yuvaraj R # Python3 implementation of the approach # Function to print the required patterndef pattern(n): # Calculating boundary size p = 2 * n - 1 for i in range(1, p + 1): for j in range(1, p + 1): # Printing the values print(max(abs(i - n), abs(j - n)) + 1, " ", end="") print() # Driver coden = 5pattern(n) # This code is contributed by subhammahato348 // C# implementation of the approachusing System; class GFG{ // Function to print the required patternstatic void pattern(int n){ // Calculating boundary size int size = 2 * n - 1; for(int i = 1; i <= size; i++) { for(int j = 1; j <= size; j++) { // Printing the values Console.Write(Math.Max(Math.Abs(i - n), Math.Abs(j - n)) + 1 + " "); } Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 5; pattern(n);}} // This code is contributed by subhammahato348 <script> // Javascript implementation of the approach // Function to print the required patternfunction pattern(n){ // Calculating boundary size let p = 2 * n - 1; for (let i = 1; i <= p; i++) { for (let j = 1; j <= p; j++) { // Printing the values document.write((Math.max(Math.abs(i - n), Math.abs(j - n)) + 1) + " "); } document.write("<br>"); }} // Driver codelet n = 5; pattern(n); </script> 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 5 5 4 3 3 3 3 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 2 1 2 3 4 5 5 4 3 2 2 2 3 4 5 5 4 3 3 3 3 3 4 5 5 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 ukasp vivekkothari yuvaram11 subhammahato348 subham348 loop pattern-printing Matrix School Programming pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Unique paths in a Grid with Obstacles Check for possible path in 2D matrix A Boolean Matrix Question Mathematics | L U Decomposition of a System of Linear Equations Python program to add two Matrices Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 24531, "s": 24503, "text": "\n22 Apr, 2021" }, { "code": null, "e": 24594, "s": 24531, "text": "Given a number N, the task is to print the following pattern:-" }, { "code": null, "e": 24605, "s": 24594, "text": "Examples: " }, { "code": null, "e": 24840, "s": 24605, "text": "Input : N = 4\nOutput : 4 4 4 4 4 4 4\n 4 3 3 3 3 3 4\n 4 3 2 2 2 3 4\n 4 3 2 1 2 3 4\n 4 3 2 2 2 3 4\n 4 3 3 3 3 3 4\n 4 4 4 4 4 4 4\n\nInput : N = 2\nOutput : 2 2 2\n 2 1 2\n 2 2 2" }, { "code": null, "e": 25138, "s": 24840, "text": "Approach 1: The common observation is that the square thus formed will be of size (2*N-1)x(2*N-1). Fill the first row and column, last row and column with N, and then gradually decrease N and fill the remaining rows and columns similarly. Decrease N every time after filling 2 rows and 2 columns. " }, { "code": null, "e": 25190, "s": 25138, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25194, "s": 25190, "text": "C++" }, { "code": null, "e": 25199, "s": 25194, "text": "Java" }, { "code": null, "e": 25207, "s": 25199, "text": "Python3" }, { "code": null, "e": 25210, "s": 25207, "text": "C#" }, { "code": null, "e": 25214, "s": 25210, "text": "PHP" }, { "code": null, "e": 25225, "s": 25214, "text": "Javascript" }, { "code": "// C++ program to print the// spiral pattern#include <bits/stdc++.h>using namespace std; // Function to print the patternvoid pattern(int value){ // Declare a square matrix int row = 2 * value - 1; int column = 2 * value - 1; int arr[row][column]; int i, j, k; for (k = 0; k < value; k++) { // store the first row // from 1st column to last column j = k; while (j < column - k) { arr[k][j] = value - k; j++; } // store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // store the last row // from last column to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1][j] = value - k; j--; } // store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i][k] = value - k; i--; } } // print the pattern for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { cout << arr[i][j] << \" \"; } cout << endl; }} // Driver codeint main(){ int n = 5; pattern(n); return 0;}", "e": 26495, "s": 25225, "text": null }, { "code": "// Java program to print// the spiral patternclass GFG { // Function to print the pattern static void pattern(int value) { // Declare a square matrix int row = 2 * value - 1; int column = 2 * value - 1; int[][] arr = new int[row][column]; int i, j, k; for (k = 0; k < value; k++) { // store the first row // from 1st column to last column j = k; while (j < column - k) { arr[k][j] = value - k; j++; } // store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // store the last row // from last column // to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1][j] = value - k; j--; } // store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i][k] = value - k; i--; } } // print the pattern for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { System.out.print(arr[i][j] + \" \"); } System.out.println(); } } // Driver code public static void main(String[] args) { int n = 5; pattern(n); }} // This code is contributed// by ChitraNayal", "e": 28054, "s": 26495, "text": null }, { "code": "# Python3 program to print# the spiral pattern # Function to print the patterndef pattern(value): # Declare a square matrix row = 2 * value - 1 column = 2 * value - 1 arr = [[0 for i in range(row)] for j in range (column)] for k in range( value): # store the first row # from 1st column to # last column j = k while (j < column - k): arr[k][j] = value - k j += 1 # store the last column # from top to bottom i = k + 1 while (i < row - k): arr[i][row - 1 - k] = value - k i += 1 # store the last row # from last column # to 1st column j = column - k - 2 while j >= k : arr[column - k - 1][j] = value - k j -= 1 # store the first column # from bottom to top i = row - k - 2 while i > k : arr[i][k] = value - k i -= 1 # print the pattern for i in range(row): for j in range(column): print(arr[i][j], end = \" \") print() # Driver codeif __name__ == \"__main__\": n = 5 pattern(n) # This code is contributed# by ChitraNayal", "e": 29264, "s": 28054, "text": null }, { "code": "// C# program to print// the spiral patternusing System; class GFG { // Function to print the pattern static void pattern(int value) { // Declare a square matrix int row = 2 * value - 1; int column = 2 * value - 1; int[, ] arr = new int[row, column]; int i, j, k; for (k = 0; k < value; k++) { // store the first row // from 1st column to // last column j = k; while (j < column - k) { arr[k, j] = value - k; j++; } // store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i, row - 1 - k] = value - k; i++; } // store the last row // from last column // to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1, j] = value - k; j--; } // store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i, k] = value - k; i--; } } // print the pattern for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { Console.Write(arr[i, j] + \" \"); } Console.Write(\"\\n\"); } } // Driver code public static void Main() { int n = 5; pattern(n); }} // This code is contributed// by ChitraNayal", "e": 30833, "s": 29264, "text": null }, { "code": "<?php// PHP program to print// the spiral pattern // Function to print the patternfunction pattern($value){ // Declare a square matrix $row = 2 * $value - 1; $column = 2 * $value - 1; $arr = array(array()); for ($k = 0; $k < $value; $k++) { // store the first row // from 1st column to // last column $j = $k; while ($j < $column - $k) { $arr[$k][$j] = $value - $k; $j++; } // store the last column // from top to bottom $i = $k + 1; while ($i < $row - $k) { $arr[$i][$row - 1 - $k] = $value - $k; $i++; } // store the last row // from last column // to 1st column $j = $column - $k - 2; while ($j >= $k) { $arr[$column - $k - 1][$j] = $value - $k; $j--; } // store the first column // from bottom to top $i = $row - $k - 2; while ($i > $k) { $arr[$i][$k] = $value - $k; $i--; } } // print the pattern for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { echo $arr[$i][$j] . \" \"; } echo \"\\n\"; }} // Driver code$n = 5;pattern($n); // This code is contributed// by ChitraNayal?>", "e": 32172, "s": 30833, "text": null }, { "code": "<script> // Javascript program to print the// spiral pattern // Function to print the patternfunction pattern(value){ // Declare a square matrix let row = 2 * value - 1; let column = 2 * value - 1; let arr = new Array(row); for(let i = 0; i < row; i++) { arr[i] = new Array(column); } let i, j, k; for(k = 0; k < value; k++) { // Store the first row // from 1st column to last column j = k; while (j < column - k) { arr[k][j] = value - k; j++; } // Store the last column // from top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // Store the last row // from last column to 1st column j = column - k - 2; while (j >= k) { arr[column - k - 1][j] = value - k; j--; } // Store the first column // from bottom to top i = row - k - 2; while (i > k) { arr[i][k] = value - k; i--; } } // Print the pattern for(i = 0; i < row; i++) { for(j = 0; j < column; j++) { document.write(arr[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver codelet n = 5; pattern(n); // This code is contributed by subham348 </script>", "e": 33599, "s": 32172, "text": null }, { "code": null, "e": 33769, "s": 33599, "text": "5 5 5 5 5 5 5 5 5 \n5 4 4 4 4 4 4 4 5 \n5 4 3 3 3 3 3 4 5 \n5 4 3 2 2 2 3 4 5 \n5 4 3 2 1 2 3 4 5 \n5 4 3 2 2 2 3 4 5 \n5 4 3 3 3 3 3 4 5 \n5 4 4 4 4 4 4 4 5 \n5 5 5 5 5 5 5 5 5" }, { "code": null, "e": 33927, "s": 33771, "text": "Approach 2: Starting the indexing from i = 1 and j = 1, it can be observed that every value of the required matrix will be max(abs(i – n), abs(j – n)) + 1." }, { "code": null, "e": 33979, "s": 33927, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 33985, "s": 33979, "text": "C++14" }, { "code": null, "e": 33987, "s": 33985, "text": "C" }, { "code": null, "e": 33992, "s": 33987, "text": "Java" }, { "code": null, "e": 34000, "s": 33992, "text": "Python3" }, { "code": null, "e": 34003, "s": 34000, "text": "C#" }, { "code": null, "e": 34014, "s": 34003, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <algorithm>#include <iostream>using namespace std; // Function to print the required patternvoid pattern(int n){ // Calculating boundary size int p = 2 * n - 1; for (int i = 1; i <= p; i++) { for (int j = 1; j <= p; j++) { // Printing the values cout << max(abs(i - n), abs(j - n)) + 1 << \" \"; } cout << endl; }} // Driver codeint main(){ int n = 5; pattern(n); return 0;}// This code is contributed by : Vivek kothari", "e": 34548, "s": 34014, "text": null }, { "code": "// C implementation of the approach#include <stdio.h>#include <stdlib.h> // Function Declarationint max(int, int); // Function to print the required patternvoid pattern(int n){ // Calculating boundary size int size = 2 * n - 1; for(int i = 1; i <= size; i++) { for(int j = 1; j <= size; j++) { // Printing the values printf(\"%d \", max(abs(i - n), abs(j - n)) + 1); } printf(\"\\n\"); }} // Function to return maximum valueint max(int val1, int val2){ if (val1 > val2) return val1; return val2;} // Driver codeint main(){ int n = 5; pattern(n); return 0;} // This code is contributed by Yuvaraj R", "e": 35287, "s": 34548, "text": null }, { "code": "// Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // Function to print the required patternpublic static void pattern(int n){ // Calculating boundary size int size = 2 * n - 1; for(int i = 1; i <= size; i++) { for(int j = 1; j <= size; j++) { // Printing the values System.out.print(Math.max( Math.abs(i - n), Math.abs(j - n)) + 1 + \" \"); } System.out.println(); }} // Driver codepublic static void main(String[] args){ int n = 5; pattern(n);}} // This code is contributed by Yuvaraj R", "e": 35930, "s": 35287, "text": null }, { "code": "# Python3 implementation of the approach # Function to print the required patterndef pattern(n): # Calculating boundary size p = 2 * n - 1 for i in range(1, p + 1): for j in range(1, p + 1): # Printing the values print(max(abs(i - n), abs(j - n)) + 1, \" \", end=\"\") print() # Driver coden = 5pattern(n) # This code is contributed by subhammahato348", "e": 36325, "s": 35930, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to print the required patternstatic void pattern(int n){ // Calculating boundary size int size = 2 * n - 1; for(int i = 1; i <= size; i++) { for(int j = 1; j <= size; j++) { // Printing the values Console.Write(Math.Max(Math.Abs(i - n), Math.Abs(j - n)) + 1 + \" \"); } Console.WriteLine(); }} // Driver codepublic static void Main(){ int n = 5; pattern(n);}} // This code is contributed by subhammahato348", "e": 36962, "s": 36325, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print the required patternfunction pattern(n){ // Calculating boundary size let p = 2 * n - 1; for (let i = 1; i <= p; i++) { for (let j = 1; j <= p; j++) { // Printing the values document.write((Math.max(Math.abs(i - n), Math.abs(j - n)) + 1) + \" \"); } document.write(\"<br>\"); }} // Driver codelet n = 5; pattern(n); </script>", "e": 37440, "s": 36962, "text": null }, { "code": null, "e": 37611, "s": 37440, "text": "5 5 5 5 5 5 5 5 5 \n5 4 4 4 4 4 4 4 5 \n5 4 3 3 3 3 3 4 5 \n5 4 3 2 2 2 3 4 5 \n5 4 3 2 1 2 3 4 5 \n5 4 3 2 2 2 3 4 5 \n5 4 3 3 3 3 3 4 5 \n5 4 4 4 4 4 4 4 5 \n5 5 5 5 5 5 5 5 5 " }, { "code": null, "e": 37617, "s": 37611, "text": "ukasp" }, { "code": null, "e": 37630, "s": 37617, "text": "vivekkothari" }, { "code": null, "e": 37640, "s": 37630, "text": "yuvaram11" }, { "code": null, "e": 37656, "s": 37640, "text": "subhammahato348" }, { "code": null, "e": 37666, "s": 37656, "text": "subham348" }, { "code": null, "e": 37671, "s": 37666, "text": "loop" }, { "code": null, "e": 37688, "s": 37671, "text": "pattern-printing" }, { "code": null, "e": 37695, "s": 37688, "text": "Matrix" }, { "code": null, "e": 37714, "s": 37695, "text": "School Programming" }, { "code": null, "e": 37731, "s": 37714, "text": "pattern-printing" }, { "code": null, "e": 37738, "s": 37731, "text": "Matrix" }, { "code": null, "e": 37836, "s": 37738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37845, "s": 37836, "text": "Comments" }, { "code": null, "e": 37858, "s": 37845, "text": "Old Comments" }, { "code": null, "e": 37896, "s": 37858, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 37933, "s": 37896, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 37959, "s": 37933, "text": "A Boolean Matrix Question" }, { "code": null, "e": 38023, "s": 37959, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 38058, "s": 38023, "text": "Python program to add two Matrices" }, { "code": null, "e": 38076, "s": 38058, "text": "Python Dictionary" }, { "code": null, "e": 38092, "s": 38076, "text": "Arrays in C/C++" }, { "code": null, "e": 38117, "s": 38092, "text": "Reverse a string in Java" }, { "code": null, "e": 38136, "s": 38117, "text": "Inheritance in C++" } ]
7 Ways to Manipulate Pandas Dataframes | by Soner Yıldırım | Towards Data Science
Pandas is a very powerful and versatile Python data analysis library that expedites the data analysis and exploration process. One of the advantages of Pandas is that it provides a variety of functions and methods for data manipulation. A dataframe is the core data structure of Pandas. In order to master Pandas, you should be able to play around with dataframes easily and smoothly. In this post, we will go over different ways to manipulate or edit them. Let’s start with importing NumPy and Pandas and creating a sample dataframe. import numpy as npimport pandas as pdvalues = np.random.randint(10, size=(3,7))df = pd.DataFrame(values, columns=list('ABCDEFG'))df.insert(0, 'category', ['cat1','cat2','cat3'])df The first way for manipulation we will mention is the melt function which converts wide dataframes (high number of columns) to narrow ones. Some dataframes are structured in a way that consecutive measurements or variables are represented as columns. In some cases, representing these columns as rows may fit better with our task. #1 meltdf_melted = pd.melt(df, id_vars='category')df_melted.head() The column specified with the id_vars parameter remains the same and the other columns are represented under the variable and value columns. The second way is the stack function which increases the index level. If dataframe has a simple column index, stack returns a series whose indices consist of row-column pairs of original dataframe. If dataframe has multi-level index, stack increases the index level. Consider the following dataframe: #2 stackdf_stacked = df_measurements.stack().to_frame()df_stacked[:6] The stack function, in this case, returns a Series object but we converted it to a dataframe using the to_frame function. The unstack function, as the name indicates, reverses the operation of the stack function. #3 unstackdf_stacked.unstack() Adding or dropping columns is probably the manipulation we do most. Let’s both add a new column and drop some of the existing ones. #4 add or drop columnsdf['city'] = ['Rome','Madrid','Houston']df.drop(['E','F','G'], axis=1, inplace=True)df We created a new column with a list. Pandas Series or NumPy array can also be used to create a column. To drop columns, in addition to the name of the columns, the axis parameters should be set to 1. The inplace parameter is set to True in order to save the changes. New columns are added at the end of dataframe by default. If you want the new columns to be placed at a specific location, you should use the insert function. #5 insertdf.insert(0, 'first_column', [4,2,5])df We may also want to add or drop rows. The append function can be used to add new rows. #6 add or drop rowsnew_row = {'A':4, 'B':2, 'C':5, 'D':4, 'city':'Berlin'}df = df.append(new_row, ignore_index=True)df We can drop a now just like dropping columns. The only change is the axis parameter value. df.drop([3], axis=0, inplace=True)df Another modification on dataframes can be achieved by the pivot_table function. Consider the following dataframe with 30 rows: import randomA = np.random.randint(10, size=30)B = np.random.randint(10, size=30)city = random.sample(['Rome', 'Houston', 'Berlin']*10, 30)cat = random.sample(['cat1', 'cat2', 'cat3']*10 ,30)df = pd.DataFrame({'A':A, 'B':B, 'city':city, 'cat':cat})df.head() The pivot_table function can also be considered as a way to look at the dataframe from a different perspective. It is used to explore the relationships among variables by allowing them present data in different formats. #7 pivot_tabledf.pivot_table(index='cat', columns='city', aggfunc='mean') The return dataframe contains the mean values for each city-cat pair. We have covered 7 ways to edit or manipulate a dataframe. Some of them are so common that you are probably using them almost every day. There will also be cases in which you need to use the rare ones. I think the success and prevalence of Pandas come from the versatile, powerful, and easy-to-use functions to manipulate and analyze data. There are almost always multiple ways to do a task with Pandas. Since a big portion of the time spent on a data science project is spent during data cleaning and preprocessing steps, it is highly encouraged to learn Pandas. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 409, "s": 172, "text": "Pandas is a very powerful and versatile Python data analysis library that expedites the data analysis and exploration process. One of the advantages of Pandas is that it provides a variety of functions and methods for data manipulation." }, { "code": null, "e": 630, "s": 409, "text": "A dataframe is the core data structure of Pandas. In order to master Pandas, you should be able to play around with dataframes easily and smoothly. In this post, we will go over different ways to manipulate or edit them." }, { "code": null, "e": 707, "s": 630, "text": "Let’s start with importing NumPy and Pandas and creating a sample dataframe." }, { "code": null, "e": 887, "s": 707, "text": "import numpy as npimport pandas as pdvalues = np.random.randint(10, size=(3,7))df = pd.DataFrame(values, columns=list('ABCDEFG'))df.insert(0, 'category', ['cat1','cat2','cat3'])df" }, { "code": null, "e": 1218, "s": 887, "text": "The first way for manipulation we will mention is the melt function which converts wide dataframes (high number of columns) to narrow ones. Some dataframes are structured in a way that consecutive measurements or variables are represented as columns. In some cases, representing these columns as rows may fit better with our task." }, { "code": null, "e": 1285, "s": 1218, "text": "#1 meltdf_melted = pd.melt(df, id_vars='category')df_melted.head()" }, { "code": null, "e": 1426, "s": 1285, "text": "The column specified with the id_vars parameter remains the same and the other columns are represented under the variable and value columns." }, { "code": null, "e": 1496, "s": 1426, "text": "The second way is the stack function which increases the index level." }, { "code": null, "e": 1624, "s": 1496, "text": "If dataframe has a simple column index, stack returns a series whose indices consist of row-column pairs of original dataframe." }, { "code": null, "e": 1693, "s": 1624, "text": "If dataframe has multi-level index, stack increases the index level." }, { "code": null, "e": 1727, "s": 1693, "text": "Consider the following dataframe:" }, { "code": null, "e": 1797, "s": 1727, "text": "#2 stackdf_stacked = df_measurements.stack().to_frame()df_stacked[:6]" }, { "code": null, "e": 1919, "s": 1797, "text": "The stack function, in this case, returns a Series object but we converted it to a dataframe using the to_frame function." }, { "code": null, "e": 2010, "s": 1919, "text": "The unstack function, as the name indicates, reverses the operation of the stack function." }, { "code": null, "e": 2041, "s": 2010, "text": "#3 unstackdf_stacked.unstack()" }, { "code": null, "e": 2173, "s": 2041, "text": "Adding or dropping columns is probably the manipulation we do most. Let’s both add a new column and drop some of the existing ones." }, { "code": null, "e": 2282, "s": 2173, "text": "#4 add or drop columnsdf['city'] = ['Rome','Madrid','Houston']df.drop(['E','F','G'], axis=1, inplace=True)df" }, { "code": null, "e": 2385, "s": 2282, "text": "We created a new column with a list. Pandas Series or NumPy array can also be used to create a column." }, { "code": null, "e": 2549, "s": 2385, "text": "To drop columns, in addition to the name of the columns, the axis parameters should be set to 1. The inplace parameter is set to True in order to save the changes." }, { "code": null, "e": 2708, "s": 2549, "text": "New columns are added at the end of dataframe by default. If you want the new columns to be placed at a specific location, you should use the insert function." }, { "code": null, "e": 2757, "s": 2708, "text": "#5 insertdf.insert(0, 'first_column', [4,2,5])df" }, { "code": null, "e": 2795, "s": 2757, "text": "We may also want to add or drop rows." }, { "code": null, "e": 2844, "s": 2795, "text": "The append function can be used to add new rows." }, { "code": null, "e": 2963, "s": 2844, "text": "#6 add or drop rowsnew_row = {'A':4, 'B':2, 'C':5, 'D':4, 'city':'Berlin'}df = df.append(new_row, ignore_index=True)df" }, { "code": null, "e": 3054, "s": 2963, "text": "We can drop a now just like dropping columns. The only change is the axis parameter value." }, { "code": null, "e": 3091, "s": 3054, "text": "df.drop([3], axis=0, inplace=True)df" }, { "code": null, "e": 3218, "s": 3091, "text": "Another modification on dataframes can be achieved by the pivot_table function. Consider the following dataframe with 30 rows:" }, { "code": null, "e": 3476, "s": 3218, "text": "import randomA = np.random.randint(10, size=30)B = np.random.randint(10, size=30)city = random.sample(['Rome', 'Houston', 'Berlin']*10, 30)cat = random.sample(['cat1', 'cat2', 'cat3']*10 ,30)df = pd.DataFrame({'A':A, 'B':B, 'city':city, 'cat':cat})df.head()" }, { "code": null, "e": 3696, "s": 3476, "text": "The pivot_table function can also be considered as a way to look at the dataframe from a different perspective. It is used to explore the relationships among variables by allowing them present data in different formats." }, { "code": null, "e": 3770, "s": 3696, "text": "#7 pivot_tabledf.pivot_table(index='cat', columns='city', aggfunc='mean')" }, { "code": null, "e": 3840, "s": 3770, "text": "The return dataframe contains the mean values for each city-cat pair." }, { "code": null, "e": 4041, "s": 3840, "text": "We have covered 7 ways to edit or manipulate a dataframe. Some of them are so common that you are probably using them almost every day. There will also be cases in which you need to use the rare ones." }, { "code": null, "e": 4403, "s": 4041, "text": "I think the success and prevalence of Pandas come from the versatile, powerful, and easy-to-use functions to manipulate and analyze data. There are almost always multiple ways to do a task with Pandas. Since a big portion of the time spent on a data science project is spent during data cleaning and preprocessing steps, it is highly encouraged to learn Pandas." } ]
Decoding: State Of The Art Recommender System | by Kb Pachauri | Towards Data Science
“Temporal-Contextual Recommendation in Real-Time” was announced as the best paper in the applied data science track, recently in SIGKDD-2020 which was held virtually between 23–27 Aug 2020. In this blog, I will walk through the key component of the HRNN-meta recommender model which achieves a state of the art performance on various datasets and also a comparison of HRNN and HRNN-meta model on skytrax-reviews-dataset for personalized airline recommendation. HRNN-meta combines below major ideas effectively and efficiently for a black-bok recommender system that can adapt to diverse use-cases Hierarchical Recurrent Neural Network (HRNN) for inter and intra sessions dynamics.Field Factorization Machines (FFM) for rich contextual features from meta.Feedback Encoding to apprehend implicit negatives.Efficient training technique using Sampling. Hierarchical Recurrent Neural Network (HRNN) for inter and intra sessions dynamics. Field Factorization Machines (FFM) for rich contextual features from meta. Feedback Encoding to apprehend implicit negatives. Efficient training technique using Sampling. The recommender system has evolved from matrix factorization to focus on two important sources 1) Temporal order of event 2) User/Item Meta. The temporal order of the event is modeled using sequence networks such as LSTM or GRU or vanilla RNN. These networks predict the probability of the next item that the user may interact with based on user history but may find it challenging to model long user sessions due to vanishing gradients. To model long sessions, sessions are partitioned into short sessions by considering periods of inactivity or using any other event. Hierarchical networks are proposed to model these long user sessions by using two sequence networks to learn user and session representations as shown in the below 2 images. During the first session, the user state is randomly initialized, and at the end of the session, SessionRNN initialized user representation as shown in the first image, which in turn initialized the state for the next session in SessionRNN as shown in 2nd image and also can be used throughout the 2nd session as shown in 3rd image. For more details about HRNN, kindly take a look at an excellent video from Alexandros Karatzoglou. “HRNN is extended to include user and item features such as location, item price, etc by stacking contextual information on top of respective user/item latent vectors through field aware multi-layer perception, an extension we call HRNN-meta.”[1] In Factorization Machines, every feature has only one latent vector to learn the latent effect while in Field-aware Factorization Machines each feature has several latent vectors, and depending upon the field of other features, one of them is used to do the inner product. For example, consider three features ESPN, Vogue, and NBC, belong to the field Publisher, and the other three features Nike, Gucci, and Adidas, belong to the field Advertiser. FM → wESPN · wNike + wESPN · wMale + wNike · wMale. FFM → wESPN,A · wNike,P + wESPN,G · wMale,P + wNike,G · wMale,A This raw data is first converted to libffm format than transformed to one-hot encoded before feeding to the network. The data format of LIBFFM is: <label> <field1>:<feature1>:<value1> <field2>:<feature2>:<value2> ... To convert raw data to FFM format, we build 2 dictionaries one for field and one for features #Field DictionaryDictField[Publisher] -> 0DictField[Advertiser] -> 1DictField[Gender] -> 2#Feature DictionaryDictFeature[Publisher-ESPN] -> 0DictFeature[Publisher-Vogue] -> 1DictFeature[Publisher-NBC] -> 2DictFeature[Advertiser-Nike] -> 3DictFeature[Advertiser-Gucci] -> 4DictFeature[Advertiser-Adidas] -> 5DictFeature[Gender-Female] -> 6DictFeature[Gender-Male] -> 7#Tranforming above example to FFM Format1 0:0:1 1:3:1 2:7:1 (since all features are cateogorical, the values are all ones) Along with user features, feedback events (e.g. ratings, purchases, costs, view duration, etc.) of the previous item are concatenate as an input context to predict the next item as shown in below HRNN-meta cell. This provides a better response to implicit negatives like refresh without any click, content open but no video view, etc. Calculating softmax to find out the probability of the next item over large vocabulary is computationally challenging and various sampling strategies are proposed in the literature for efficient training with softmax for eg: Noise Contrastive Estimation, Importance sampling, Negative Sampling, etc. There are 2 approaches Softmax Approximation Sampling-based All the sampling-based approaches approximate softmax with some other loss which is efficient to compute and is mostly useful at training time. For more details on sampling strategies kindly take a look at the excellent blog from Sebastian Ruder. HRNN relies on Negative Sampling which is an approximation of Noise Contrastive Estimation and transforms softmax to logistic loss. Negative items are sampled by raising the item frequencies to 0.75-th power. HRNN-meta is currently available in Amazon Personalize and the below diagram shows how it works. We did a quick check on the comparing HRNN-meta w.r.t HRNN using Amazon Personalize on skytrax-reviews-dataset which has ~41.4K airline reviews, for personalized airline recommendation based on user history and review. To train a model HRNN and HRNN-meta model using Amazon Personalize, after creating an environment, we follow the personalize sample for a contextual recommendation, and the offline metric results using HRNN-meta vs HRNN were very impressive as shown in the below chart. ~80% improvement in coverage, ~17% in mean reciprocal rank and ndcg, ~14% improvement in precision. If you find this interesting and want to train HRNN-meta, please follow getting started amazon personalize samples which will walk you through from environment creation to training recommender model on custom datasets. HRNN-meta provides an efficient/effective recommender solution by effectively combining session-based recommendations with field aware factorization to provide contextualized recommendations. Also provides various methods like item trend decomposition to improve on cold-start item recommendation. It will be interesting to explore other recent methods like BERT4Rec and also see the potentials of replacing GRUs with transformers. Thanks for reading the article, I hope you found this to be helpful. If you did, please share it on your favorite social media so other folks can find it, too. Also, let us know in the comment section if something is not clear or incorrect.
[ { "code": null, "e": 633, "s": 172, "text": "“Temporal-Contextual Recommendation in Real-Time” was announced as the best paper in the applied data science track, recently in SIGKDD-2020 which was held virtually between 23–27 Aug 2020. In this blog, I will walk through the key component of the HRNN-meta recommender model which achieves a state of the art performance on various datasets and also a comparison of HRNN and HRNN-meta model on skytrax-reviews-dataset for personalized airline recommendation." }, { "code": null, "e": 769, "s": 633, "text": "HRNN-meta combines below major ideas effectively and efficiently for a black-bok recommender system that can adapt to diverse use-cases" }, { "code": null, "e": 1021, "s": 769, "text": "Hierarchical Recurrent Neural Network (HRNN) for inter and intra sessions dynamics.Field Factorization Machines (FFM) for rich contextual features from meta.Feedback Encoding to apprehend implicit negatives.Efficient training technique using Sampling." }, { "code": null, "e": 1105, "s": 1021, "text": "Hierarchical Recurrent Neural Network (HRNN) for inter and intra sessions dynamics." }, { "code": null, "e": 1180, "s": 1105, "text": "Field Factorization Machines (FFM) for rich contextual features from meta." }, { "code": null, "e": 1231, "s": 1180, "text": "Feedback Encoding to apprehend implicit negatives." }, { "code": null, "e": 1276, "s": 1231, "text": "Efficient training technique using Sampling." }, { "code": null, "e": 1714, "s": 1276, "text": "The recommender system has evolved from matrix factorization to focus on two important sources 1) Temporal order of event 2) User/Item Meta. The temporal order of the event is modeled using sequence networks such as LSTM or GRU or vanilla RNN. These networks predict the probability of the next item that the user may interact with based on user history but may find it challenging to model long user sessions due to vanishing gradients." }, { "code": null, "e": 1846, "s": 1714, "text": "To model long sessions, sessions are partitioned into short sessions by considering periods of inactivity or using any other event." }, { "code": null, "e": 2353, "s": 1846, "text": "Hierarchical networks are proposed to model these long user sessions by using two sequence networks to learn user and session representations as shown in the below 2 images. During the first session, the user state is randomly initialized, and at the end of the session, SessionRNN initialized user representation as shown in the first image, which in turn initialized the state for the next session in SessionRNN as shown in 2nd image and also can be used throughout the 2nd session as shown in 3rd image." }, { "code": null, "e": 2452, "s": 2353, "text": "For more details about HRNN, kindly take a look at an excellent video from Alexandros Karatzoglou." }, { "code": null, "e": 2699, "s": 2452, "text": "“HRNN is extended to include user and item features such as location, item price, etc by stacking contextual information on top of respective user/item latent vectors through field aware multi-layer perception, an extension we call HRNN-meta.”[1]" }, { "code": null, "e": 2972, "s": 2699, "text": "In Factorization Machines, every feature has only one latent vector to learn the latent effect while in Field-aware Factorization Machines each feature has several latent vectors, and depending upon the field of other features, one of them is used to do the inner product." }, { "code": null, "e": 3148, "s": 2972, "text": "For example, consider three features ESPN, Vogue, and NBC, belong to the field Publisher, and the other three features Nike, Gucci, and Adidas, belong to the field Advertiser." }, { "code": null, "e": 3200, "s": 3148, "text": "FM → wESPN · wNike + wESPN · wMale + wNike · wMale." }, { "code": null, "e": 3264, "s": 3200, "text": "FFM → wESPN,A · wNike,P + wESPN,G · wMale,P + wNike,G · wMale,A" }, { "code": null, "e": 3381, "s": 3264, "text": "This raw data is first converted to libffm format than transformed to one-hot encoded before feeding to the network." }, { "code": null, "e": 3411, "s": 3381, "text": "The data format of LIBFFM is:" }, { "code": null, "e": 3481, "s": 3411, "text": "<label> <field1>:<feature1>:<value1> <field2>:<feature2>:<value2> ..." }, { "code": null, "e": 3575, "s": 3481, "text": "To convert raw data to FFM format, we build 2 dictionaries one for field and one for features" }, { "code": null, "e": 4069, "s": 3575, "text": "#Field DictionaryDictField[Publisher] -> 0DictField[Advertiser] -> 1DictField[Gender] -> 2#Feature DictionaryDictFeature[Publisher-ESPN] -> 0DictFeature[Publisher-Vogue] -> 1DictFeature[Publisher-NBC] -> 2DictFeature[Advertiser-Nike] -> 3DictFeature[Advertiser-Gucci] -> 4DictFeature[Advertiser-Adidas] -> 5DictFeature[Gender-Female] -> 6DictFeature[Gender-Male] -> 7#Tranforming above example to FFM Format1 0:0:1 1:3:1 2:7:1 (since all features are cateogorical, the values are all ones)" }, { "code": null, "e": 4404, "s": 4069, "text": "Along with user features, feedback events (e.g. ratings, purchases, costs, view duration, etc.) of the previous item are concatenate as an input context to predict the next item as shown in below HRNN-meta cell. This provides a better response to implicit negatives like refresh without any click, content open but no video view, etc." }, { "code": null, "e": 4727, "s": 4404, "text": "Calculating softmax to find out the probability of the next item over large vocabulary is computationally challenging and various sampling strategies are proposed in the literature for efficient training with softmax for eg: Noise Contrastive Estimation, Importance sampling, Negative Sampling, etc. There are 2 approaches" }, { "code": null, "e": 4749, "s": 4727, "text": "Softmax Approximation" }, { "code": null, "e": 4764, "s": 4749, "text": "Sampling-based" }, { "code": null, "e": 4908, "s": 4764, "text": "All the sampling-based approaches approximate softmax with some other loss which is efficient to compute and is mostly useful at training time." }, { "code": null, "e": 5220, "s": 4908, "text": "For more details on sampling strategies kindly take a look at the excellent blog from Sebastian Ruder. HRNN relies on Negative Sampling which is an approximation of Noise Contrastive Estimation and transforms softmax to logistic loss. Negative items are sampled by raising the item frequencies to 0.75-th power." }, { "code": null, "e": 5317, "s": 5220, "text": "HRNN-meta is currently available in Amazon Personalize and the below diagram shows how it works." }, { "code": null, "e": 5806, "s": 5317, "text": "We did a quick check on the comparing HRNN-meta w.r.t HRNN using Amazon Personalize on skytrax-reviews-dataset which has ~41.4K airline reviews, for personalized airline recommendation based on user history and review. To train a model HRNN and HRNN-meta model using Amazon Personalize, after creating an environment, we follow the personalize sample for a contextual recommendation, and the offline metric results using HRNN-meta vs HRNN were very impressive as shown in the below chart." }, { "code": null, "e": 5836, "s": 5806, "text": "~80% improvement in coverage," }, { "code": null, "e": 5875, "s": 5836, "text": "~17% in mean reciprocal rank and ndcg," }, { "code": null, "e": 5906, "s": 5875, "text": "~14% improvement in precision." }, { "code": null, "e": 6125, "s": 5906, "text": "If you find this interesting and want to train HRNN-meta, please follow getting started amazon personalize samples which will walk you through from environment creation to training recommender model on custom datasets." }, { "code": null, "e": 6557, "s": 6125, "text": "HRNN-meta provides an efficient/effective recommender solution by effectively combining session-based recommendations with field aware factorization to provide contextualized recommendations. Also provides various methods like item trend decomposition to improve on cold-start item recommendation. It will be interesting to explore other recent methods like BERT4Rec and also see the potentials of replacing GRUs with transformers." } ]