title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Docker host network vs bridge network
There are two types of single−host networks available for Docker Networking - “host” and “bridge” networks. Single−host networks mean that their effect is local to each individual host. In case of a host network, a particular Docker Container can directly use the Networking of the host for sending and receiving the packets. In the case of a bridge network, it requires port mapping to communicate. To understand them better, let’s create a nginx container with the help of host networking. Before creating a nginx container, let’s list all the available networks. sudo docker network ls You will find a network with the name host and driver name as host with the scope as local. Try to inspect that network using the following command. sudo docker network inspect host You will get a json list with all the details about the network. Note that the Containers object is initially empty. We will now create a nginx Docker Container with the host network. sudo docker container run −d −−network host −−name nginx01 nginx−alpine We do not specify port mapping while using the host network because the host network driver automatically uses the “eth0” when running on linux/unix systems. Use the below command to get the container Id. sudo docker inspect <container−id> Inside the browser, copy this IP address and you can verify that the nginx container is running successfully. To check whether the host network is using port mapping or not, list the containers to get the details of the ports. sudo docker container ls You will find that the list of ports for the nginx container is empty. Now, inspect the host network using the following command. sudo network inspect host You will find that now the container’s list has the nginx container details inside it. This verifies that the nginx container is now running on the host network. Now let’s create another nginx container using the network bridge driver without port mapping. sudo docker run −d −−network bridge −−name nginx02 nginx−alpine Now, execute the docker list command to get the details of the container. sudo docker container ls You will find that inside the ports section of the nginx02 container, you will find a port number along with the protocol listed there. Now since we have not specified port mapping while creating the container with bridge network driver, you will not be able to access it through your local machine. To verify the same, try to access it through your browser by pasting the Ip address of the container. sudo docker inspect <container−id> Copy the IP address to your browser, you will find that it throws an error because we did not specify port mapping. Now, we will stop and remove the nginx02 container and create another one but this time specifying the port mapping. sudo docker stop nginx02 sudo docker container rm nginx02 After removing the nginx container, create another network preferably with the same name but using port mapping and bridge network driver. sudo docker container run −d −−network bridge −−name nginx02 −p 80:80 nginx:alpine We have now created the nginx02 container using bridge network driver by mapping port number 80. Execute container list command to verify the same. sudo docker container ls Now, find out the IP address of the nginx02 container using the following command. sudo docker inspect <container−id> Copy the IP address and paste it in your browser. You will now be able to access the nginx container using your browser. Inspect the bridge network to verify the same sudo docker network inspect bridge To conclude, in this article we discussed how to create nginx containers using both host and bridge network drivers. We then saw the differences between the both. Host drivers automatically access the eth0 port and port mapping is not required there. However, bridge network drivers require port mapping in order to access them externally.
[ { "code": null, "e": 1248, "s": 1062, "text": "There are two types of single−host networks available for Docker Networking - “host” and “bridge” networks. Single−host networks mean that their effect is local to each individual host." }, { "code": null, "e": 1462, "s": 1248, "text": "In case of a host network, a particular Docker Container can directly use the Networking of the host for sending and receiving the packets. In the case of a bridge network, it requires port mapping to communicate." }, { "code": null, "e": 1628, "s": 1462, "text": "To understand them better, let’s create a nginx container with the help of host networking. Before creating a nginx container, let’s list all the available networks." }, { "code": null, "e": 1651, "s": 1628, "text": "sudo docker network ls" }, { "code": null, "e": 1800, "s": 1651, "text": "You will find a network with the name host and driver name as host with the scope as local. Try to inspect that network using the following command." }, { "code": null, "e": 1833, "s": 1800, "text": "sudo docker network inspect host" }, { "code": null, "e": 1950, "s": 1833, "text": "You will get a json list with all the details about the network. Note that the Containers object is initially empty." }, { "code": null, "e": 2017, "s": 1950, "text": "We will now create a nginx Docker Container with the host network." }, { "code": null, "e": 2089, "s": 2017, "text": "sudo docker container run −d −−network host −−name nginx01 nginx−alpine" }, { "code": null, "e": 2247, "s": 2089, "text": "We do not specify port mapping while using the host network because the host network driver automatically uses the “eth0” when running on linux/unix systems." }, { "code": null, "e": 2294, "s": 2247, "text": "Use the below command to get the container Id." }, { "code": null, "e": 2330, "s": 2294, "text": "sudo docker inspect <container−id>\n" }, { "code": null, "e": 2440, "s": 2330, "text": "Inside the browser, copy this IP address and you can verify that the nginx container is running successfully." }, { "code": null, "e": 2557, "s": 2440, "text": "To check whether the host network is using port mapping or not, list the containers to get the details of the ports." }, { "code": null, "e": 2582, "s": 2557, "text": "sudo docker container ls" }, { "code": null, "e": 2653, "s": 2582, "text": "You will find that the list of ports for the nginx container is empty." }, { "code": null, "e": 2712, "s": 2653, "text": "Now, inspect the host network using the following command." }, { "code": null, "e": 2738, "s": 2712, "text": "sudo network inspect host" }, { "code": null, "e": 2900, "s": 2738, "text": "You will find that now the container’s list has the nginx container details inside it. This verifies that the nginx container is now running on the host network." }, { "code": null, "e": 2995, "s": 2900, "text": "Now let’s create another nginx container using the network bridge driver without port mapping." }, { "code": null, "e": 3059, "s": 2995, "text": "sudo docker run −d −−network bridge −−name nginx02 nginx−alpine" }, { "code": null, "e": 3133, "s": 3059, "text": "Now, execute the docker list command to get the details of the container." }, { "code": null, "e": 3159, "s": 3133, "text": "sudo docker container ls\n" }, { "code": null, "e": 3561, "s": 3159, "text": "You will find that inside the ports section of the nginx02 container, you will find a port number along with the protocol listed there. Now since we have not specified port mapping while creating the container with bridge network driver, you will not be able to access it through your local machine. To verify the same, try to access it through your browser by pasting the Ip address of the container." }, { "code": null, "e": 3596, "s": 3561, "text": "sudo docker inspect <container−id>" }, { "code": null, "e": 3712, "s": 3596, "text": "Copy the IP address to your browser, you will find that it throws an error because we did not specify port mapping." }, { "code": null, "e": 3829, "s": 3712, "text": "Now, we will stop and remove the nginx02 container and create another one but this time specifying the port mapping." }, { "code": null, "e": 3888, "s": 3829, "text": "sudo docker stop nginx02\n\nsudo docker container rm nginx02" }, { "code": null, "e": 4027, "s": 3888, "text": "After removing the nginx container, create another network preferably with the same name but using port mapping and bridge network driver." }, { "code": null, "e": 4110, "s": 4027, "text": "sudo docker container run −d −−network bridge −−name nginx02 −p 80:80 nginx:alpine" }, { "code": null, "e": 4258, "s": 4110, "text": "We have now created the nginx02 container using bridge network driver by mapping port number 80. Execute container list command to verify the same." }, { "code": null, "e": 4283, "s": 4258, "text": "sudo docker container ls" }, { "code": null, "e": 4366, "s": 4283, "text": "Now, find out the IP address of the nginx02 container using the following command." }, { "code": null, "e": 4402, "s": 4366, "text": "sudo docker inspect <container−id>\n" }, { "code": null, "e": 4569, "s": 4402, "text": "Copy the IP address and paste it in your browser. You will now be able to access the nginx container using your browser. Inspect the bridge network to verify the same" }, { "code": null, "e": 4604, "s": 4569, "text": "sudo docker network inspect bridge" }, { "code": null, "e": 4944, "s": 4604, "text": "To conclude, in this article we discussed how to create nginx containers using both host and bridge network drivers. We then saw the differences between the both. Host drivers automatically access the eth0 port and port mapping is not required there. However, bridge network drivers require port mapping in order to access them externally." } ]
How to Install Yarn in MacOs/Ubuntu/Windows? - GeeksforGeeks
05 Oct, 2021 Prerequisite: Difference between npm and yarn Yarn in layman’s term is a package manager that can be used in your code or a project that is currently being built, what yarn does is it helps to share the code with fellow mates or within a community of developers, and they can even run the project that we are building on their end. But how actually is that code shared with other people, well that’s done by sharing the code files that are used to develop the project and with a package.json file, and this package.json file describes what all yarn package is used in the project, also which are required with its version used while developing the project. So, what the other fellow mate can do is install yarn on his/her machine and do yarn install To install all the dependencies and packages required to get started with the project. Method 1: Using NPM. In the OS X terminal you need to type: npm install --global yarn NOTE: You will need to have NPM (Node package manager pre-installed on the pc) If some error comes you need to give admin privileges to the terminal so that it can access npm already installed on your pc. installing yarn using npm on macOS Method 2: Using HomeBrew Package Manager: brew install yarn Method 3: Using curl: You need to type the following command in the terminal curl -o- -L https://yarnpkg.com/install.sh | bash NOTE: the above command works for both Linux and macOS. Method 1: Using npm manager. It’s valid to use the standard method to install with npm, using the following commands in the terminal npm install --global yarn Method 2: Using curl. Step 1: You can install it with the Debian package repository by first configuring the repository first using the following commands. curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list Demo of the above 2 commands Step 2: And then once after successful install of the above command use sudo apt install yarn installing yarn and checking the version installed Method 1: Using msi file. Using the .msi file which can be downloaded from here (from the official yarn-site) Source: yarn official site Method 2: Using chocolatey package manager. Step 1: Install choco package in your windows, for that you need to go here. Basically, you need to type the following command shown below with administrative privileges Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’)) Step 2: After installing head over to PowerShell and follow the instructions below. Open up the windows PowerShell or any preferable terminal and type the following command choco install yarn Yarn installation Successful install of yarn Step 1: Using RPM package manager type the following command in the terminal. curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo Step 2: After performing the above steps type the following commands in the terminal curl --silent --location https://rpm.nodesource.com/setup_12.x | sudo bash - Step 3: At last, type the following to install yarn completely in the machine sudo yum install yarn how-to-install Packages How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS?
[ { "code": null, "e": 24561, "s": 24533, "text": "\n05 Oct, 2021" }, { "code": null, "e": 24607, "s": 24561, "text": "Prerequisite: Difference between npm and yarn" }, { "code": null, "e": 24894, "s": 24607, "text": "Yarn in layman’s term is a package manager that can be used in your code or a project that is currently being built, what yarn does is it helps to share the code with fellow mates or within a community of developers, and they can even run the project that we are building on their end. " }, { "code": null, "e": 25300, "s": 24894, "text": "But how actually is that code shared with other people, well that’s done by sharing the code files that are used to develop the project and with a package.json file, and this package.json file describes what all yarn package is used in the project, also which are required with its version used while developing the project. So, what the other fellow mate can do is install yarn on his/her machine and do " }, { "code": null, "e": 25314, "s": 25300, "text": "yarn install " }, { "code": null, "e": 25401, "s": 25314, "text": "To install all the dependencies and packages required to get started with the project." }, { "code": null, "e": 25422, "s": 25401, "text": "Method 1: Using NPM." }, { "code": null, "e": 25461, "s": 25422, "text": "In the OS X terminal you need to type:" }, { "code": null, "e": 25487, "s": 25461, "text": "npm install --global yarn" }, { "code": null, "e": 25566, "s": 25487, "text": "NOTE: You will need to have NPM (Node package manager pre-installed on the pc)" }, { "code": null, "e": 25692, "s": 25566, "text": "If some error comes you need to give admin privileges to the terminal so that it can access npm already installed on your pc." }, { "code": null, "e": 25727, "s": 25692, "text": "installing yarn using npm on macOS" }, { "code": null, "e": 25769, "s": 25727, "text": "Method 2: Using HomeBrew Package Manager:" }, { "code": null, "e": 25787, "s": 25769, "text": "brew install yarn" }, { "code": null, "e": 25809, "s": 25787, "text": "Method 3: Using curl:" }, { "code": null, "e": 25864, "s": 25809, "text": "You need to type the following command in the terminal" }, { "code": null, "e": 25914, "s": 25864, "text": "curl -o- -L https://yarnpkg.com/install.sh | bash" }, { "code": null, "e": 25970, "s": 25914, "text": "NOTE: the above command works for both Linux and macOS." }, { "code": null, "e": 25999, "s": 25970, "text": "Method 1: Using npm manager." }, { "code": null, "e": 26103, "s": 25999, "text": "It’s valid to use the standard method to install with npm, using the following commands in the terminal" }, { "code": null, "e": 26129, "s": 26103, "text": "npm install --global yarn" }, { "code": null, "e": 26151, "s": 26129, "text": "Method 2: Using curl." }, { "code": null, "e": 26285, "s": 26151, "text": "Step 1: You can install it with the Debian package repository by first configuring the repository first using the following commands." }, { "code": null, "e": 26455, "s": 26285, "text": "curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -\necho \"deb https://dl.yarnpkg.com/debian/ stable main\" | sudo tee /etc/apt/sources.list.d/yarn.list" }, { "code": null, "e": 26484, "s": 26455, "text": "Demo of the above 2 commands" }, { "code": null, "e": 26556, "s": 26484, "text": "Step 2: And then once after successful install of the above command use" }, { "code": null, "e": 26578, "s": 26556, "text": "sudo apt install yarn" }, { "code": null, "e": 26629, "s": 26578, "text": "installing yarn and checking the version installed" }, { "code": null, "e": 26655, "s": 26629, "text": "Method 1: Using msi file." }, { "code": null, "e": 26739, "s": 26655, "text": "Using the .msi file which can be downloaded from here (from the official yarn-site)" }, { "code": null, "e": 26766, "s": 26739, "text": "Source: yarn official site" }, { "code": null, "e": 26810, "s": 26766, "text": "Method 2: Using chocolatey package manager." }, { "code": null, "e": 26887, "s": 26810, "text": "Step 1: Install choco package in your windows, for that you need to go here." }, { "code": null, "e": 26980, "s": 26887, "text": "Basically, you need to type the following command shown below with administrative privileges" }, { "code": null, "e": 27238, "s": 26980, "text": "Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’))" }, { "code": null, "e": 27322, "s": 27238, "text": "Step 2: After installing head over to PowerShell and follow the instructions below." }, { "code": null, "e": 27411, "s": 27322, "text": "Open up the windows PowerShell or any preferable terminal and type the following command" }, { "code": null, "e": 27430, "s": 27411, "text": "choco install yarn" }, { "code": null, "e": 27449, "s": 27430, "text": "Yarn installation " }, { "code": null, "e": 27476, "s": 27449, "text": "Successful install of yarn" }, { "code": null, "e": 27554, "s": 27476, "text": "Step 1: Using RPM package manager type the following command in the terminal." }, { "code": null, "e": 27654, "s": 27554, "text": "curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo" }, { "code": null, "e": 27739, "s": 27654, "text": "Step 2: After performing the above steps type the following commands in the terminal" }, { "code": null, "e": 27816, "s": 27739, "text": "curl --silent --location https://rpm.nodesource.com/setup_12.x | sudo bash -" }, { "code": null, "e": 27894, "s": 27816, "text": "Step 3: At last, type the following to install yarn completely in the machine" }, { "code": null, "e": 27916, "s": 27894, "text": "sudo yum install yarn" }, { "code": null, "e": 27931, "s": 27916, "text": "how-to-install" }, { "code": null, "e": 27940, "s": 27931, "text": "Packages" }, { "code": null, "e": 27947, "s": 27940, "text": "How To" }, { "code": null, "e": 27966, "s": 27947, "text": "Installation Guide" }, { "code": null, "e": 28064, "s": 27966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28073, "s": 28064, "text": "Comments" }, { "code": null, "e": 28086, "s": 28073, "text": "Old Comments" }, { "code": null, "e": 28120, "s": 28086, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28169, "s": 28120, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 28227, "s": 28169, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 28269, "s": 28227, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 28329, "s": 28269, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 28362, "s": 28329, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28396, "s": 28362, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28431, "s": 28396, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 28489, "s": 28431, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" } ]
C library function - isalpha()
The C library function int isalpha(int c) checks if the passed character is alphabetic. Following is the declaration for isalpha() function. int isalpha(int c); c − This is the character to be checked. c − This is the character to be checked. This function returns non-zero value if c is an alphabet, else it returns 0. The following example shows the usage of isalpha() function. #include <stdio.h> #include <ctype.h> int main () { int var1 = 'd'; int var2 = '2'; int var3 = '\t'; int var4 = ' '; if( isalpha(var1) ) { printf("var1 = |%c| is an alphabet\n", var1 ); } else { printf("var1 = |%c| is not an alphabet\n", var1 ); } if( isalpha(var2) ) { printf("var2 = |%c| is an alphabet\n", var2 ); } else { printf("var2 = |%c| is not an alphabet\n", var2 ); } if( isalpha(var3) ) { printf("var3 = |%c| is an alphabet\n", var3 ); } else { printf("var3 = |%c| is not an alphabet\n", var3 ); } if( isalpha(var4) ) { printf("var4 = |%c| is an alphabet\n", var4 ); } else { printf("var4 = |%c| is not an alphabet\n", var4 ); } return(0); } Let us compile and run the above program, to produce the following result − var1 = |d| is an alphabet var2 = |2| is not an alphabet var3 = | | is not an alphabet var4 = | | is not an alphabet 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2095, "s": 2007, "text": "The C library function int isalpha(int c) checks if the passed character is alphabetic." }, { "code": null, "e": 2148, "s": 2095, "text": "Following is the declaration for isalpha() function." }, { "code": null, "e": 2168, "s": 2148, "text": "int isalpha(int c);" }, { "code": null, "e": 2209, "s": 2168, "text": "c − This is the character to be checked." }, { "code": null, "e": 2250, "s": 2209, "text": "c − This is the character to be checked." }, { "code": null, "e": 2327, "s": 2250, "text": "This function returns non-zero value if c is an alphabet, else it returns 0." }, { "code": null, "e": 2388, "s": 2327, "text": "The following example shows the usage of isalpha() function." }, { "code": null, "e": 3163, "s": 2388, "text": "#include <stdio.h>\n#include <ctype.h>\n\nint main () {\n int var1 = 'd';\n int var2 = '2';\n int var3 = '\\t';\n int var4 = ' ';\n \n if( isalpha(var1) ) {\n printf(\"var1 = |%c| is an alphabet\\n\", var1 );\n } else {\n printf(\"var1 = |%c| is not an alphabet\\n\", var1 );\n }\n \n if( isalpha(var2) ) {\n printf(\"var2 = |%c| is an alphabet\\n\", var2 );\n } else {\n printf(\"var2 = |%c| is not an alphabet\\n\", var2 );\n }\n \n if( isalpha(var3) ) {\n printf(\"var3 = |%c| is an alphabet\\n\", var3 );\n } else {\n printf(\"var3 = |%c| is not an alphabet\\n\", var3 );\n }\n \n if( isalpha(var4) ) {\n printf(\"var4 = |%c| is an alphabet\\n\", var4 );\n } else {\n printf(\"var4 = |%c| is not an alphabet\\n\", var4 );\n }\n \n return(0);\n}" }, { "code": null, "e": 3239, "s": 3163, "text": "Let us compile and run the above program, to produce the following result −" }, { "code": null, "e": 3503, "s": 3239, "text": "var1 = |d| is an alphabet \nvar2 = |2| is not an alphabet \nvar3 = | | is not an alphabet \nvar4 = | | is not an alphabet \n" }, { "code": null, "e": 3536, "s": 3503, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3551, "s": 3536, "text": " Nishant Malik" }, { "code": null, "e": 3586, "s": 3551, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3601, "s": 3586, "text": " Nishant Malik" }, { "code": null, "e": 3636, "s": 3601, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3650, "s": 3636, "text": " Asif Hussain" }, { "code": null, "e": 3683, "s": 3650, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3701, "s": 3683, "text": " Richa Maheshwari" }, { "code": null, "e": 3736, "s": 3701, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3755, "s": 3736, "text": " Vandana Annavaram" }, { "code": null, "e": 3788, "s": 3755, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3800, "s": 3788, "text": " Amit Diwan" }, { "code": null, "e": 3807, "s": 3800, "text": " Print" }, { "code": null, "e": 3818, "s": 3807, "text": " Add Notes" } ]
Variables in Scala
31 Oct, 2021 Variables are simply storage locations. Every variable is known by its name and stores some known and unknown piece of information known as value. So one can define a variable by its data type and name, a data type is responsible for allocating memory for the variable. In Scala there are two types of variables: Mutable Variables Immutable Variables Let’s understand each one of these variables in detail. Mutable Variable: These variables are those variables that allow us to change a value after the declaration of a variable. Mutable variables are defined by using the var keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. Syntax: var Variable_name: Data_type = "value"; For Example: var name: String = "geekforgeeks"; Here, name is the name of the variable, string is the data type of variable and geeksforgeeks is the value that store in the memory. Another way of defining variable: Syntax: var variable_name = value For Example: var value = 40 //it works without error value = 32 Here, the value is the name of the variable. Immutable Variable: These variables are those variables that do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the val keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. Syntax: val Variable_name: Data_type = "value"; For Example: val name: String = "geekforgeeks"; Here, a name is the name of the variable, a string is the data type of variable and geeksforgeeks is the value that store in the memory. Another way of defining variable: Syntax: val variable_name = "value" For Example: val value = 40 //it will give an error value = 32 Here value is the name of the variable. Rules for naming variable in Scala Variable name should be in lower case. Variable name can contain letter, digit and two special characters(Underscore(_) and Dollar($) sign) Variable name must not contain the keyword or reserved word. Starting letter of the variable name should be an alphabet. White space is not allowed in variable name. Note: Scala supports multiple assignments but you can use multiple assignments only with immutable variables.For Example: val(name1:Int, name2:String) = pair(2, "geekforgeeks") Variable Type Inference In Scala: Scala supports variable type inference. In variable type inference values are directly assigned to the variable without defining its data type, the Scala compiler automatically resolves which value belongs to which data type. For Example: var name1=40; val name2="geeksforgeeks"; Here, name1 is by default int type and name2 is by default string type. sujayshashank nikhildhimanntpc Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Oct, 2021" }, { "code": null, "e": 367, "s": 53, "text": "Variables are simply storage locations. Every variable is known by its name and stores some known and unknown piece of information known as value. So one can define a variable by its data type and name, a data type is responsible for allocating memory for the variable. In Scala there are two types of variables: " }, { "code": null, "e": 385, "s": 367, "text": "Mutable Variables" }, { "code": null, "e": 405, "s": 385, "text": "Immutable Variables" }, { "code": null, "e": 462, "s": 405, "text": "Let’s understand each one of these variables in detail. " }, { "code": null, "e": 759, "s": 462, "text": "Mutable Variable: These variables are those variables that allow us to change a value after the declaration of a variable. Mutable variables are defined by using the var keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. Syntax: " }, { "code": null, "e": 799, "s": 759, "text": "var Variable_name: Data_type = \"value\";" }, { "code": null, "e": 813, "s": 799, "text": "For Example: " }, { "code": null, "e": 848, "s": 813, "text": "var name: String = \"geekforgeeks\";" }, { "code": null, "e": 1016, "s": 848, "text": "Here, name is the name of the variable, string is the data type of variable and geeksforgeeks is the value that store in the memory. Another way of defining variable: " }, { "code": null, "e": 1025, "s": 1016, "text": "Syntax: " }, { "code": null, "e": 1051, "s": 1025, "text": "var variable_name = value" }, { "code": null, "e": 1065, "s": 1051, "text": "For Example: " }, { "code": null, "e": 1081, "s": 1065, "text": "var value = 40 " }, { "code": null, "e": 1117, "s": 1081, "text": "//it works without error value = 32" }, { "code": null, "e": 1164, "s": 1117, "text": " Here, the value is the name of the variable. " }, { "code": null, "e": 1464, "s": 1164, "text": "Immutable Variable: These variables are those variables that do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the val keyword. The first letter of data type should be in capital letter because in Scala data type is treated as objects. " }, { "code": null, "e": 1473, "s": 1464, "text": "Syntax: " }, { "code": null, "e": 1514, "s": 1473, "text": "val Variable_name: Data_type = \"value\";" }, { "code": null, "e": 1528, "s": 1514, "text": "For Example: " }, { "code": null, "e": 1563, "s": 1528, "text": "val name: String = \"geekforgeeks\";" }, { "code": null, "e": 1735, "s": 1563, "text": "Here, a name is the name of the variable, a string is the data type of variable and geeksforgeeks is the value that store in the memory. Another way of defining variable: " }, { "code": null, "e": 1744, "s": 1735, "text": "Syntax: " }, { "code": null, "e": 1772, "s": 1744, "text": "val variable_name = \"value\"" }, { "code": null, "e": 1786, "s": 1772, "text": "For Example: " }, { "code": null, "e": 1802, "s": 1786, "text": "val value = 40 " }, { "code": null, "e": 1837, "s": 1802, "text": "//it will give an error value = 32" }, { "code": null, "e": 1879, "s": 1837, "text": " Here value is the name of the variable. " }, { "code": null, "e": 1915, "s": 1879, "text": "Rules for naming variable in Scala " }, { "code": null, "e": 1954, "s": 1915, "text": "Variable name should be in lower case." }, { "code": null, "e": 2055, "s": 1954, "text": "Variable name can contain letter, digit and two special characters(Underscore(_) and Dollar($) sign)" }, { "code": null, "e": 2116, "s": 2055, "text": "Variable name must not contain the keyword or reserved word." }, { "code": null, "e": 2176, "s": 2116, "text": "Starting letter of the variable name should be an alphabet." }, { "code": null, "e": 2221, "s": 2176, "text": "White space is not allowed in variable name." }, { "code": null, "e": 2344, "s": 2221, "text": "Note: Scala supports multiple assignments but you can use multiple assignments only with immutable variables.For Example: " }, { "code": null, "e": 2399, "s": 2344, "text": "val(name1:Int, name2:String) = pair(2, \"geekforgeeks\")" }, { "code": null, "e": 2660, "s": 2399, "text": "Variable Type Inference In Scala: Scala supports variable type inference. In variable type inference values are directly assigned to the variable without defining its data type, the Scala compiler automatically resolves which value belongs to which data type. " }, { "code": null, "e": 2674, "s": 2660, "text": "For Example: " }, { "code": null, "e": 2715, "s": 2674, "text": "var name1=40;\nval name2=\"geeksforgeeks\";" }, { "code": null, "e": 2788, "s": 2715, "text": "Here, name1 is by default int type and name2 is by default string type. " }, { "code": null, "e": 2802, "s": 2788, "text": "sujayshashank" }, { "code": null, "e": 2819, "s": 2802, "text": "nikhildhimanntpc" }, { "code": null, "e": 2825, "s": 2819, "text": "Scala" }, { "code": null, "e": 2838, "s": 2825, "text": "Scala-Basics" }, { "code": null, "e": 2844, "s": 2838, "text": "Scala" } ]
sys.path in Python
01 Oct, 2020 Sys is a built-in Python module that contains parameters specific to the system i.e. it contains variables and methods that interact with the interpreter and are also governed by it. sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. When a module(a module is a python file) is imported within a Python file, the interpreter first searches for the specified module among its built-in modules. If not found it looks through the list of directories(a directory is a folder that contains related modules) defined by sys.path. There are three ways to specify a path : DEFAULT- By default, the interpreter looks for a module within the current directory. To make the interpreter search in some other directory you just simply have to change the current directory. The following example depicts a default path taken by the interpreter: Python3 # importing moduleimport sys # printing all directories for # interpreter to searchsys.path Output: THROUGH ENVIRONMENT VARIABLES- An environment variable that contains the path an interpreter can take while looking for modules can be employed. Once set, it hints interpreter with directories to locate a module. The following example shows how this can be done. PYTHONPATH=C:\Users\Vanshi\Desktop Python3 # importing moduleimport sys # printing all directoriessys.path Output: APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search. The following example shows how this can be done. Python3 # importing moduleimport sys # appending a pathsys.path.append('C:/Users/Vanshi/Desktop') # printing all pathssys.path Output: Note that the first string returned by path is always empty this is to indicate the interpreter to check in the current directory. Python-sys Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2020" }, { "code": null, "e": 236, "s": 52, "text": "Sys is a built-in Python module that contains parameters specific to the system i.e. it contains variables and methods that interact with the interpreter and are also governed by it. " }, { "code": null, "e": 387, "s": 236, "text": "sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. " }, { "code": null, "e": 676, "s": 387, "text": "When a module(a module is a python file) is imported within a Python file, the interpreter first searches for the specified module among its built-in modules. If not found it looks through the list of directories(a directory is a folder that contains related modules) defined by sys.path." }, { "code": null, "e": 717, "s": 676, "text": "There are three ways to specify a path :" }, { "code": null, "e": 983, "s": 717, "text": "DEFAULT- By default, the interpreter looks for a module within the current directory. To make the interpreter search in some other directory you just simply have to change the current directory. The following example depicts a default path taken by the interpreter:" }, { "code": null, "e": 991, "s": 983, "text": "Python3" }, { "code": "# importing moduleimport sys # printing all directories for # interpreter to searchsys.path", "e": 1084, "s": 991, "text": null }, { "code": null, "e": 1092, "s": 1084, "text": "Output:" }, { "code": null, "e": 1356, "s": 1092, "text": "THROUGH ENVIRONMENT VARIABLES- An environment variable that contains the path an interpreter can take while looking for modules can be employed. Once set, it hints interpreter with directories to locate a module. The following example shows how this can be done." }, { "code": null, "e": 1392, "s": 1356, "text": "PYTHONPATH=C:\\Users\\Vanshi\\Desktop\n" }, { "code": null, "e": 1400, "s": 1392, "text": "Python3" }, { "code": "# importing moduleimport sys # printing all directoriessys.path", "e": 1465, "s": 1400, "text": null }, { "code": null, "e": 1473, "s": 1465, "text": "Output:" }, { "code": null, "e": 1671, "s": 1473, "text": "APPENDING PATH- append() is a built-in function of sys module that can be used with path variable to add a specific path for interpreter to search. The following example shows how this can be done." }, { "code": null, "e": 1679, "s": 1671, "text": "Python3" }, { "code": "# importing moduleimport sys # appending a pathsys.path.append('C:/Users/Vanshi/Desktop') # printing all pathssys.path", "e": 1800, "s": 1679, "text": null }, { "code": null, "e": 1808, "s": 1800, "text": "Output:" }, { "code": null, "e": 1939, "s": 1808, "text": "Note that the first string returned by path is always empty this is to indicate the interpreter to check in the current directory." }, { "code": null, "e": 1950, "s": 1939, "text": "Python-sys" }, { "code": null, "e": 1957, "s": 1950, "text": "Python" } ]
Matplotlib.pyplot.colors() in Python
03 May, 2020 In Python we can plot graphs for visualization using Matplotlib library. For integrating plots into applications, Matplotlib provides an API. Matplotlib has a module named pyplot which provides a MATLAB-like interface. This function is used to specify the color. It is do-nothing function. We can use this function for various data visualizations and obtain insights from them. Examples 1: import matplotlib.pyplot as plt # Define the Colorcolor = 'green'plt.plot([1, 2, 3, 4], color = color) plt.show() Output: Example 2: import matplotlib.pyplot as plt x = [1, 2, 3, 4]y= [1, 4, 9, 16] plt.plot(x, y, marker = 'o', markerfacecolor = 'r') plt.show() Output: Here, marker=’o’ represents circle while markerfacecolor is used for specifying color of the point marker. Note: This function has been deprecated since version 2.1. Matplotlib Pyplot-class Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2020" }, { "code": null, "e": 247, "s": 28, "text": "In Python we can plot graphs for visualization using Matplotlib library. For integrating plots into applications, Matplotlib provides an API. Matplotlib has a module named pyplot which provides a MATLAB-like interface." }, { "code": null, "e": 318, "s": 247, "text": "This function is used to specify the color. It is do-nothing function." }, { "code": null, "e": 406, "s": 318, "text": "We can use this function for various data visualizations and obtain insights from them." }, { "code": null, "e": 418, "s": 406, "text": "Examples 1:" }, { "code": "import matplotlib.pyplot as plt # Define the Colorcolor = 'green'plt.plot([1, 2, 3, 4], color = color) plt.show()", "e": 536, "s": 418, "text": null }, { "code": null, "e": 544, "s": 536, "text": "Output:" }, { "code": null, "e": 555, "s": 544, "text": "Example 2:" }, { "code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4]y= [1, 4, 9, 16] plt.plot(x, y, marker = 'o', markerfacecolor = 'r') plt.show()", "e": 688, "s": 555, "text": null }, { "code": null, "e": 696, "s": 688, "text": "Output:" }, { "code": null, "e": 803, "s": 696, "text": "Here, marker=’o’ represents circle while markerfacecolor is used for specifying color of the point marker." }, { "code": null, "e": 862, "s": 803, "text": "Note: This function has been deprecated since version 2.1." }, { "code": null, "e": 886, "s": 862, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 904, "s": 886, "text": "Python-matplotlib" }, { "code": null, "e": 911, "s": 904, "text": "Python" }, { "code": null, "e": 927, "s": 911, "text": "Write From Home" } ]
Map.Entry interface in Java with example
28 Sep, 2021 Map.Entry interface in Java provides certain methods to access the entry in the Map. By gaining access to the entry of the Map we can easily manipulate them. Map.Entry is a generic and is defined in the java.util package. Declaration : Interface Map.Entry k -> Key V -> Value Methods: equals (Object o) – It compares the object (invoking object) with the Object o for equality.Syntax :boolean equals(Object o) Parameters : o -> Object to which we want to compare Returns: true: if both objects are equals false: otherwise K getKey() – Returns the key for the corresponding map entry.Syntax :K getKey() Parameters : ------------- Returns: K -> Returns the corresponding Key of a entry on which it is invoked Exception –IllegalSateException is thrown when entry has been removed from the map.V getValue() – Returns the value for the corresponding map entry.Syntax :V getValue() Parameters : ------------- Returns: V -> Returns the corresponding value of a entry on which it is invoked int hashcode() – Returns the hashcode for the corresponding map entry.Syntax :int hashcode() Parameters : ------------- Returns: int -> Returns the hash-code of entry on which it is invoked V setValue(V v) – Sets the value of the map with specified value vV setValue(V v) Parameters : v -> Value which was earlier stored in the entry on which it is invoked Returns: int -> Returns the hash-code of a entry on which it is invokedException :ClassCastException is thrown if the class of the value ‘v’ is not a correct type for map.NullPointerException is thrown if ‘null’ is stored in ‘v’, and ‘null ’ is not supported by map.UnsupportedOperationException is thrown if we cannot manipulate the map or the put operation is not supported by the map.IllegalArgumetException is thrown If there is some problem with the argument i.e vIllegalStateException is thrown when entry has been removed from the map equals (Object o) – It compares the object (invoking object) with the Object o for equality.Syntax :boolean equals(Object o) Parameters : o -> Object to which we want to compare Returns: true: if both objects are equals false: otherwise boolean equals(Object o) Parameters : o -> Object to which we want to compare Returns: true: if both objects are equals false: otherwise K getKey() – Returns the key for the corresponding map entry.Syntax :K getKey() Parameters : ------------- Returns: K -> Returns the corresponding Key of a entry on which it is invoked Exception –IllegalSateException is thrown when entry has been removed from the map. K getKey() Parameters : ------------- Returns: K -> Returns the corresponding Key of a entry on which it is invoked Exception – IllegalSateException is thrown when entry has been removed from the map. V getValue() – Returns the value for the corresponding map entry.Syntax :V getValue() Parameters : ------------- Returns: V -> Returns the corresponding value of a entry on which it is invoked V getValue() Parameters : ------------- Returns: V -> Returns the corresponding value of a entry on which it is invoked int hashcode() – Returns the hashcode for the corresponding map entry.Syntax :int hashcode() Parameters : ------------- Returns: int -> Returns the hash-code of entry on which it is invoked int hashcode() Parameters : ------------- Returns: int -> Returns the hash-code of entry on which it is invoked V setValue(V v) – Sets the value of the map with specified value vV setValue(V v) Parameters : v -> Value which was earlier stored in the entry on which it is invoked Returns: int -> Returns the hash-code of a entry on which it is invokedException :ClassCastException is thrown if the class of the value ‘v’ is not a correct type for map.NullPointerException is thrown if ‘null’ is stored in ‘v’, and ‘null ’ is not supported by map.UnsupportedOperationException is thrown if we cannot manipulate the map or the put operation is not supported by the map.IllegalArgumetException is thrown If there is some problem with the argument i.e vIllegalStateException is thrown when entry has been removed from the map V setValue(V v) Parameters : v -> Value which was earlier stored in the entry on which it is invoked Returns: int -> Returns the hash-code of a entry on which it is invoked Exception : ClassCastException is thrown if the class of the value ‘v’ is not a correct type for map. NullPointerException is thrown if ‘null’ is stored in ‘v’, and ‘null ’ is not supported by map. UnsupportedOperationException is thrown if we cannot manipulate the map or the put operation is not supported by the map. IllegalArgumetException is thrown If there is some problem with the argument i.e v IllegalStateException is thrown when entry has been removed from the map Set<Map.Entry> entrySet() – Returns the Set view of the entire map.Note : This is not a method of Map.entry interface but it is discussed here because this method is useful while working with Map.Entry interface. Set<Map.Entry> entrySet() Parameters : --------------- Returns: Set<Map.Entry> ->: Returns a Set containing the Map.Entry values Program below demonstrate the working of Map.Entry: // Java Program to demonstrate the// methods of Map.Entry import java.util.LinkedHashMap;import java.util.Map;import java.util.Set; public class GFG { public static void main(String[] args) { // Create a LinkedHashMap LinkedHashMap<String,Integer> m = new LinkedHashMap<String, Integer>(); m.put("1 - Bedroom" , 25000); m.put("2 - Bedroom" , 50000); m.put("3 - Bedroom" , 75000); m.put("1 - Bedroom - hall", 65000); m.put("2 - Bedroom - hall", 85000); m.put("3 - Bedroom - hall", 105000); // Using entrySet() to get the entry's of the map Set<Map.Entry<String,Integer>> s = m.entrySet(); for (Map.Entry<String, Integer> it: s) { // Using the getKey to get key of the it element // Using the getValue to get value of the it element System.out.println("Before change of value = " + it.getKey() + " " + it.getValue()); // Changing the value of 1 - Bedroom. double getRandom = Math.random() * 100000; int getRoundoff = (int) Math.round(getRandom); // Using setValue to change the value of the // map element it.setValue(getRoundoff); System.out.println("After change of value = " + it.getKey() + " " + it.getValue()); } }} Output: Before change of value = 1 - Bedroom 25000 After change of value = 1 - Bedroom 59475 Before change of value = 2 - Bedroom 50000 After change of value = 2 - Bedroom 51650 Before change of value = 3 - Bedroom 75000 After change of value = 3 - Bedroom 95200 Before change of value = 1 - Bedroom - hall 65000 After change of value = 1 - Bedroom - hall 74112 Before change of value = 2 - Bedroom - hall 85000 After change of value = 2 - Bedroom - hall 41490 Before change of value = 3 - Bedroom - hall 105000 After change of value = 3 - Bedroom - hall 10902 This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to write@geeksforgeeks.org. 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. surinderdawra388 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Sep, 2021" }, { "code": null, "e": 274, "s": 52, "text": "Map.Entry interface in Java provides certain methods to access the entry in the Map. By gaining access to the entry of the Map we can easily manipulate them. Map.Entry is a generic and is defined in the java.util package." }, { "code": null, "e": 288, "s": 274, "text": "Declaration :" }, { "code": null, "e": 328, "s": 288, "text": "Interface Map.Entry\nk -> Key\nV -> Value" }, { "code": null, "e": 337, "s": 328, "text": "Methods:" }, { "code": null, "e": 1934, "s": 337, "text": "equals (Object o) – It compares the object (invoking object) with the Object o for equality.Syntax :boolean equals(Object o)\nParameters :\no -> Object to which we want to compare\nReturns:\ntrue: if both objects are equals\nfalse: otherwise\nK getKey() – Returns the key for the corresponding map entry.Syntax :K getKey()\nParameters :\n-------------\nReturns:\nK -> Returns the corresponding Key of a entry on which it is invoked\nException –IllegalSateException is thrown when entry has been removed from the map.V getValue() – Returns the value for the corresponding map entry.Syntax :V getValue()\nParameters :\n-------------\nReturns:\nV -> Returns the corresponding value of a entry on which it is invoked\nint hashcode() – Returns the hashcode for the corresponding map entry.Syntax :int hashcode()\nParameters :\n-------------\nReturns:\nint -> Returns the hash-code of entry on which it is invoked\nV setValue(V v) – Sets the value of the map with specified value vV setValue(V v)\nParameters :\nv -> Value which was earlier stored in the entry on which it is invoked\nReturns:\nint -> Returns the hash-code of a entry on which it is invokedException :ClassCastException is thrown if the class of the value ‘v’ is not a correct type for map.NullPointerException is thrown if ‘null’ is stored in ‘v’, and ‘null ’ is not supported by map.UnsupportedOperationException is thrown if we cannot manipulate the map or the put operation is not supported by the map.IllegalArgumetException is thrown If there is some problem with the argument i.e vIllegalStateException is thrown when entry has been removed from the map" }, { "code": null, "e": 2172, "s": 1934, "text": "equals (Object o) – It compares the object (invoking object) with the Object o for equality.Syntax :boolean equals(Object o)\nParameters :\no -> Object to which we want to compare\nReturns:\ntrue: if both objects are equals\nfalse: otherwise\n" }, { "code": null, "e": 2310, "s": 2172, "text": "boolean equals(Object o)\nParameters :\no -> Object to which we want to compare\nReturns:\ntrue: if both objects are equals\nfalse: otherwise\n" }, { "code": null, "e": 2579, "s": 2310, "text": "K getKey() – Returns the key for the corresponding map entry.Syntax :K getKey()\nParameters :\n-------------\nReturns:\nK -> Returns the corresponding Key of a entry on which it is invoked\nException –IllegalSateException is thrown when entry has been removed from the map." }, { "code": null, "e": 2696, "s": 2579, "text": "K getKey()\nParameters :\n-------------\nReturns:\nK -> Returns the corresponding Key of a entry on which it is invoked\n" }, { "code": null, "e": 2708, "s": 2696, "text": "Exception –" }, { "code": null, "e": 2781, "s": 2708, "text": "IllegalSateException is thrown when entry has been removed from the map." }, { "code": null, "e": 2975, "s": 2781, "text": "V getValue() – Returns the value for the corresponding map entry.Syntax :V getValue()\nParameters :\n-------------\nReturns:\nV -> Returns the corresponding value of a entry on which it is invoked\n" }, { "code": null, "e": 3096, "s": 2975, "text": "V getValue()\nParameters :\n-------------\nReturns:\nV -> Returns the corresponding value of a entry on which it is invoked\n" }, { "code": null, "e": 3287, "s": 3096, "text": "int hashcode() – Returns the hashcode for the corresponding map entry.Syntax :int hashcode()\nParameters :\n-------------\nReturns:\nint -> Returns the hash-code of entry on which it is invoked\n" }, { "code": null, "e": 3400, "s": 3287, "text": "int hashcode()\nParameters :\n-------------\nReturns:\nint -> Returns the hash-code of entry on which it is invoked\n" }, { "code": null, "e": 4109, "s": 3400, "text": "V setValue(V v) – Sets the value of the map with specified value vV setValue(V v)\nParameters :\nv -> Value which was earlier stored in the entry on which it is invoked\nReturns:\nint -> Returns the hash-code of a entry on which it is invokedException :ClassCastException is thrown if the class of the value ‘v’ is not a correct type for map.NullPointerException is thrown if ‘null’ is stored in ‘v’, and ‘null ’ is not supported by map.UnsupportedOperationException is thrown if we cannot manipulate the map or the put operation is not supported by the map.IllegalArgumetException is thrown If there is some problem with the argument i.e vIllegalStateException is thrown when entry has been removed from the map" }, { "code": null, "e": 4282, "s": 4109, "text": "V setValue(V v)\nParameters :\nv -> Value which was earlier stored in the entry on which it is invoked\nReturns:\nint -> Returns the hash-code of a entry on which it is invoked" }, { "code": null, "e": 4294, "s": 4282, "text": "Exception :" }, { "code": null, "e": 4384, "s": 4294, "text": "ClassCastException is thrown if the class of the value ‘v’ is not a correct type for map." }, { "code": null, "e": 4480, "s": 4384, "text": "NullPointerException is thrown if ‘null’ is stored in ‘v’, and ‘null ’ is not supported by map." }, { "code": null, "e": 4602, "s": 4480, "text": "UnsupportedOperationException is thrown if we cannot manipulate the map or the put operation is not supported by the map." }, { "code": null, "e": 4685, "s": 4602, "text": "IllegalArgumetException is thrown If there is some problem with the argument i.e v" }, { "code": null, "e": 4758, "s": 4685, "text": "IllegalStateException is thrown when entry has been removed from the map" }, { "code": null, "e": 4971, "s": 4758, "text": "Set<Map.Entry> entrySet() – Returns the Set view of the entire map.Note : This is not a method of Map.entry interface but it is discussed here because this method is useful while working with Map.Entry interface." }, { "code": null, "e": 5101, "s": 4971, "text": "Set<Map.Entry> entrySet() \nParameters :\n---------------\nReturns:\nSet<Map.Entry> ->: Returns a Set containing the Map.Entry values" }, { "code": null, "e": 5153, "s": 5101, "text": "Program below demonstrate the working of Map.Entry:" }, { "code": "// Java Program to demonstrate the// methods of Map.Entry import java.util.LinkedHashMap;import java.util.Map;import java.util.Set; public class GFG { public static void main(String[] args) { // Create a LinkedHashMap LinkedHashMap<String,Integer> m = new LinkedHashMap<String, Integer>(); m.put(\"1 - Bedroom\" , 25000); m.put(\"2 - Bedroom\" , 50000); m.put(\"3 - Bedroom\" , 75000); m.put(\"1 - Bedroom - hall\", 65000); m.put(\"2 - Bedroom - hall\", 85000); m.put(\"3 - Bedroom - hall\", 105000); // Using entrySet() to get the entry's of the map Set<Map.Entry<String,Integer>> s = m.entrySet(); for (Map.Entry<String, Integer> it: s) { // Using the getKey to get key of the it element // Using the getValue to get value of the it element System.out.println(\"Before change of value = \" + it.getKey() + \" \" + it.getValue()); // Changing the value of 1 - Bedroom. double getRandom = Math.random() * 100000; int getRoundoff = (int) Math.round(getRandom); // Using setValue to change the value of the // map element it.setValue(getRoundoff); System.out.println(\"After change of value = \" + it.getKey() + \" \" + it.getValue()); } }}", "e": 6627, "s": 5153, "text": null }, { "code": null, "e": 6635, "s": 6627, "text": "Output:" }, { "code": null, "e": 7213, "s": 6635, "text": "Before change of value = 1 - Bedroom 25000\nAfter change of value = 1 - Bedroom 59475\nBefore change of value = 2 - Bedroom 50000\nAfter change of value = 2 - Bedroom 51650\nBefore change of value = 3 - Bedroom 75000\nAfter change of value = 3 - Bedroom 95200\nBefore change of value = 1 - Bedroom - hall 65000\nAfter change of value = 1 - Bedroom - hall 74112\nBefore change of value = 2 - Bedroom - hall 85000\nAfter change of value = 2 - Bedroom - hall 41490\nBefore change of value = 3 - Bedroom - hall 105000\nAfter change of value = 3 - Bedroom - hall 10902\n" }, { "code": null, "e": 7502, "s": 7213, "text": "This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to write@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7627, "s": 7502, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7644, "s": 7627, "text": "surinderdawra388" }, { "code": null, "e": 7649, "s": 7644, "text": "Java" }, { "code": null, "e": 7654, "s": 7649, "text": "Java" } ]
Node.js fs.chmod() Method
08 Oct, 2021 The fs.chmod() method is used to change the permissions of a given path. These permissions can be specified using string constants or octal numbers that correspond to their respective file modes. Note: The Windows platform only supports the changing of the write permission. It also does not support the distinction between the permissions of user, group, or others. Syntax: fs.chmod( path, mode, callback ) Parameters: This method accepts three parameters as mentioned above and described below: path: It is a string, Buffer or URL that denotes the path of the file of which the permission has to be changed. mode: It is string or octal integer constant that denotes the permission to be granted. The logical OR operator can be used to separate multiple permissions. callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails. err: It is an error that would be thrown if the method fails. Below examples illustrate the fs.chmod() method in Node.js: Example 1: This example shows the usage of octal integer constants to give the file permissions. // Node.js program to demonstrate the// fs.chmod() method // Import the filesystem moduleconst fs = require('fs'); // Grant only read permission to userconsole.log("Granting only read access to user"); fs.chmod("example.txt", 0o400, () => { console.log("\nReading the file contents"); console.log(fs.readFileSync("example.txt", 'utf8')); console.log("\nTrying to write to file"); try { fs.writeFileSync('example.txt', "This file has now been edited."); } catch (e) { console.log("Error Code:", e.code); } // Grant both read and write permission to user console.log("\nGranting read and write access to user"); fs.chmod("example.txt", 0o600, () => { console.log("Trying to write to file"); fs.writeFileSync('example.txt', "This file has now been edited."); console.log("\nReading the file contents"); console.log(fs.readFileSync("example.txt", 'utf8')); });}); Output: Granting only read access to user Reading the file contents This is an example text file. Trying to write to file Error Code: EACCES Granting read and write access to user Trying to write to file Reading the file contents This file has now been edited. Example 2: This example shows the usage of string constants and OR operator to give the file permissions. // Node.js program to demonstrate the// fs.chmod() method // Import the filesystem moduleconst fs = require('fs'); // Grant only read permission to userconsole.log("Granting only read access to user");fs.chmod("example.txt", fs.constants.S_IRUSR, () => { // Reading the file console.log("File Contents:", fs.readFileSync("example.txt", 'utf8')); // Trying to write to file try { console.log("\nTrying to write to file"); fs.writeFileSync('example.txt', "This file now has been edited."); } catch (e) { console.log("Error Occurred, Error Code:", e.code); } // Granting both read and write permission console.log("\nGranting both read and write permission to user"); fs.chmod("example.txt", fs.constants.S_IRUSR | fs.constants.S_IWUSR, () => { // Check the file mode console.log("Current File Mode:", fs.statSync("example.txt").mode); console.log("Trying to write to file"); fs.writeFileSync('example.txt', "This file now has been edited."); console.log("File Contents:", fs.readFileSync("example.txt", 'utf8')); });}); Output: Granting only read access to user File Contents: This file now has been edited. Trying to write to file Error Occurred, Error Code: EACCES Granting both read and write permission to user Trying to write to file File Contents: This file now has been edited. Reference: https://nodejs.org/api/fs.html#fs_fs_chmod_path_mode_callback nidhi_biet Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 224, "s": 28, "text": "The fs.chmod() method is used to change the permissions of a given path. These permissions can be specified using string constants or octal numbers that correspond to their respective file modes." }, { "code": null, "e": 395, "s": 224, "text": "Note: The Windows platform only supports the changing of the write permission. It also does not support the distinction between the permissions of user, group, or others." }, { "code": null, "e": 403, "s": 395, "text": "Syntax:" }, { "code": null, "e": 436, "s": 403, "text": "fs.chmod( path, mode, callback )" }, { "code": null, "e": 525, "s": 436, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 638, "s": 525, "text": "path: It is a string, Buffer or URL that denotes the path of the file of which the permission has to be changed." }, { "code": null, "e": 796, "s": 638, "text": "mode: It is string or octal integer constant that denotes the permission to be granted. The logical OR operator can be used to separate multiple permissions." }, { "code": null, "e": 934, "s": 796, "text": "callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 996, "s": 934, "text": "err: It is an error that would be thrown if the method fails." }, { "code": null, "e": 1056, "s": 996, "text": "Below examples illustrate the fs.chmod() method in Node.js:" }, { "code": null, "e": 1153, "s": 1056, "text": "Example 1: This example shows the usage of octal integer constants to give the file permissions." }, { "code": "// Node.js program to demonstrate the// fs.chmod() method // Import the filesystem moduleconst fs = require('fs'); // Grant only read permission to userconsole.log(\"Granting only read access to user\"); fs.chmod(\"example.txt\", 0o400, () => { console.log(\"\\nReading the file contents\"); console.log(fs.readFileSync(\"example.txt\", 'utf8')); console.log(\"\\nTrying to write to file\"); try { fs.writeFileSync('example.txt', \"This file has now been edited.\"); } catch (e) { console.log(\"Error Code:\", e.code); } // Grant both read and write permission to user console.log(\"\\nGranting read and write access to user\"); fs.chmod(\"example.txt\", 0o600, () => { console.log(\"Trying to write to file\"); fs.writeFileSync('example.txt', \"This file has now been edited.\"); console.log(\"\\nReading the file contents\"); console.log(fs.readFileSync(\"example.txt\", 'utf8')); });});", "e": 2051, "s": 1153, "text": null }, { "code": null, "e": 2059, "s": 2051, "text": "Output:" }, { "code": null, "e": 2317, "s": 2059, "text": "Granting only read access to user\n\nReading the file contents\nThis is an example text file.\n\nTrying to write to file\nError Code: EACCES\n\nGranting read and write access to user\nTrying to write to file\n\nReading the file contents\nThis file has now been edited.\n" }, { "code": null, "e": 2423, "s": 2317, "text": "Example 2: This example shows the usage of string constants and OR operator to give the file permissions." }, { "code": "// Node.js program to demonstrate the// fs.chmod() method // Import the filesystem moduleconst fs = require('fs'); // Grant only read permission to userconsole.log(\"Granting only read access to user\");fs.chmod(\"example.txt\", fs.constants.S_IRUSR, () => { // Reading the file console.log(\"File Contents:\", fs.readFileSync(\"example.txt\", 'utf8')); // Trying to write to file try { console.log(\"\\nTrying to write to file\"); fs.writeFileSync('example.txt', \"This file now has been edited.\"); } catch (e) { console.log(\"Error Occurred, Error Code:\", e.code); } // Granting both read and write permission console.log(\"\\nGranting both read and write permission to user\"); fs.chmod(\"example.txt\", fs.constants.S_IRUSR | fs.constants.S_IWUSR, () => { // Check the file mode console.log(\"Current File Mode:\", fs.statSync(\"example.txt\").mode); console.log(\"Trying to write to file\"); fs.writeFileSync('example.txt', \"This file now has been edited.\"); console.log(\"File Contents:\", fs.readFileSync(\"example.txt\", 'utf8')); });});", "e": 3490, "s": 2423, "text": null }, { "code": null, "e": 3498, "s": 3490, "text": "Output:" }, { "code": null, "e": 3758, "s": 3498, "text": "Granting only read access to user\nFile Contents: This file now has been edited.\n\nTrying to write to file\nError Occurred, Error Code: EACCES\n\nGranting both read and write permission to user\nTrying to write to file\nFile Contents: This file now has been edited.\n" }, { "code": null, "e": 3831, "s": 3758, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_chmod_path_mode_callback" }, { "code": null, "e": 3842, "s": 3831, "text": "nidhi_biet" }, { "code": null, "e": 3860, "s": 3842, "text": "Node.js-fs-module" }, { "code": null, "e": 3868, "s": 3860, "text": "Node.js" }, { "code": null, "e": 3885, "s": 3868, "text": "Web Technologies" } ]
Flutter – Creating Dialog in using GetX Library
14 May, 2021 When we want to show anything in the form of the dialog then we can create this Dialog using the GetX library in Flutter. When we normally create a dialog in flutter then it uses context and builder to create a Dialog. This is not a good practice for a developer to create Dialogs using contexts and builders. To overcome this problem, we can create Dialog using GetX with simple code and very easy to create a dialog. It does not use context and builder to create Dialog. Follow the steps to create a Dialog in flutter using the GetX library: Create a new Flutter app: flutter create APP_NAME Add get under dependencies in pubspec.yaml file: Import get in main.dart import 'package:get/get.dart'; The constructor of Get.defaultDialog(): defaultDialog<T>({ String title = "Alert", TextStyle? titleStyle, Widget? content, void Function()? onConfirm, void Function()? onCancel, void Function()? onCustom, Color? cancelTextColor, Color? confirmTextColor, String? textConfirm, String? textCancel, String? textCustom, Widget? confirm, Widget? cancel, Widget? custom, Color? backgroundColor, bool barrierDismissible = true, Color? buttonColor, String middleText = "Dialog made in 3 lines of code", TextStyle? middleTextStyle, double radius = 20.0, List<Widget>? actions, Future<bool> Function()? onWillPop}) Let’s discuss some properties of Get.defaultDialog(): title: The title of the Dialog. By default, the title is “Alert”. titleStyle: The style given to the title text using TextStyle. content: The content given to the Dialog and should use Widget to give content. middleText: The middle text given to the Dialog. If we use content also then content widget data will be displayed. barrierDismissible: If we want to close the Dialog by clicking outside the dialog then its value should be true else false. By default, its value is true. middleTextStyle: The style given to the middle text using TextStyle. radius: The radius of the Dialog provided. By default, its value is 20. backgroundColor: The background color of the Dialog. The main.dart file: Dart import 'package:flutter/material.dart';import 'package:get/get.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return GetMaterialApp( title: 'Dialog Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Home(), debugShowCheckedModeBanner: false, ); }} class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Dialog'), centerTitle: true, backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( child: Text('Show Dialog'), onPressed: (){ Get.defaultDialog( ); }, ) ), ); }} Explanation: The first step is to create an app and run it. We have used GetMaterialApp instead of MaterialApp because we are building our app using GetX library. If we do not use GetMaterialApp then its functionalities will not work. Then we have created a Home class that is Stateless. Then we have created a Scaffold widget. In the body, create a button in the center. Create dialog using Get.defaultDialog() . We can add extra features to this default dialog like backgroundColor, the radius of dialog, middle text, barrierDismissible, etc. Output: Get.defaultDialog( title: "GeeksforGeeks", middleText: "Hello world!", backgroundColor: Colors.green, titleStyle: TextStyle(color: Colors.white), middleTextStyle: TextStyle(color: Colors.white), ); When the above code is executed, the output will be: Get.defaultDialog( title: "GeeksforGeeks", middleText: "Hello world!", backgroundColor: Colors.green, titleStyle: TextStyle(color: Colors.white), middleTextStyle: TextStyle(color: Colors.white), textConfirm: "Confirm", textCancel: "Cancel", cancelTextColor: Colors.white, confirmTextColor: Colors.white, buttonColor: Colors.red, barrierDismissible: false, radius: 50, content: Column( children: [ Container(child:Text("Hello 1")), Container(child:Text("Hello 2")), Container(child:Text("Hello 3")), ], ) ); When we execute the above code, the output will be: Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2021" }, { "code": null, "e": 527, "s": 54, "text": "When we want to show anything in the form of the dialog then we can create this Dialog using the GetX library in Flutter. When we normally create a dialog in flutter then it uses context and builder to create a Dialog. This is not a good practice for a developer to create Dialogs using contexts and builders. To overcome this problem, we can create Dialog using GetX with simple code and very easy to create a dialog. It does not use context and builder to create Dialog." }, { "code": null, "e": 598, "s": 527, "text": "Follow the steps to create a Dialog in flutter using the GetX library:" }, { "code": null, "e": 624, "s": 598, "text": "Create a new Flutter app:" }, { "code": null, "e": 648, "s": 624, "text": "flutter create APP_NAME" }, { "code": null, "e": 697, "s": 648, "text": "Add get under dependencies in pubspec.yaml file:" }, { "code": null, "e": 721, "s": 697, "text": "Import get in main.dart" }, { "code": null, "e": 752, "s": 721, "text": "import 'package:get/get.dart';" }, { "code": null, "e": 792, "s": 752, "text": "The constructor of Get.defaultDialog():" }, { "code": null, "e": 1377, "s": 792, "text": "defaultDialog<T>({\nString title = \"Alert\", \nTextStyle? titleStyle, \nWidget? content, \nvoid Function()? onConfirm, \nvoid Function()? onCancel, \nvoid Function()? onCustom, \nColor? cancelTextColor, \nColor? confirmTextColor, \nString? textConfirm, \nString? textCancel, \nString? textCustom, \nWidget? confirm, \nWidget? cancel, \nWidget? custom, \nColor? backgroundColor, \nbool barrierDismissible = true, \nColor? buttonColor, \nString middleText = \"Dialog made in 3 lines of code\", \nTextStyle? middleTextStyle, \ndouble radius = 20.0, \nList<Widget>? actions, \nFuture<bool> Function()? onWillPop})" }, { "code": null, "e": 1431, "s": 1377, "text": "Let’s discuss some properties of Get.defaultDialog():" }, { "code": null, "e": 1497, "s": 1431, "text": "title: The title of the Dialog. By default, the title is “Alert”." }, { "code": null, "e": 1560, "s": 1497, "text": "titleStyle: The style given to the title text using TextStyle." }, { "code": null, "e": 1640, "s": 1560, "text": "content: The content given to the Dialog and should use Widget to give content." }, { "code": null, "e": 1756, "s": 1640, "text": "middleText: The middle text given to the Dialog. If we use content also then content widget data will be displayed." }, { "code": null, "e": 1911, "s": 1756, "text": "barrierDismissible: If we want to close the Dialog by clicking outside the dialog then its value should be true else false. By default, its value is true." }, { "code": null, "e": 1980, "s": 1911, "text": "middleTextStyle: The style given to the middle text using TextStyle." }, { "code": null, "e": 2052, "s": 1980, "text": "radius: The radius of the Dialog provided. By default, its value is 20." }, { "code": null, "e": 2105, "s": 2052, "text": "backgroundColor: The background color of the Dialog." }, { "code": null, "e": 2125, "s": 2105, "text": "The main.dart file:" }, { "code": null, "e": 2130, "s": 2125, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:get/get.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return GetMaterialApp( title: 'Dialog Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Home(), debugShowCheckedModeBanner: false, ); }} class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Dialog'), centerTitle: true, backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( child: Text('Show Dialog'), onPressed: (){ Get.defaultDialog( ); }, ) ), ); }}", "e": 3001, "s": 2130, "text": null }, { "code": null, "e": 3014, "s": 3001, "text": "Explanation:" }, { "code": null, "e": 3061, "s": 3014, "text": "The first step is to create an app and run it." }, { "code": null, "e": 3236, "s": 3061, "text": "We have used GetMaterialApp instead of MaterialApp because we are building our app using GetX library. If we do not use GetMaterialApp then its functionalities will not work." }, { "code": null, "e": 3329, "s": 3236, "text": "Then we have created a Home class that is Stateless. Then we have created a Scaffold widget." }, { "code": null, "e": 3373, "s": 3329, "text": "In the body, create a button in the center." }, { "code": null, "e": 3415, "s": 3373, "text": "Create dialog using Get.defaultDialog() ." }, { "code": null, "e": 3546, "s": 3415, "text": "We can add extra features to this default dialog like backgroundColor, the radius of dialog, middle text, barrierDismissible, etc." }, { "code": null, "e": 3554, "s": 3546, "text": "Output:" }, { "code": null, "e": 3835, "s": 3554, "text": "Get.defaultDialog(\n title: \"GeeksforGeeks\",\n middleText: \"Hello world!\",\n backgroundColor: Colors.green,\n titleStyle: TextStyle(color: Colors.white),\n middleTextStyle: TextStyle(color: Colors.white),\n\n );" }, { "code": null, "e": 3888, "s": 3835, "text": "When the above code is executed, the output will be:" }, { "code": null, "e": 4689, "s": 3888, "text": "Get.defaultDialog(\n title: \"GeeksforGeeks\",\n middleText: \"Hello world!\",\n backgroundColor: Colors.green,\n titleStyle: TextStyle(color: Colors.white),\n middleTextStyle: TextStyle(color: Colors.white),\n textConfirm: \"Confirm\",\n textCancel: \"Cancel\",\n cancelTextColor: Colors.white,\n confirmTextColor: Colors.white,\n buttonColor: Colors.red,\n barrierDismissible: false,\n radius: 50,\n content: Column(\n children: [\n Container(child:Text(\"Hello 1\")),\n Container(child:Text(\"Hello 2\")),\n Container(child:Text(\"Hello 3\")),\n ],\n )\n );" }, { "code": null, "e": 4741, "s": 4689, "text": "When we execute the above code, the output will be:" }, { "code": null, "e": 4763, "s": 4741, "text": "Flutter UI-components" }, { "code": null, "e": 4768, "s": 4763, "text": "Dart" }, { "code": null, "e": 4776, "s": 4768, "text": "Flutter" } ]
C/C++ Tokens
03 Feb, 2022 A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows: KeywordsIdentifiersConstantsStringsSpecial SymbolsOperators Keywords Identifiers Constants Strings Special Symbols Operators 1.Keywords: Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords. However, you can specify the text to be substituted for keywords before compilation by using C/C++ preprocessor directives. C language supports 32 keywords which are given below: auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while While in C++ there are 31 additional keywords other than C Keywords they are: asm bool catch class const_cast delete dynamic_cast explicit export false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t 2.Identifiers: Identifiers are used as the general terminology for the naming of variables, functions and arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements. There are certain rules that should be followed while naming c identifiers: They must begin with a letter or underscore(_). They must consist of only letters, digits, or underscore. No other special character is allowed. It should not be a keyword. It must not contain white space. It should be up to 31 characters long as only the first 31 characters are significant. main: method name. a: variable name. 3.Constants: Constants are also like normal variables. But, the only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called literals. Constants may belong to any of the data type Syntax:const data_type variable_name; (or) const data_type *variable_name; Types of Constants: Integer constants – Example: 0, 1, 1218, 12482Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10Character constants -Example: ‘a’, ‘A’, ‘z’String constants -Example: “GeeksforGeeks” Integer constants – Example: 0, 1, 1218, 12482 Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184 Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10 Character constants -Example: ‘a’, ‘A’, ‘z’ String constants -Example: “GeeksforGeeks” 4.Strings: Strings are nothing but an array of characters ended with a null character (‘\0’). This null character indicates the end of the string. Strings are always enclosed in double-quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for String: char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’}; char string[20] = “geeksforgeeks”; char string [] = “geeksforgeeks”; when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value. When we declare char as “string[]”, memory space will be allocated as per the requirement during the execution of the program. 5.Special Symbols: The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose.[] () {}, ; * = # Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts. Parentheses(): These special symbols are used to indicate function calls and function parameters. Braces{}: These opening and ending curly braces mark the start and end of a block of code containing more than one executable statement. Comma (, ): It is used to separate more than one statements like for separating parameters in function calls. Colon(:): It is an operator that essentially invokes something called an initialization list. Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s why each individual statement must be ended with a semicolon. Asterisk (*): It is used to create a pointer variable and for the multiplication of variables. Assignment operator(=): It is used to assign values and for the logical operation validation. Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation. 6.Operators: Operators are symbols that trigger an action when applied to C variables and other objects. The data items on which operators act upon are called operands. Depending on the number of operands that an operator can act upon, operators can be classified as follows: Unary Operators: Those operators that require only a single operand to act upon are known as unary operators.For Example increment and decrement operators Binary Operators: Those operators that require two operands to act upon are called binary operators. Binary operators are classified into : Arithmetic operatorsRelational OperatorsLogical OperatorsAssignment OperatorsBitwise Operator Arithmetic operatorsRelational OperatorsLogical OperatorsAssignment OperatorsBitwise Operator Arithmetic operators Relational Operators Logical Operators Assignment Operators Bitwise Operator Ternary Operator: The operator that require three operands to act upon are called ternary operator. Conditional Operator(?) is also called ternary operator. Syntax: (Expression1)? expression2: expression3; This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. ashutoshjoshi1995 om_mishra vanshkushwka hitendrasinghpal3 pavannm1999 codeyash CBSE - Class 11 school-programming C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Feb, 2022" }, { "code": null, "e": 173, "s": 53, "text": "A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows: " }, { "code": null, "e": 233, "s": 173, "text": "KeywordsIdentifiersConstantsStringsSpecial SymbolsOperators" }, { "code": null, "e": 242, "s": 233, "text": "Keywords" }, { "code": null, "e": 254, "s": 242, "text": "Identifiers" }, { "code": null, "e": 264, "s": 254, "text": "Constants" }, { "code": null, "e": 272, "s": 264, "text": "Strings" }, { "code": null, "e": 288, "s": 272, "text": "Special Symbols" }, { "code": null, "e": 298, "s": 288, "text": "Operators" }, { "code": null, "e": 840, "s": 298, "text": "1.Keywords: Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords. However, you can specify the text to be substituted for keywords before compilation by using C/C++ preprocessor directives. C language supports 32 keywords which are given below: " }, { "code": null, "e": 1186, "s": 840, "text": "auto double int struct\nbreak else long switch\ncase enum register typedef\nchar extern return union\nconst float short unsigned\ncontinue for signed void\ndefault goto sizeof volatile\ndo if static while " }, { "code": null, "e": 1265, "s": 1186, "text": "While in C++ there are 31 additional keywords other than C Keywords they are: " }, { "code": null, "e": 1646, "s": 1265, "text": "asm bool catch class\nconst_cast delete dynamic_cast explicit \nexport false friend inline \nmutable namespace new operator \nprivate protected public reinterpret_cast\nstatic_cast template this throw\ntrue try typeid typename \nusing virtual wchar_t " }, { "code": null, "e": 2332, "s": 1646, "text": "2.Identifiers: Identifiers are used as the general terminology for the naming of variables, functions and arrays. These are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements. There are certain rules that should be followed while naming c identifiers: " }, { "code": null, "e": 2380, "s": 2332, "text": "They must begin with a letter or underscore(_)." }, { "code": null, "e": 2477, "s": 2380, "text": "They must consist of only letters, digits, or underscore. No other special character is allowed." }, { "code": null, "e": 2505, "s": 2477, "text": "It should not be a keyword." }, { "code": null, "e": 2538, "s": 2505, "text": "It must not contain white space." }, { "code": null, "e": 2625, "s": 2538, "text": "It should be up to 31 characters long as only the first 31 characters are significant." }, { "code": null, "e": 2644, "s": 2625, "text": "main: method name." }, { "code": null, "e": 2662, "s": 2644, "text": "a: variable name." }, { "code": null, "e": 2926, "s": 2662, "text": "3.Constants: Constants are also like normal variables. But, the only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called literals. Constants may belong to any of the data type" }, { "code": null, "e": 3023, "s": 2926, "text": "Syntax:const data_type variable_name; (or) const data_type *variable_name; Types of Constants: " }, { "code": null, "e": 3317, "s": 3023, "text": "Integer constants – Example: 0, 1, 1218, 12482Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10Character constants -Example: ‘a’, ‘A’, ‘z’String constants -Example: “GeeksforGeeks”" }, { "code": null, "e": 3364, "s": 3317, "text": "Integer constants – Example: 0, 1, 1218, 12482" }, { "code": null, "e": 3432, "s": 3364, "text": "Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184" }, { "code": null, "e": 3528, "s": 3432, "text": "Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10" }, { "code": null, "e": 3572, "s": 3528, "text": "Character constants -Example: ‘a’, ‘A’, ‘z’" }, { "code": null, "e": 3615, "s": 3572, "text": "String constants -Example: “GeeksforGeeks”" }, { "code": null, "e": 3898, "s": 3615, "text": "4.Strings: Strings are nothing but an array of characters ended with a null character (‘\\0’). This null character indicates the end of the string. Strings are always enclosed in double-quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for String: " }, { "code": null, "e": 3989, "s": 3898, "text": "char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\\0’};" }, { "code": null, "e": 4024, "s": 3989, "text": "char string[20] = “geeksforgeeks”;" }, { "code": null, "e": 4058, "s": 4024, "text": "char string [] = “geeksforgeeks”;" }, { "code": null, "e": 4164, "s": 4058, "text": "when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value." }, { "code": null, "e": 4291, "s": 4164, "text": "When we declare char as “string[]”, memory space will be allocated as per the requirement during the execution of the program." }, { "code": null, "e": 4450, "s": 4291, "text": "5.Special Symbols: The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose.[] () {}, ; * = # " }, { "code": null, "e": 4583, "s": 4450, "text": "Brackets[]: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts." }, { "code": null, "e": 4681, "s": 4583, "text": "Parentheses(): These special symbols are used to indicate function calls and function parameters." }, { "code": null, "e": 4818, "s": 4681, "text": "Braces{}: These opening and ending curly braces mark the start and end of a block of code containing more than one executable statement." }, { "code": null, "e": 4928, "s": 4818, "text": "Comma (, ): It is used to separate more than one statements like for separating parameters in function calls." }, { "code": null, "e": 5022, "s": 4928, "text": "Colon(:): It is an operator that essentially invokes something called an initialization list." }, { "code": null, "e": 5189, "s": 5022, "text": "Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s why each individual statement must be ended with a semicolon." }, { "code": null, "e": 5285, "s": 5189, "text": "Asterisk (*): It is used to create a pointer variable and for the multiplication of variables." }, { "code": null, "e": 5379, "s": 5285, "text": "Assignment operator(=): It is used to assign values and for the logical operation validation." }, { "code": null, "e": 5532, "s": 5379, "text": "Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation." }, { "code": null, "e": 5810, "s": 5532, "text": "6.Operators: Operators are symbols that trigger an action when applied to C variables and other objects. The data items on which operators act upon are called operands. Depending on the number of operands that an operator can act upon, operators can be classified as follows: " }, { "code": null, "e": 5965, "s": 5810, "text": "Unary Operators: Those operators that require only a single operand to act upon are known as unary operators.For Example increment and decrement operators" }, { "code": null, "e": 6199, "s": 5965, "text": "Binary Operators: Those operators that require two operands to act upon are called binary operators. Binary operators are classified into : Arithmetic operatorsRelational OperatorsLogical OperatorsAssignment OperatorsBitwise Operator" }, { "code": null, "e": 6293, "s": 6199, "text": "Arithmetic operatorsRelational OperatorsLogical OperatorsAssignment OperatorsBitwise Operator" }, { "code": null, "e": 6314, "s": 6293, "text": "Arithmetic operators" }, { "code": null, "e": 6335, "s": 6314, "text": "Relational Operators" }, { "code": null, "e": 6353, "s": 6335, "text": "Logical Operators" }, { "code": null, "e": 6374, "s": 6353, "text": "Assignment Operators" }, { "code": null, "e": 6391, "s": 6374, "text": "Bitwise Operator" }, { "code": null, "e": 6597, "s": 6391, "text": "Ternary Operator: The operator that require three operands to act upon are called ternary operator. Conditional Operator(?) is also called ternary operator. Syntax: (Expression1)? expression2: expression3;" }, { "code": null, "e": 6896, "s": 6597, "text": "This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 7023, "s": 6896, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7047, "s": 7029, "text": "ashutoshjoshi1995" }, { "code": null, "e": 7057, "s": 7047, "text": "om_mishra" }, { "code": null, "e": 7070, "s": 7057, "text": "vanshkushwka" }, { "code": null, "e": 7088, "s": 7070, "text": "hitendrasinghpal3" }, { "code": null, "e": 7100, "s": 7088, "text": "pavannm1999" }, { "code": null, "e": 7109, "s": 7100, "text": "codeyash" }, { "code": null, "e": 7125, "s": 7109, "text": "CBSE - Class 11" }, { "code": null, "e": 7144, "s": 7125, "text": "school-programming" }, { "code": null, "e": 7155, "s": 7144, "text": "C Language" }, { "code": null, "e": 7159, "s": 7155, "text": "C++" }, { "code": null, "e": 7163, "s": 7159, "text": "CPP" } ]
Difference between wait and sleep in Java
16 Jun, 2021 Sleep(): This Method is used to pause the execution of current thread for a specified time in Milliseconds. Here, Thread does not lose its ownership of the monitor and resume’s it’s execution Wait(): This method is defined in object class. It tells the calling thread (a.k.a Current Thread) to wait until another thread invoke’s the notify() or notifyAll() method for this object, The thread waits until it reobtains the ownership of the monitor and Resume’s Execution. Wait() Has Three Overloaded Methods: wait() wait(long timeout) wait(long timeout, int nanos) Sleep() Has Two Overloaded Methods: sleep(long millis)millis: milliseconds sleep(long millis,int nanos) nanos: Nanoseconds Example For Sleep Method: synchronized(monitor) { Thread.sleep(1000); Here Lock Is Held By The Current Thread //after 1000 milliseconds, current thread will wake up, or after we call that is interrupt() method } Example For wait Method: synchronized(monitor) { monitor.wait() Here Lock Is Released By Current Thread } Similarity Between Both wait() and sleep() Method: Both Make The Current Thread go Into the Not Runnable State.Both are Native Methods. Both Make The Current Thread go Into the Not Runnable State. Both are Native Methods. The Below Code Snippet For Calling wait() and sleep() Method: Java synchronized(monitor){ while(condition == true) { monitor.wait() //releases monitor lock } Thread.sleep(100); //puts current thread on Sleep } Program: Java // Java program to demonstrate the difference// between wait and sleep class GfG{ private static Object LOCK = new Object(); public static void main(String[] args) throws InterruptedException { Thread.sleep(1000); System.out.println("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); synchronized (LOCK) { LOCK.wait(1000); System.out.println("Object '" + LOCK + "' is woken after" + " waiting for 1 second"); }}} Thread 'main' is woken after sleeping for 1 second Object 'java.lang.Object@1d81eb93' is woken after waiting for 1 second scraptrashscrap arorakashish0911 Java-Multithreading Picked Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2021" }, { "code": null, "e": 244, "s": 52, "text": "Sleep(): This Method is used to pause the execution of current thread for a specified time in Milliseconds. Here, Thread does not lose its ownership of the monitor and resume’s it’s execution" }, { "code": null, "e": 522, "s": 244, "text": "Wait(): This method is defined in object class. It tells the calling thread (a.k.a Current Thread) to wait until another thread invoke’s the notify() or notifyAll() method for this object, The thread waits until it reobtains the ownership of the monitor and Resume’s Execution." }, { "code": null, "e": 559, "s": 522, "text": "Wait() Has Three Overloaded Methods:" }, { "code": null, "e": 566, "s": 559, "text": "wait()" }, { "code": null, "e": 585, "s": 566, "text": "wait(long timeout)" }, { "code": null, "e": 615, "s": 585, "text": "wait(long timeout, int nanos)" }, { "code": null, "e": 651, "s": 615, "text": "Sleep() Has Two Overloaded Methods:" }, { "code": null, "e": 690, "s": 651, "text": "sleep(long millis)millis: milliseconds" }, { "code": null, "e": 738, "s": 690, "text": "sleep(long millis,int nanos) nanos: Nanoseconds" }, { "code": null, "e": 764, "s": 738, "text": "Example For Sleep Method:" }, { "code": null, "e": 951, "s": 764, "text": "synchronized(monitor)\n{\nThread.sleep(1000); Here Lock Is Held By The Current Thread\n//after 1000 milliseconds, current thread will wake up, or after we call that is interrupt() method\n}" }, { "code": null, "e": 976, "s": 951, "text": "Example For wait Method:" }, { "code": null, "e": 1059, "s": 976, "text": "synchronized(monitor)\n{\nmonitor.wait() Here Lock Is Released By Current Thread \n}" }, { "code": null, "e": 1111, "s": 1059, "text": "Similarity Between Both wait() and sleep() Method: " }, { "code": null, "e": 1196, "s": 1111, "text": "Both Make The Current Thread go Into the Not Runnable State.Both are Native Methods." }, { "code": null, "e": 1257, "s": 1196, "text": "Both Make The Current Thread go Into the Not Runnable State." }, { "code": null, "e": 1282, "s": 1257, "text": "Both are Native Methods." }, { "code": null, "e": 1344, "s": 1282, "text": "The Below Code Snippet For Calling wait() and sleep() Method:" }, { "code": null, "e": 1349, "s": 1344, "text": "Java" }, { "code": "synchronized(monitor){ while(condition == true) { monitor.wait() //releases monitor lock } Thread.sleep(100); //puts current thread on Sleep }", "e": 1515, "s": 1349, "text": null }, { "code": null, "e": 1524, "s": 1515, "text": "Program:" }, { "code": null, "e": 1529, "s": 1524, "text": "Java" }, { "code": "// Java program to demonstrate the difference// between wait and sleep class GfG{ private static Object LOCK = new Object(); public static void main(String[] args) throws InterruptedException { Thread.sleep(1000); System.out.println(\"Thread '\" + Thread.currentThread().getName() + \"' is woken after sleeping for 1 second\"); synchronized (LOCK) { LOCK.wait(1000); System.out.println(\"Object '\" + LOCK + \"' is woken after\" + \" waiting for 1 second\"); }}}", "e": 2042, "s": 1529, "text": null }, { "code": null, "e": 2167, "s": 2045, "text": "Thread 'main' is woken after sleeping for 1 second\nObject 'java.lang.Object@1d81eb93' is woken after waiting for 1 second" }, { "code": null, "e": 2185, "s": 2169, "text": "scraptrashscrap" }, { "code": null, "e": 2202, "s": 2185, "text": "arorakashish0911" }, { "code": null, "e": 2222, "s": 2202, "text": "Java-Multithreading" }, { "code": null, "e": 2229, "s": 2222, "text": "Picked" }, { "code": null, "e": 2248, "s": 2229, "text": "Difference Between" }, { "code": null, "e": 2253, "s": 2248, "text": "Java" }, { "code": null, "e": 2258, "s": 2253, "text": "Java" } ]
Remove shadow of an element in Bootstrap 4
Use the .shadow-none class in Bootstrap to remove shadow. You can try to run the following code to remove an element’s shadow − Live Demo <!DOCTYPE html> <html lang = "en"> <head> <title>Bootstrap Example</title> <meta charset = "utf-8"> <meta name = "viewport" content="width = device-width, initial-scale = 1"> <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h1>Learning</h1> <p>Learn Tutorials for free</p> <div class = "shadow-none p-4 mb-4 bg-light">Play Quiz and check your knowledge</div> </div> </body> </html>
[ { "code": null, "e": 1120, "s": 1062, "text": "Use the .shadow-none class in Bootstrap to remove shadow." }, { "code": null, "e": 1190, "s": 1120, "text": "You can try to run the following code to remove an element’s shadow −" }, { "code": null, "e": 1200, "s": 1190, "text": "Live Demo" }, { "code": null, "e": 1950, "s": 1200, "text": "<!DOCTYPE html>\n<html lang = \"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content=\"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h1>Learning</h1>\n <p>Learn Tutorials for free</p>\n <div class = \"shadow-none p-4 mb-4 bg-light\">Play Quiz and check your knowledge</div>\n </div>\n </body>\n</html>" } ]
Create temporary file in specified directory in Java
A temporary file in the specified directory can be created using the method java.io.File.createTempFile(). This method requires three parameters i.e. the prefix to define the file name, the suffix to define the file extension and the directory in which the temporary file is to be created. It also returns the abstract path name for the temporary file created. A program that demonstrates this is given as follows − import java.io.File; public class Demo { public static void main(String[] args) throws Exception { File directory = new File("C:/JavaProgram"); File file = File.createTempFile("temp", ".java", directory); System.out.println(file.getAbsolutePath()); file.deleteOnExit(); } } The output of the above program is as follows − C:\JavaProgram\temp1333744144499445058.java Now let us understand the above program. A temporary file in the specified directory is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows − File directory = new File("C:/JavaProgram"); File file = File.createTempFile("temp", ".java", directory); System.out.println(file.getAbsolutePath()); file.deleteOnExit();
[ { "code": null, "e": 1423, "s": 1062, "text": "A temporary file in the specified directory can be created using the method java.io.File.createTempFile(). This method requires three parameters i.e. the prefix to define the file name, the suffix to define the file extension and the directory in which the temporary file is to be created. It also returns the abstract path name for the temporary file created." }, { "code": null, "e": 1478, "s": 1423, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1784, "s": 1478, "text": "import java.io.File;\npublic class Demo { \n public static void main(String[] args) throws Exception {\n File directory = new File(\"C:/JavaProgram\");\n File file = File.createTempFile(\"temp\", \".java\", directory);\n System.out.println(file.getAbsolutePath());\n file.deleteOnExit();\n }\n}" }, { "code": null, "e": 1832, "s": 1784, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1876, "s": 1832, "text": "C:\\JavaProgram\\temp1333744144499445058.java" }, { "code": null, "e": 1917, "s": 1876, "text": "Now let us understand the above program." }, { "code": null, "e": 2219, "s": 1917, "text": "A temporary file in the specified directory is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows −" }, { "code": null, "e": 2390, "s": 2219, "text": "File directory = new File(\"C:/JavaProgram\");\nFile file = File.createTempFile(\"temp\", \".java\", directory);\nSystem.out.println(file.getAbsolutePath());\nfile.deleteOnExit();" } ]
Get PID of Browser launched by Selenium.
We can PID of browsers launched by Selenium webdriver. First of all, we have to create an object of the webdriver. Next, for example, to launch the browser in the Firefox browser, we have to take the help of webdriver.Firefox() class. The location of the geckodriver.exe file is passed as a parameter to that class. This is done by setting the path to executable_path property. Then, the browser shall be launched with the get method. Finally, to obtain the PID of the browser, we shall use the driver.service.process.id method. s = driver.service.process.pid from selenium import webdriver #path of geckodriver.exe driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") #launch browser driver.get ("https://www.tutorialspoint.com/index.htm") #obtain PID of browser s = driver.service.process.pid print(s) #close browser driver.close()
[ { "code": null, "e": 1297, "s": 1062, "text": "We can PID of browsers launched by Selenium webdriver. First of all, we have to create an object of the webdriver. Next, for example, to launch the browser in the Firefox browser, we have to take the help of webdriver.Firefox() class." }, { "code": null, "e": 1497, "s": 1297, "text": "The location of the geckodriver.exe file is passed as a parameter to that class. This is done by setting the path to executable_path property. Then, the browser shall be launched with the get method." }, { "code": null, "e": 1591, "s": 1497, "text": "Finally, to obtain the PID of the browser, we shall use the driver.service.process.id method." }, { "code": null, "e": 1622, "s": 1591, "text": "s = driver.service.process.pid" }, { "code": null, "e": 1909, "s": 1622, "text": "from selenium import webdriver\n#path of geckodriver.exe\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\n#launch browser\ndriver.get (\"https://www.tutorialspoint.com/index.htm\")\n#obtain PID of browser\ns = driver.service.process.pid\nprint(s)\n#close browser\ndriver.close()" } ]
C/C++ Program for Median of two sorted arrays of same size?
Here we will see how to get the median of two sorted array of the same size. We will use C++ STL to store array elements. After getting two arrays, we will merge them into one. As two arrays of same size are merged, then the final array will always hold even number of elements. We need to take two middle elements, then get the average of them for the median. Begin arr3 := array after merging arr1 and arr2 sort arr3 len := length of arr3 mid := len/2 median := (arr3[mid] + arr3[mid-1])/2 return median End Live Demo #include<iostream> #include<vector> #include<algorithm> using namespace std; float median(vector<int> arr1, vector<int> arr2) { vector arr3(arr1.size() + arr2.size()); merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin()); sort(arr3.begin(), arr3.end()); int len = arr3.size(); int mid = len/2; return float(arr3[mid] + arr3[mid-1])/2; } main() { vector<int> arr1 = {1, 3, 4, 6, 7}; vector<int> arr2 = {4, 5, 7, 8, 9}; cout << "Median: " << median(arr1, arr2); } Median: 5.5
[ { "code": null, "e": 1423, "s": 1062, "text": "Here we will see how to get the median of two sorted array of the same size. We will use C++ STL to store array elements. After getting two arrays, we will merge them into one. As two arrays of same size are merged, then the final array will always hold even number of elements. We need to take two middle elements, then get the average of them for the median." }, { "code": null, "e": 1590, "s": 1423, "text": "Begin\n arr3 := array after merging arr1 and arr2\n sort arr3\n len := length of arr3\n mid := len/2\n median := (arr3[mid] + arr3[mid-1])/2\n return median\nEnd" }, { "code": null, "e": 1601, "s": 1590, "text": " Live Demo" }, { "code": null, "e": 2109, "s": 1601, "text": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nfloat median(vector<int> arr1, vector<int> arr2) {\n vector arr3(arr1.size() + arr2.size());\n merge(arr1.begin(), arr1.end(), arr2.begin(), arr2.end(), arr3.begin());\n sort(arr3.begin(), arr3.end());\n int len = arr3.size();\n int mid = len/2;\n return float(arr3[mid] + arr3[mid-1])/2;\n}\nmain() {\n vector<int> arr1 = {1, 3, 4, 6, 7};\n vector<int> arr2 = {4, 5, 7, 8, 9};\n cout << \"Median: \" << median(arr1, arr2);\n}" }, { "code": null, "e": 2121, "s": 2109, "text": "Median: 5.5" } ]
k-th smallest element in BST | Practice | GeeksforGeeks
Given a BST and an integer K. Find the Kth Smallest element in the BST. Example 1: Input: 2 / \ 1 3 K = 2 Output: 2 Example 2: Input: 2 / \ 1 3 K = 5 Output: -1 Your Task: You don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and return the Kth smallest element in the BST, if no such element exists return -1. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1<=Number of nodes<=100000 -1 amarrajsmart1971 week ago void inorder(Node*root,vector<int> &v) { if(!root) { return ; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } int KthSmallestElement(Node *root, int K) { // add code here. vector<int> v; inorder(root,v); if(K>v.size()) return -1; else return v[K-1]; } 0 joyrockok2 weeks ago class Solution {int orderCnt=0;int resultValue=-1;public int KthSmallestElement(Node root, int K) { if(root == null) return -1; getElement(root.left, K); if(root != null) orderCnt++; if(orderCnt == K) return root.data; getElement(root.right, K); if(resultValue == -1) return -1; else return resultValue;}public void getElement(Node node, int K) { if(node == null) return; getElement(node.left, K); if(node != null) orderCnt++; if(orderCnt == K) { resultValue = node.data; return; } getElement(node.right, K);} } 0 adarshgupta4012 weeks ago OPtimal, Easy Java Soln using itertaive inOrder Traversal class Solution { public int KthSmallestElement(Node root, int k) { Stack<Node> st = new Stack<>(); Node node = root; int count = 0; while( true ){ if(node != null){ st.push(node); node = node.left; }else{ if(st.isEmpty()) break; node = st.peek(); st.pop(); count++; if(count == k) return node.data; node = node.right; } } return -1; } } 0 amishasahu3282 weeks ago void inorder(Node* root, int &k, int &ans) { if(root == NULL) return; inorder(root -> left, k, ans); k--; if(k == 0) { ans = root -> data; return ; } inorder(root -> right, k, ans); } int KthSmallestElement(Node *root, int K) { // add code here. int ans = -1; inorder(root, K, ans); return ans; } 0 inspiringseeds3 weeks ago void solve(Node *root, int &k,int &ans) { if(root == NULL) { return ; } solve(root->left,k,ans); k--; if(k == 0) { ans = root->data; return ; } solve(root->right,k,ans); } // Return the Kth smallest element in the given BST int KthSmallestElement(Node *root, int K) { // add code here. int ans = -1; solve(root,K,ans); return ans; } 0 abhibarkade1113 weeks ago public int KthSmallestElement(Node root, int K) { // Write your code here PriorityQueue<Integer> pq = new PriorityQueue<>(); solve(root,pq); if(pq.size()<K){ return -1; } else{ while(K!=1){ pq.poll(); K--; } } return pq.peek(); } public void solve(Node root, PriorityQueue<Integer> pq){ if(root==null){ return; } pq.add(root.data); solve(root.left, pq); solve(root.right, pq); } 0 chhitizgoyal3 weeks ago Java Solution. ArrayList<Integer> list = new ArrayList<>(); public int KthSmallestElement(Node root, int k) { if(root==null){ return -1; } KthSmallestElement(root.left, k); list.add(root.data); KthSmallestElement(root.right, k); if(k>list.size()){ return -1; } return list.get(k-1); } 0 aryankhatana353 weeks ago C++ sol int solve(Node *root,int &i ,int K){ if(root==NULL){ return -1; } // L int left=solve(root->left,i,K); if(left!=-1){ return left; } // N i++; if(i==K){ return root->data; } // R int right=solve(root->right,i,K); } int KthSmallestElement(Node *root, int K) { // add code here. int i=0; int ans=solve(root,i,K); return ans; }}; 0 sergiojacksonramos3 weeks ago // Simple Java solution using Inorer traversal ONLY ArrayList<Integer> arr; // Return the Kth smallest element in the given BST public int KthSmallestElement(Node root, int K) { // Write your code here arr = new ArrayList<>(); inorder(root, arr); if (arr.size() < K) return -1; return arr.get(K-1); } static void inorder(Node root, ArrayList<Integer> arr) { if (root == null) return; inorder(root.left, arr); arr.add(root.data); inorder(root.right, arr); } 0 sandeep55214 weeks ago C++ Morris Traversal Solution using O(1) space int KthSmallestElement(Node *root, int k) { Node *cur=root; int i=1; while(cur){ if(!(cur->left)){ if(i==k) return cur->data; i++; cur=cur->right; } else{ Node *p=cur->left; while(p->right and p->right!=cur) p=p->right; if(!p->right){ p->right=cur; cur=cur->left; } if(p->right==cur){ if(i==k) return cur->data; i++; cur=cur->right; p->right=NULL; } } } return -1; } 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": 311, "s": 238, "text": "Given a BST and an integer K. Find the Kth Smallest element in the BST. " }, { "code": null, "e": 322, "s": 311, "text": "Example 1:" }, { "code": null, "e": 375, "s": 322, "text": "Input:\n 2\n / \\\n 1 3\nK = 2\nOutput: 2\n" }, { "code": null, "e": 386, "s": 375, "text": "Example 2:" }, { "code": null, "e": 443, "s": 386, "text": "Input:\n 2\n / \\\n 1 3\nK = 5\nOutput: -1" }, { "code": null, "e": 704, "s": 445, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and return the Kth smallest element in the BST, if no such element exists return -1." }, { "code": null, "e": 809, "s": 704, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n\nConstraints:\n1<=Number of nodes<=100000" }, { "code": null, "e": 814, "s": 811, "text": "-1" }, { "code": null, "e": 840, "s": 814, "text": "amarrajsmart1971 week ago" }, { "code": null, "e": 1220, "s": 840, "text": " void inorder(Node*root,vector<int> &v) { if(!root) { return ; } inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } int KthSmallestElement(Node *root, int K) { // add code here. vector<int> v; inorder(root,v); if(K>v.size()) return -1; else return v[K-1]; }" }, { "code": null, "e": 1222, "s": 1220, "text": "0" }, { "code": null, "e": 1243, "s": 1222, "text": "joyrockok2 weeks ago" }, { "code": null, "e": 1372, "s": 1243, "text": "class Solution {int orderCnt=0;int resultValue=-1;public int KthSmallestElement(Node root, int K) { if(root == null) return -1;" }, { "code": null, "e": 1494, "s": 1372, "text": " getElement(root.left, K); if(root != null) orderCnt++; if(orderCnt == K) return root.data; getElement(root.right, K);" }, { "code": null, "e": 1628, "s": 1494, "text": " if(resultValue == -1) return -1; else return resultValue;}public void getElement(Node node, int K) { if(node == null) return;" }, { "code": null, "e": 1770, "s": 1628, "text": " getElement(node.left, K); if(node != null) orderCnt++; if(orderCnt == K) { resultValue = node.data; return; } getElement(node.right, K);}" }, { "code": null, "e": 1775, "s": 1772, "text": "} " }, { "code": null, "e": 1777, "s": 1775, "text": "0" }, { "code": null, "e": 1803, "s": 1777, "text": "adarshgupta4012 weeks ago" }, { "code": null, "e": 1861, "s": 1803, "text": "OPtimal, Easy Java Soln using itertaive inOrder Traversal" }, { "code": null, "e": 2435, "s": 1861, "text": "class Solution {\n public int KthSmallestElement(Node root, int k) {\n Stack<Node> st = new Stack<>();\n Node node = root;\n int count = 0;\n while( true ){\n if(node != null){\n st.push(node);\n node = node.left;\n }else{\n if(st.isEmpty()) break;\n node = st.peek();\n st.pop();\n count++;\n if(count == k) return node.data;\n \n node = node.right;\n }\n }\n return -1;\n }\n}" }, { "code": null, "e": 2437, "s": 2435, "text": "0" }, { "code": null, "e": 2462, "s": 2437, "text": "amishasahu3282 weeks ago" }, { "code": null, "e": 2927, "s": 2462, "text": "void inorder(Node* root, int &k, int &ans)\n {\n if(root == NULL)\n return;\n \n inorder(root -> left, k, ans);\n \n k--;\n \n if(k == 0)\n {\n ans = root -> data;\n return ;\n }\n \n inorder(root -> right, k, ans);\n }\n int KthSmallestElement(Node *root, int K) {\n // add code here.\n int ans = -1;\n inorder(root, K, ans);\n return ans;\n }" }, { "code": null, "e": 2929, "s": 2927, "text": "0" }, { "code": null, "e": 2955, "s": 2929, "text": "inspiringseeds3 weeks ago" }, { "code": null, "e": 3414, "s": 2955, "text": "void solve(Node *root, int &k,int &ans) { if(root == NULL) { return ; } solve(root->left,k,ans); k--; if(k == 0) { ans = root->data; return ; } solve(root->right,k,ans); } // Return the Kth smallest element in the given BST int KthSmallestElement(Node *root, int K) { // add code here. int ans = -1; solve(root,K,ans); return ans; }" }, { "code": null, "e": 3416, "s": 3414, "text": "0" }, { "code": null, "e": 3442, "s": 3416, "text": "abhibarkade1113 weeks ago" }, { "code": null, "e": 3980, "s": 3442, "text": "public int KthSmallestElement(Node root, int K) { // Write your code here PriorityQueue<Integer> pq = new PriorityQueue<>(); solve(root,pq); if(pq.size()<K){ return -1; } else{ while(K!=1){ pq.poll(); K--; } } return pq.peek(); } public void solve(Node root, PriorityQueue<Integer> pq){ if(root==null){ return; } pq.add(root.data); solve(root.left, pq); solve(root.right, pq); }" }, { "code": null, "e": 3982, "s": 3980, "text": "0" }, { "code": null, "e": 4006, "s": 3982, "text": "chhitizgoyal3 weeks ago" }, { "code": null, "e": 4021, "s": 4006, "text": "Java Solution." }, { "code": null, "e": 4368, "s": 4021, "text": "ArrayList<Integer> list = new ArrayList<>(); public int KthSmallestElement(Node root, int k) { if(root==null){ return -1; } KthSmallestElement(root.left, k); list.add(root.data); KthSmallestElement(root.right, k); if(k>list.size()){ return -1; } return list.get(k-1); }" }, { "code": null, "e": 4370, "s": 4368, "text": "0" }, { "code": null, "e": 4396, "s": 4370, "text": "aryankhatana353 weeks ago" }, { "code": null, "e": 4405, "s": 4396, "text": "C++ sol " }, { "code": null, "e": 4895, "s": 4407, "text": "int solve(Node *root,int &i ,int K){ if(root==NULL){ return -1; } // L int left=solve(root->left,i,K); if(left!=-1){ return left; } // N i++; if(i==K){ return root->data; } // R int right=solve(root->right,i,K); } int KthSmallestElement(Node *root, int K) { // add code here. int i=0; int ans=solve(root,i,K); return ans; }};" }, { "code": null, "e": 4897, "s": 4895, "text": "0" }, { "code": null, "e": 4927, "s": 4897, "text": "sergiojacksonramos3 weeks ago" }, { "code": null, "e": 5481, "s": 4927, "text": "// Simple Java solution using Inorer traversal ONLY\nArrayList<Integer> arr;\n // Return the Kth smallest element in the given BST\n public int KthSmallestElement(Node root, int K) {\n // Write your code here\n arr = new ArrayList<>();\n inorder(root, arr);\n if (arr.size() < K) return -1;\n return arr.get(K-1);\n }\n \n static void inorder(Node root, ArrayList<Integer> arr) {\n if (root == null) return;\n inorder(root.left, arr);\n arr.add(root.data);\n inorder(root.right, arr);\n }" }, { "code": null, "e": 5483, "s": 5481, "text": "0" }, { "code": null, "e": 5506, "s": 5483, "text": "sandeep55214 weeks ago" }, { "code": null, "e": 5553, "s": 5506, "text": "C++ Morris Traversal Solution using O(1) space" }, { "code": null, "e": 6251, "s": 5553, "text": "int KthSmallestElement(Node *root, int k) {\n Node *cur=root;\n int i=1;\n while(cur){\n if(!(cur->left)){\n if(i==k) return cur->data;\n i++;\n cur=cur->right;\n }\n else{\n Node *p=cur->left;\n while(p->right and p->right!=cur) p=p->right;\n if(!p->right){\n p->right=cur;\n cur=cur->left;\n }\n if(p->right==cur){\n if(i==k) return cur->data;\n i++;\n cur=cur->right;\n p->right=NULL;\n }\n }\n }\n return -1;\n }" }, { "code": null, "e": 6397, "s": 6251, "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": 6433, "s": 6397, "text": " Login to access your submissions. " }, { "code": null, "e": 6443, "s": 6433, "text": "\nProblem\n" }, { "code": null, "e": 6453, "s": 6443, "text": "\nContest\n" }, { "code": null, "e": 6516, "s": 6453, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6664, "s": 6516, "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": 6872, "s": 6664, "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": 6978, "s": 6872, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Viruses - From Newbie to pro - GeeksforGeeks
25 Nov, 2020 NOTE: Using an online compiler is not going to work here. Please install Python 2.7x and cv2, argparse modules to actually try out this example. Heya friends! Welcome back! Before continuing on with Malicious Logic, I request you to have a look at this great and informative article Worms, Viruses and Beyond!! Now, this article will focus more on applications than theory of computer viruses, worms, and Trojan horses. But, please note that this article is meant to be used for educational purposes only.I, in no way, promote the usage of viruses, worms, or trojan horses to attack computer systems and causing damage. Malicious logic is a set of instructions (basically a program) that causes the violation of a security policy of a website/program/application, etc. UNIX Script cp /bin/sh /tmp/.xxsh chmod u+s,o+x /tmp/.xxsh rm ./ls ls $* In this example, we are assuming that “.” is in the path environment and the script has been named ls and is placed in the directory. Analysing the script This script creates a copy of the UNIX Shell that is setuid of the user executing this program. To understand setuid programs, we first need to understand how User Identity is stored in a UNIX OS. In UNIX OS, user identity is usually represented as an integer between 0 and generally, 65,535. This number is also referred to as UID (Unique Identification Number). Now, what setuid programs do is that they create processes with UID of the owner and not of a third person executing the program. This means, that an executor will have the rights of the owner... This in itself is a possible vulnerability. Coming back to our script, so a setuid copy of the UNIX shell was created. Later on, this program is deleted, and then the correct ls command (for listing the files and folders present in the current working directory) is executed. Trojan Horses Go back to the previous script... Suppose if someone (root) typed: cp /bin/sh /tmp/.xxsh chmod o+s,w+x /tmp.xxsh If the script was typed deliberately, then it will result in a Trojan Horse. Virus – A basic format Most of the computer viruses follow the following basic script: Beginvirus if spread-condition TRUE then begin for the target files begin if target affected TRUE then begin Determine where to place virus instructions Copy the virus instructions Modify target to spread the virus later End if End for End if Perform some other instruction(s) //Optional Go back to beginning Endvirus Basically, every computer virus has two phases – Insertion phase – in this phase, the virus inserts itself into the target.Execution phase- in this phase, the virus performs some actions. Insertion phase – in this phase, the virus inserts itself into the target. Execution phase- in this phase, the virus performs some actions. Let’s take a look at a real virus in Python. Now this is not an actual virus which will cause corruption files, deletion of system files, etc. but just a simple harmless virus. #!/usr/bin/python import os, datetime, inspect DATA_TO_INSERT = "GEEKSFORGEEKS" #search for target files in pathdef search(path): filestoinfect = [] filelist = os.listdir(path) for filename in filelist: #If it is a folder if os.path.isdir(path+"/"+filename): filestoinfect.extend(search(path+"/"+filename)) #If it is a python script -> Infect it elif filename[-3:] == ".py": #default value infected = False for line in open(path+"/"+filename): if DATA_TO_INSERT in line: infected = True break if infected == False: filestoinfect.append(path+"/"+filename) return filestoinfect #changes to be made in the target file def infect(filestoinfect): target_file = inspect.currentframe().f_code.co_filename virus = open(os.path.abspath(target_file)) virusstring = "" for i,line in enumerate(virus): if i>=0 and i <41: virusstring += line virus.close for fname in filestoinfect: f = open(fname) temp = f.read() f.close() f = open(fname,"w") f.write(virusstring + temp) f.close() #Not required actually def explode(): if datetime.datetime.now().month == 4 and datetime.datetime.now().day == 1: print ("HAPPY APRIL FOOL'S DAY!!")filestoinfect = search(os.path.abspath("")) infect(filestoinfect) explode() Now, this is quite a safe virus But, the basic format and working is the same. Also, there are various types of computer virus – Boot sector infectors, executable infectors, multipartite virus, TSR virus, Stealth virus, Encrypted virus, polymorphic virus, macro virus. Now, I won’t go into the details and will just stop here. That’s all from my side! About the author: Vishwesh Shrimali is an Undergraduate Mechanical Engineering student at BITS Pilani. He fulfils about all the requirements not taught in his branch- white hat hacker, network security operator, and an ex – Competitive Programmer. As a firm believer in power of Python, his majority work has been in the same language. Whenever he get some time apart from programming, attending classes, watching CSI Cyber, he go for a long walk and play guitar in silence. His motto of life is – “Enjoy your life, ‘cause it’s worth enjoying!” If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. GBlog Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar Top 10 Angular Libraries For Web Developers Working with csv files in Python Types of Software Testing SDE SHEET - A Complete Guide for SDE Preparation XML parsing in Python Working with zip files in Python Python | Simple GUI calculator using Tkinter Implementing Web Scraping in Python with BeautifulSoup
[ { "code": null, "e": 24576, "s": 24548, "text": "\n25 Nov, 2020" }, { "code": null, "e": 24721, "s": 24576, "text": "NOTE: Using an online compiler is not going to work here. Please install Python 2.7x and cv2, argparse modules to actually try out this example." }, { "code": null, "e": 24887, "s": 24721, "text": "Heya friends! Welcome back! Before continuing on with Malicious Logic, I request you to have a look at this great and informative article Worms, Viruses and Beyond!!" }, { "code": null, "e": 24996, "s": 24887, "text": "Now, this article will focus more on applications than theory of computer viruses, worms, and Trojan horses." }, { "code": null, "e": 25196, "s": 24996, "text": "But, please note that this article is meant to be used for educational purposes only.I, in no way, promote the usage of viruses, worms, or trojan horses to attack computer systems and causing damage." }, { "code": null, "e": 25345, "s": 25196, "text": "Malicious logic is a set of instructions (basically a program) that causes the violation of a security policy of a website/program/application, etc." }, { "code": null, "e": 25357, "s": 25345, "text": "UNIX Script" }, { "code": null, "e": 25435, "s": 25357, "text": " cp /bin/sh /tmp/.xxsh\n chmod u+s,o+x /tmp/.xxsh\n rm ./ls\n ls $*\n" }, { "code": null, "e": 25569, "s": 25435, "text": "In this example, we are assuming that “.” is in the path environment and the script has been named ls and is placed in the directory." }, { "code": null, "e": 25590, "s": 25569, "text": "Analysing the script" }, { "code": null, "e": 25787, "s": 25590, "text": "This script creates a copy of the UNIX Shell that is setuid of the user executing this program. To understand setuid programs, we first need to understand how User Identity is stored in a UNIX OS." }, { "code": null, "e": 26194, "s": 25787, "text": "In UNIX OS, user identity is usually represented as an integer between 0 and generally, 65,535. This number is also referred to as UID (Unique Identification Number). Now, what setuid programs do is that they create processes with UID of the owner and not of a third person executing the program. This means, that an executor will have the rights of the owner... This in itself is a possible vulnerability." }, { "code": null, "e": 26426, "s": 26194, "text": "Coming back to our script, so a setuid copy of the UNIX shell was created. Later on, this program is deleted, and then the correct ls command (for listing the files and folders present in the current working directory) is executed." }, { "code": null, "e": 26440, "s": 26426, "text": "Trojan Horses" }, { "code": null, "e": 26507, "s": 26440, "text": "Go back to the previous script... Suppose if someone (root) typed:" }, { "code": null, "e": 26562, "s": 26507, "text": " cp /bin/sh /tmp/.xxsh\n chmod o+s,w+x /tmp.xxsh\n" }, { "code": null, "e": 26639, "s": 26562, "text": "If the script was typed deliberately, then it will result in a Trojan Horse." }, { "code": null, "e": 26662, "s": 26639, "text": "Virus – A basic format" }, { "code": null, "e": 26726, "s": 26662, "text": "Most of the computer viruses follow the following basic script:" }, { "code": null, "e": 27097, "s": 26726, "text": "Beginvirus\nif spread-condition TRUE then begin\n for the target files begin\n if target affected TRUE then begin\n Determine where to place virus instructions\n Copy the virus instructions\n Modify target to spread the virus later\n End if\n End for\nEnd if\nPerform some other instruction(s) //Optional\nGo back to beginning\nEndvirus\n" }, { "code": null, "e": 27146, "s": 27097, "text": "Basically, every computer virus has two phases –" }, { "code": null, "e": 27285, "s": 27146, "text": "Insertion phase – in this phase, the virus inserts itself into the target.Execution phase- in this phase, the virus performs some actions." }, { "code": null, "e": 27360, "s": 27285, "text": "Insertion phase – in this phase, the virus inserts itself into the target." }, { "code": null, "e": 27425, "s": 27360, "text": "Execution phase- in this phase, the virus performs some actions." }, { "code": null, "e": 27602, "s": 27425, "text": "Let’s take a look at a real virus in Python. Now this is not an actual virus which will cause corruption files, deletion of system files, etc. but just a simple harmless virus." }, { "code": "#!/usr/bin/python import os, datetime, inspect DATA_TO_INSERT = \"GEEKSFORGEEKS\" #search for target files in pathdef search(path): filestoinfect = [] filelist = os.listdir(path) for filename in filelist: #If it is a folder if os.path.isdir(path+\"/\"+filename): filestoinfect.extend(search(path+\"/\"+filename)) #If it is a python script -> Infect it elif filename[-3:] == \".py\": #default value infected = False for line in open(path+\"/\"+filename): if DATA_TO_INSERT in line: infected = True break if infected == False: filestoinfect.append(path+\"/\"+filename) return filestoinfect #changes to be made in the target file def infect(filestoinfect): target_file = inspect.currentframe().f_code.co_filename virus = open(os.path.abspath(target_file)) virusstring = \"\" for i,line in enumerate(virus): if i>=0 and i <41: virusstring += line virus.close for fname in filestoinfect: f = open(fname) temp = f.read() f.close() f = open(fname,\"w\") f.write(virusstring + temp) f.close() #Not required actually def explode(): if datetime.datetime.now().month == 4 and datetime.datetime.now().day == 1: print (\"HAPPY APRIL FOOL'S DAY!!\")filestoinfect = search(os.path.abspath(\"\")) infect(filestoinfect) explode() ", "e": 29143, "s": 27602, "text": null }, { "code": null, "e": 29222, "s": 29143, "text": "Now, this is quite a safe virus But, the basic format and working is the same." }, { "code": null, "e": 29412, "s": 29222, "text": "Also, there are various types of computer virus – Boot sector infectors, executable infectors, multipartite virus, TSR virus, Stealth virus, Encrypted virus, polymorphic virus, macro virus." }, { "code": null, "e": 29495, "s": 29412, "text": "Now, I won’t go into the details and will just stop here. That’s all from my side!" }, { "code": null, "e": 29513, "s": 29495, "text": "About the author:" }, { "code": null, "e": 30040, "s": 29513, "text": "Vishwesh Shrimali is an Undergraduate Mechanical Engineering student at BITS Pilani. He fulfils about all the requirements not taught in his branch- white hat hacker, network security operator, and an ex – Competitive Programmer. As a firm believer in power of Python, his majority work has been in the same language. Whenever he get some time apart from programming, attending classes, watching CSI Cyber, he go for a long walk and play guitar in silence. His motto of life is – “Enjoy your life, ‘cause it’s worth enjoying!”" }, { "code": null, "e": 30143, "s": 30040, "text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks." }, { "code": null, "e": 30151, "s": 30145, "text": "GBlog" }, { "code": null, "e": 30159, "s": 30151, "text": "Project" }, { "code": null, "e": 30166, "s": 30159, "text": "Python" }, { "code": null, "e": 30264, "s": 30166, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30273, "s": 30264, "text": "Comments" }, { "code": null, "e": 30286, "s": 30273, "text": "Old Comments" }, { "code": null, "e": 30328, "s": 30286, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30353, "s": 30328, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30397, "s": 30353, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 30430, "s": 30397, "text": "Working with csv files in Python" }, { "code": null, "e": 30456, "s": 30430, "text": "Types of Software Testing" }, { "code": null, "e": 30505, "s": 30456, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30527, "s": 30505, "text": "XML parsing in Python" }, { "code": null, "e": 30560, "s": 30527, "text": "Working with zip files in Python" }, { "code": null, "e": 30605, "s": 30560, "text": "Python | Simple GUI calculator using Tkinter" } ]
Number.longValue() method in java with examples - GeeksforGeeks
20 Jun, 2018 The java.lang.Number.longValue() is an inbuilt method in java that returns the value of the specified number casted to long data type. This may involve rounding or truncation. Syntax: public abstract long longValue() Parameters: This method does not accepts any parameter. Return value: This method returns the numeric value represented by this object after conversion to type long. Below program illustrate the Number.longValue() method: Program 1: // java program to demonstrate// Number.longValue() methodpublic class gfg { public static void main(String[] args) { // number as float Float x = new Float(127483456f); // print the value as long System.out.println(x.longValue()); // number as double Double y = new Double(78549876); // print the value as long System.out.println(y.longValue()); }} 127483456 78549876 Program 2: // java program to demonstrate// Number.longValue() methodpublic class gfg { public static void main(String[] args) { // number as float Float x = new Float(127f); // print the value as long System.out.println(x.longValue()); // number as double Double y = new Double(76.23); // print the value as long System.out.println(y.longValue()); }} 127 76 Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java Difference between Abstract Class and Interface in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n20 Jun, 2018" }, { "code": null, "e": 23733, "s": 23557, "text": "The java.lang.Number.longValue() is an inbuilt method in java that returns the value of the specified number casted to long data type. This may involve rounding or truncation." }, { "code": null, "e": 23741, "s": 23733, "text": "Syntax:" }, { "code": null, "e": 23775, "s": 23741, "text": "public abstract long longValue()\n" }, { "code": null, "e": 23831, "s": 23775, "text": "Parameters: This method does not accepts any parameter." }, { "code": null, "e": 23941, "s": 23831, "text": "Return value: This method returns the numeric value represented by this object after conversion to type long." }, { "code": null, "e": 23997, "s": 23941, "text": "Below program illustrate the Number.longValue() method:" }, { "code": null, "e": 24008, "s": 23997, "text": "Program 1:" }, { "code": "// java program to demonstrate// Number.longValue() methodpublic class gfg { public static void main(String[] args) { // number as float Float x = new Float(127483456f); // print the value as long System.out.println(x.longValue()); // number as double Double y = new Double(78549876); // print the value as long System.out.println(y.longValue()); }}", "e": 24429, "s": 24008, "text": null }, { "code": null, "e": 24449, "s": 24429, "text": "127483456\n78549876\n" }, { "code": null, "e": 24460, "s": 24449, "text": "Program 2:" }, { "code": "// java program to demonstrate// Number.longValue() methodpublic class gfg { public static void main(String[] args) { // number as float Float x = new Float(127f); // print the value as long System.out.println(x.longValue()); // number as double Double y = new Double(76.23); // print the value as long System.out.println(y.longValue()); }}", "e": 24872, "s": 24460, "text": null }, { "code": null, "e": 24880, "s": 24872, "text": "127\n76\n" }, { "code": null, "e": 24895, "s": 24880, "text": "Java-Functions" }, { "code": null, "e": 24913, "s": 24895, "text": "Java-lang package" }, { "code": null, "e": 24918, "s": 24913, "text": "Java" }, { "code": null, "e": 24923, "s": 24918, "text": "Java" }, { "code": null, "e": 25021, "s": 24923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25030, "s": 25021, "text": "Comments" }, { "code": null, "e": 25043, "s": 25030, "text": "Old Comments" }, { "code": null, "e": 25073, "s": 25043, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25088, "s": 25073, "text": "Stream In Java" }, { "code": null, "e": 25109, "s": 25088, "text": "Constructors in Java" }, { "code": null, "e": 25155, "s": 25109, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25174, "s": 25155, "text": "Exceptions in Java" }, { "code": null, "e": 25191, "s": 25174, "text": "Generics in Java" }, { "code": null, "e": 25234, "s": 25191, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 25250, "s": 25234, "text": "Strings in Java" }, { "code": null, "e": 25306, "s": 25250, "text": "Difference between Abstract Class and Interface in Java" } ]
map operator= in C++ STL - GeeksforGeeks
12 Jul, 2018 The map::operator= is a built function in C++ STL which assigns contents of a container to a different container, replacing its current content. Syntax: map1_name = map2_name Parameters: The map on the left is the container in which the map on the right is to be assigned by destroying the elements of map1. Return Value: This function does not return anything. // C++ program for illustration of// map::operator= function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp, copymp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 4, 50 }); // = operator is used to copy map copymp = mp; // prints the elements cout << "\nThe map mp is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } cout << "\nThe map copymap is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = copymp.begin(); itr != copymp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;} The map mp is : KEY ELEMENT 1 40 2 30 4 50 The map copymap is : KEY ELEMENT 1 40 2 30 4 50 CPP-Functions cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Constructors in C++ C++ Classes and Objects Bitwise Operators in C/C++ Socket Programming in C/C++ Operator Overloading in C++ Multidimensional Arrays in C / C++ Copy Constructor in C++ Virtual Function in C++ Templates in C++ with Examples
[ { "code": null, "e": 24126, "s": 24098, "text": "\n12 Jul, 2018" }, { "code": null, "e": 24271, "s": 24126, "text": "The map::operator= is a built function in C++ STL which assigns contents of a container to a different container, replacing its current content." }, { "code": null, "e": 24279, "s": 24271, "text": "Syntax:" }, { "code": null, "e": 24301, "s": 24279, "text": "map1_name = map2_name" }, { "code": null, "e": 24434, "s": 24301, "text": "Parameters: The map on the left is the container in which the map on the right is to be assigned by destroying the elements of map1." }, { "code": null, "e": 24488, "s": 24434, "text": "Return Value: This function does not return anything." }, { "code": "// C++ program for illustration of// map::operator= function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp, copymp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 4, 50 }); // = operator is used to copy map copymp = mp; // prints the elements cout << \"\\nThe map mp is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } cout << \"\\nThe map copymap is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = copymp.begin(); itr != copymp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}", "e": 25283, "s": 24488, "text": null }, { "code": null, "e": 25402, "s": 25283, "text": "The map mp is : \nKEY ELEMENT\n1 40\n2 30\n4 50\n\nThe map copymap is : \nKEY ELEMENT\n1 40\n2 30\n4 50\n" }, { "code": null, "e": 25416, "s": 25402, "text": "CPP-Functions" }, { "code": null, "e": 25424, "s": 25416, "text": "cpp-map" }, { "code": null, "e": 25428, "s": 25424, "text": "STL" }, { "code": null, "e": 25432, "s": 25428, "text": "C++" }, { "code": null, "e": 25436, "s": 25432, "text": "STL" }, { "code": null, "e": 25440, "s": 25436, "text": "CPP" }, { "code": null, "e": 25538, "s": 25440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25547, "s": 25538, "text": "Comments" }, { "code": null, "e": 25560, "s": 25547, "text": "Old Comments" }, { "code": null, "e": 25579, "s": 25560, "text": "Inheritance in C++" }, { "code": null, "e": 25599, "s": 25579, "text": "Constructors in C++" }, { "code": null, "e": 25623, "s": 25599, "text": "C++ Classes and Objects" }, { "code": null, "e": 25650, "s": 25623, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 25678, "s": 25650, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25706, "s": 25678, "text": "Operator Overloading in C++" }, { "code": null, "e": 25741, "s": 25706, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25765, "s": 25741, "text": "Copy Constructor in C++" }, { "code": null, "e": 25789, "s": 25765, "text": "Virtual Function in C++" } ]
How to Create a Dot loading Animation using HTML and CSS? - GeeksforGeeks
14 Aug, 2020 The Dot Loading animation can be used to enhance the user interface of a website, it can be added while the website loads. This animation can be easily created using HTML and CSS. HTML Code: In this section we will create the basic structure of the dot loader using a div tag which will have some span tags inside of it. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dots Loading Animation</title></head><style> <body> <div class="loader"> <span></span> <span ></span> <span ></span> <span ></span> <span></span> <span></span> </div></body></html> CSS Code: In this section first we will create the dots structure using some basic CSS properties and then in order to create the animation we will use @keyframes rule and use the transformX() function to produce the desired effect. <style>body{ margin: 0; padding: 0; } .loader{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } /* Creating the dots */ span{ height: 25px; width: 25px; margin-right: 10px; border-radius: 50%; background-color: green; animation: loading 1s linear infinite; } /* Creating the loading animation*/ @keyframes loading { 0%{ transform: translateX(0); } 25%{ transform: translateX(15px); } 50%{ transform: translateX(-15px); } 100%{ transform: translateX(0); } } span:nth-child(1){ animation-delay: 0.1s;}span:nth-child(2){ animation-delay: 0.2s;}span:nth-child(3){ animation-delay: 0.3s;}span:nth-child(4){ animation-delay: 0.4s;}span:nth-child(5){ animation-delay: 0.5s;}</style> Complete Code: It is the combination of the above two code sections. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dots loading animation</title></head><style> body{ margin: 0; padding: 0; } .loader{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } /* Creating the dots */ span{ height: 25px; width: 25px; margin-right: 10px; border-radius: 50%; background-color: green; animation: loading 1s linear infinite; } /* Creating the loading animation*/ @keyframes loading { 0%{ transform: translateX(0); } 25%{ transform: translateX(15px); } 50%{ transform: translateX(-15px); } 100%{ transform: translateX(0); } }span:nth-child(1){ animation-delay: 0.1s;}span:nth-child(2){ animation-delay: 0.2s;}span:nth-child(3){ animation-delay: 0.3s;}span:nth-child(4){ animation-delay: 0.4s;}span:nth-child(5){ animation-delay: 0.5s;}</style> <body> <div class="loader"> <span></span> <span ></span> <span ></span> <span ></span> <span></span> <span></span> </div></body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24985, "s": 24957, "text": "\n14 Aug, 2020" }, { "code": null, "e": 25165, "s": 24985, "text": "The Dot Loading animation can be used to enhance the user interface of a website, it can be added while the website loads. This animation can be easily created using HTML and CSS." }, { "code": null, "e": 25306, "s": 25165, "text": "HTML Code: In this section we will create the basic structure of the dot loader using a div tag which will have some span tags inside of it." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Dots Loading Animation</title></head><style> <body> <div class=\"loader\"> <span></span> <span ></span> <span ></span> <span ></span> <span></span> <span></span> </div></body></html>", "e": 25675, "s": 25306, "text": null }, { "code": null, "e": 25908, "s": 25675, "text": "CSS Code: In this section first we will create the dots structure using some basic CSS properties and then in order to create the animation we will use @keyframes rule and use the transformX() function to produce the desired effect." }, { "code": "<style>body{ margin: 0; padding: 0; } .loader{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } /* Creating the dots */ span{ height: 25px; width: 25px; margin-right: 10px; border-radius: 50%; background-color: green; animation: loading 1s linear infinite; } /* Creating the loading animation*/ @keyframes loading { 0%{ transform: translateX(0); } 25%{ transform: translateX(15px); } 50%{ transform: translateX(-15px); } 100%{ transform: translateX(0); } } span:nth-child(1){ animation-delay: 0.1s;}span:nth-child(2){ animation-delay: 0.2s;}span:nth-child(3){ animation-delay: 0.3s;}span:nth-child(4){ animation-delay: 0.4s;}span:nth-child(5){ animation-delay: 0.5s;}</style>", "e": 26720, "s": 25908, "text": null }, { "code": null, "e": 26790, "s": 26720, "text": "Complete Code: It is the combination of the above two code sections." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Dots loading animation</title></head><style> body{ margin: 0; padding: 0; } .loader{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } /* Creating the dots */ span{ height: 25px; width: 25px; margin-right: 10px; border-radius: 50%; background-color: green; animation: loading 1s linear infinite; } /* Creating the loading animation*/ @keyframes loading { 0%{ transform: translateX(0); } 25%{ transform: translateX(15px); } 50%{ transform: translateX(-15px); } 100%{ transform: translateX(0); } }span:nth-child(1){ animation-delay: 0.1s;}span:nth-child(2){ animation-delay: 0.2s;}span:nth-child(3){ animation-delay: 0.3s;}span:nth-child(4){ animation-delay: 0.4s;}span:nth-child(5){ animation-delay: 0.5s;}</style> <body> <div class=\"loader\"> <span></span> <span ></span> <span ></span> <span ></span> <span></span> <span></span> </div></body></html>", "e": 27961, "s": 26790, "text": null }, { "code": null, "e": 27970, "s": 27961, "text": "Output: " }, { "code": null, "e": 28107, "s": 27970, "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": 28116, "s": 28107, "text": "CSS-Misc" }, { "code": null, "e": 28120, "s": 28116, "text": "CSS" }, { "code": null, "e": 28125, "s": 28120, "text": "HTML" }, { "code": null, "e": 28142, "s": 28125, "text": "Web Technologies" }, { "code": null, "e": 28147, "s": 28142, "text": "HTML" }, { "code": null, "e": 28245, "s": 28147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28254, "s": 28245, "text": "Comments" }, { "code": null, "e": 28267, "s": 28254, "text": "Old Comments" }, { "code": null, "e": 28304, "s": 28267, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28333, "s": 28304, "text": "Form validation using jQuery" }, { "code": null, "e": 28372, "s": 28333, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28414, "s": 28372, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28449, "s": 28414, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28509, "s": 28449, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28570, "s": 28509, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28623, "s": 28570, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28673, "s": 28623, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to Create a Multi-line Text Input (Text Area) In HTML?
To create a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows. Here are the attributes of <textarea> tag − You can try to run the following code to create a multi-line text input in HTML − <!DOCTYPE html> <html> <head> <title>HTML textarea Tag</title> </head> <body> <form action = "/cgi-bin/hello_get.cgi" method = "get"> What improvements you want in College? <br> <textarea rows = "5" cols = "60" name = "description"> Enter details here... </textarea><br> <input type = "submit" value = "submit" /> </form> </body> </html>
[ { "code": null, "e": 1273, "s": 1062, "text": "To create a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows." }, { "code": null, "e": 1317, "s": 1273, "text": "Here are the attributes of <textarea> tag −" }, { "code": null, "e": 1399, "s": 1317, "text": "You can try to run the following code to create a multi-line text input in HTML −" }, { "code": null, "e": 1825, "s": 1399, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML textarea Tag</title>\n </head>\n\n <body>\n <form action = \"/cgi-bin/hello_get.cgi\" method = \"get\">\n What improvements you want in College?\n <br>\n <textarea rows = \"5\" cols = \"60\" name = \"description\">\n Enter details here...\n </textarea><br>\n <input type = \"submit\" value = \"submit\" />\n </form>\n </body>\n</html>" } ]
Objective-C Overview
Objective-C is general-purpose language that is developed on top of C Programming language by adding features of Small Talk programming language making it an object-oriented language. It is primarily used in developing iOS and Mac OS X operating systems as well as its applications. Initially, Objective-C was developed by NeXT for its NeXTSTEP OS from whom it was taken over by Apple for its iOS and Mac OS X. Objective-C fully supports object-oriented programming, including the four pillars of object-oriented development − Encapsulation Data hiding Inheritance Polymorphism #import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog (@"hello world"); [pool drain]; return 0; } Foundation Framework provides large set of features and they are listed below. It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on. It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on. It consists of a rich set of functions manipulating files, strings, etc. It consists of a rich set of functions manipulating files, strings, etc. It provides features for URL handling, utilities like date formatting, data handling, error handling, etc. It provides features for URL handling, utilities like date formatting, data handling, error handling, etc. The most important thing to do when learning Objective-C is to focus on concepts and not get lost in language technical details. The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones. Objective-C, as mentioned earlier, is used in iOS and Mac OS X. It has large base of iOS users and largely increasing Mac OS X users. And since Apple focuses on quality first and its wonderful for those who started learning Objective-C. 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2843, "s": 2560, "text": "Objective-C is general-purpose language that is developed on top of C Programming language by adding features of Small Talk programming language making it an object-oriented language. It is primarily used in developing iOS and Mac OS X operating systems as well as its applications." }, { "code": null, "e": 2971, "s": 2843, "text": "Initially, Objective-C was developed by NeXT for its NeXTSTEP OS from whom it was taken over by Apple for its iOS and Mac OS X." }, { "code": null, "e": 3087, "s": 2971, "text": "Objective-C fully supports object-oriented programming, including the four pillars of object-oriented development −" }, { "code": null, "e": 3101, "s": 3087, "text": "Encapsulation" }, { "code": null, "e": 3113, "s": 3101, "text": "Data hiding" }, { "code": null, "e": 3125, "s": 3113, "text": "Inheritance" }, { "code": null, "e": 3138, "s": 3125, "text": "Polymorphism" }, { "code": null, "e": 3340, "s": 3138, "text": "#import <Foundation/Foundation.h>\n\nint main (int argc, const char * argv[]) {\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n NSLog (@\"hello world\");\n [pool drain];\n return 0;\n}" }, { "code": null, "e": 3419, "s": 3340, "text": "Foundation Framework provides large set of features and they are listed below." }, { "code": null, "e": 3505, "s": 3419, "text": "It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on." }, { "code": null, "e": 3591, "s": 3505, "text": "It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on." }, { "code": null, "e": 3664, "s": 3591, "text": "It consists of a rich set of functions manipulating files, strings, etc." }, { "code": null, "e": 3737, "s": 3664, "text": "It consists of a rich set of functions manipulating files, strings, etc." }, { "code": null, "e": 3844, "s": 3737, "text": "It provides features for URL handling, utilities like date formatting, data handling, error handling, etc." }, { "code": null, "e": 3951, "s": 3844, "text": "It provides features for URL handling, utilities like date formatting, data handling, error handling, etc." }, { "code": null, "e": 4080, "s": 3951, "text": "The most important thing to do when learning Objective-C is to focus on concepts and not get lost in language technical details." }, { "code": null, "e": 4266, "s": 4080, "text": "The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones." }, { "code": null, "e": 4503, "s": 4266, "text": "Objective-C, as mentioned earlier, is used in iOS and Mac OS X. It has large base of iOS users and largely increasing Mac OS X users. And since Apple focuses on quality first and its wonderful for those who started learning Objective-C." }, { "code": null, "e": 4536, "s": 4503, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 4553, "s": 4536, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 4584, "s": 4553, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 4595, "s": 4584, "text": " Ken Burke" }, { "code": null, "e": 4602, "s": 4595, "text": " Print" }, { "code": null, "e": 4613, "s": 4602, "text": " Add Notes" } ]
Python - Exceptions Handling
Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them − Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions. Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions. Assertions − This would be covered in Assertions in Python tutorial. Assertions − This would be covered in Assertions in Python tutorial. List of Standard Exceptions − Exception Base class for all exceptions StopIteration Raised when the next() method of an iterator does not point to any object. SystemExit Raised by the sys.exit() function. StandardError Base class for all built-in exceptions except StopIteration and SystemExit. ArithmeticError Base class for all errors that occur for numeric calculation. OverflowError Raised when a calculation exceeds maximum limit for a numeric type. FloatingPointError Raised when a floating point calculation fails. ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types. AssertionError Raised in case of failure of the Assert statement. AttributeError Raised in case of failure of attribute reference or assignment. EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. ImportError Raised when an import statement fails. KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. LookupError Base class for all lookup errors. IndexError Raised when an index is not found in a sequence. KeyError Raised when the specified key is not found in the dictionary. NameError Raised when an identifier is not found in the local or global namespace. UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it. EnvironmentError Base class for all exceptions that occur outside the Python environment. IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. IOError Raised for operating system-related errors. SyntaxError Raised when there is an error in Python syntax. IndentationError Raised when indentation is not specified properly. SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. TypeError Raised when an operation or function is attempted that is invalid for the specified data type. ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. RuntimeError Raised when a generated error does not fall into any category. NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program. The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised. Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5. Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output. When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception. The syntax for assert is − assert Expression[, Arguments] If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback. Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature − #!/usr/bin/python def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78)) print KelvinToFahrenheit(-5) When the above code is executed, it produces the following result − 32.0 451 Traceback (most recent call last): File "test.py", line 9, in <module> print KelvinToFahrenheit(-5) File "test.py", line 4, in KelvinToFahrenheit assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than absolute zero! An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits. If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. Here is simple syntax of try....except...else blocks − try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block. Here are few important points about the above-mentioned syntax − A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection. The else-block is a good place for code that does not need the try: block's protection. This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all − #!/usr/bin/python try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.close() This produces the following result − Written content in the file successfully This example tries to open a file where you do not have write permission, so it raises an exception − #!/usr/bin/python try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" This produces the following result − Error: can't find file or read data You can also use the except statement with no exceptions defined as follows − try: You do your operations here; ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block. This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur. You can also use the same except statement to handle multiple exceptions as follows − try: You do your operations here; ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block. You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this − try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ...................... You cannot use else clause as well along with a finally clause. #!/usr/bin/python try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data" If you do not have permission to open the file in writing mode, then this will produce the following result − Error: can't find file or read data Same example can be written more cleanly as follows − #!/usr/bin/python try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print "Going to close the file" fh.close() except IOError: print "Error: can\'t find file or read data" When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement. An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows − try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here... If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception. This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location. Following is an example for a single exception − #!/usr/bin/python # Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbers\n", Argument # Call above function here. temp_convert("xyz"); This produces the following result − The argument does not contain numbers invalid literal for int() with base 10: 'xyz' You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows. raise [Exception [, args [, traceback]]] Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None. The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception. An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows − def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows − try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here... Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught. In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror. class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg So once you defined above class, you can raise the exception as follows − try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args 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": 2387, "s": 2244, "text": "Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them −" }, { "code": null, "e": 2525, "s": 2387, "text": "Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions." }, { "code": null, "e": 2663, "s": 2525, "text": "Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions." }, { "code": null, "e": 2732, "s": 2663, "text": "Assertions − This would be covered in Assertions in Python tutorial." }, { "code": null, "e": 2801, "s": 2732, "text": "Assertions − This would be covered in Assertions in Python tutorial." }, { "code": null, "e": 2831, "s": 2801, "text": "List of Standard Exceptions −" }, { "code": null, "e": 2841, "s": 2831, "text": "Exception" }, { "code": null, "e": 2871, "s": 2841, "text": "Base class for all exceptions" }, { "code": null, "e": 2885, "s": 2871, "text": "StopIteration" }, { "code": null, "e": 2960, "s": 2885, "text": "Raised when the next() method of an iterator does not point to any object." }, { "code": null, "e": 2971, "s": 2960, "text": "SystemExit" }, { "code": null, "e": 3006, "s": 2971, "text": "Raised by the sys.exit() function." }, { "code": null, "e": 3020, "s": 3006, "text": "StandardError" }, { "code": null, "e": 3096, "s": 3020, "text": "Base class for all built-in exceptions except StopIteration and SystemExit." }, { "code": null, "e": 3112, "s": 3096, "text": "ArithmeticError" }, { "code": null, "e": 3174, "s": 3112, "text": "Base class for all errors that occur for numeric calculation." }, { "code": null, "e": 3188, "s": 3174, "text": "OverflowError" }, { "code": null, "e": 3256, "s": 3188, "text": "Raised when a calculation exceeds maximum limit for a numeric type." }, { "code": null, "e": 3275, "s": 3256, "text": "FloatingPointError" }, { "code": null, "e": 3323, "s": 3275, "text": "Raised when a floating point calculation fails." }, { "code": null, "e": 3341, "s": 3323, "text": "ZeroDivisionError" }, { "code": null, "e": 3415, "s": 3341, "text": "Raised when division or modulo by zero takes place for all numeric types." }, { "code": null, "e": 3430, "s": 3415, "text": "AssertionError" }, { "code": null, "e": 3481, "s": 3430, "text": "Raised in case of failure of the Assert statement." }, { "code": null, "e": 3496, "s": 3481, "text": "AttributeError" }, { "code": null, "e": 3560, "s": 3496, "text": "Raised in case of failure of attribute reference or assignment." }, { "code": null, "e": 3569, "s": 3560, "text": "EOFError" }, { "code": null, "e": 3679, "s": 3569, "text": "Raised when there is no input from either the raw_input() or input() function and the end of file is reached." }, { "code": null, "e": 3691, "s": 3679, "text": "ImportError" }, { "code": null, "e": 3730, "s": 3691, "text": "Raised when an import statement fails." }, { "code": null, "e": 3748, "s": 3730, "text": "KeyboardInterrupt" }, { "code": null, "e": 3827, "s": 3748, "text": "Raised when the user interrupts program execution, usually by pressing Ctrl+c." }, { "code": null, "e": 3839, "s": 3827, "text": "LookupError" }, { "code": null, "e": 3873, "s": 3839, "text": "Base class for all lookup errors." }, { "code": null, "e": 3884, "s": 3873, "text": "IndexError" }, { "code": null, "e": 3933, "s": 3884, "text": "Raised when an index is not found in a sequence." }, { "code": null, "e": 3942, "s": 3933, "text": "KeyError" }, { "code": null, "e": 4004, "s": 3942, "text": "Raised when the specified key is not found in the dictionary." }, { "code": null, "e": 4014, "s": 4004, "text": "NameError" }, { "code": null, "e": 4087, "s": 4014, "text": "Raised when an identifier is not found in the local or global namespace." }, { "code": null, "e": 4105, "s": 4087, "text": "UnboundLocalError" }, { "code": null, "e": 4213, "s": 4105, "text": "Raised when trying to access a local variable in a function or method but no value has been assigned to it." }, { "code": null, "e": 4230, "s": 4213, "text": "EnvironmentError" }, { "code": null, "e": 4303, "s": 4230, "text": "Base class for all exceptions that occur outside the Python environment." }, { "code": null, "e": 4311, "s": 4303, "text": "IOError" }, { "code": null, "e": 4456, "s": 4311, "text": "Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist." }, { "code": null, "e": 4464, "s": 4456, "text": "IOError" }, { "code": null, "e": 4508, "s": 4464, "text": "Raised for operating system-related errors." }, { "code": null, "e": 4520, "s": 4508, "text": "SyntaxError" }, { "code": null, "e": 4568, "s": 4520, "text": "Raised when there is an error in Python syntax." }, { "code": null, "e": 4585, "s": 4568, "text": "IndentationError" }, { "code": null, "e": 4636, "s": 4585, "text": "Raised when indentation is not specified properly." }, { "code": null, "e": 4648, "s": 4636, "text": "SystemError" }, { "code": null, "e": 4776, "s": 4648, "text": "Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit." }, { "code": null, "e": 4787, "s": 4776, "text": "SystemExit" }, { "code": null, "e": 4920, "s": 4787, "text": "Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit." }, { "code": null, "e": 4930, "s": 4920, "text": "TypeError" }, { "code": null, "e": 5025, "s": 4930, "text": "Raised when an operation or function is attempted that is invalid for the specified data type." }, { "code": null, "e": 5036, "s": 5025, "text": "ValueError" }, { "code": null, "e": 5168, "s": 5036, "text": "Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified." }, { "code": null, "e": 5181, "s": 5168, "text": "RuntimeError" }, { "code": null, "e": 5244, "s": 5181, "text": "Raised when a generated error does not fall into any category." }, { "code": null, "e": 5264, "s": 5244, "text": "NotImplementedError" }, { "code": null, "e": 5375, "s": 5264, "text": "Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented." }, { "code": null, "e": 5491, "s": 5375, "text": "An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program." }, { "code": null, "e": 5706, "s": 5491, "text": "The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised." }, { "code": null, "e": 5815, "s": 5706, "text": "Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5." }, { "code": null, "e": 5956, "s": 5815, "text": "Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output." }, { "code": null, "e": 6138, "s": 5956, "text": "When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception." }, { "code": null, "e": 6165, "s": 6138, "text": "The syntax for assert is −" }, { "code": null, "e": 6197, "s": 6165, "text": "assert Expression[, Arguments]\n" }, { "code": null, "e": 6478, "s": 6197, "text": "If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback." }, { "code": null, "e": 6676, "s": 6478, "text": "Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature −" }, { "code": null, "e": 6923, "s": 6676, "text": "#!/usr/bin/python\ndef KelvinToFahrenheit(Temperature):\n assert (Temperature >= 0),\"Colder than absolute zero!\"\n return ((Temperature-273)*1.8)+32\nprint KelvinToFahrenheit(273)\nprint int(KelvinToFahrenheit(505.78))\nprint KelvinToFahrenheit(-5)" }, { "code": null, "e": 6991, "s": 6923, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 7245, "s": 6991, "text": "32.0\n451\nTraceback (most recent call last):\nFile \"test.py\", line 9, in <module>\nprint KelvinToFahrenheit(-5)\nFile \"test.py\", line 4, in KelvinToFahrenheit\nassert (Temperature >= 0),\"Colder than absolute zero!\"\nAssertionError: Colder than absolute zero!\n" }, { "code": null, "e": 7543, "s": 7245, "text": "An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error." }, { "code": null, "e": 7668, "s": 7543, "text": "When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits." }, { "code": null, "e": 7938, "s": 7668, "text": "If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible." }, { "code": null, "e": 7993, "s": 7938, "text": "Here is simple syntax of try....except...else blocks −" }, { "code": null, "e": 8287, "s": 7993, "text": "try:\n You do your operations here;\n ......................\nexcept ExceptionI:\n If there is ExceptionI, then execute this block.\nexcept ExceptionII:\n If there is ExceptionII, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. \n" }, { "code": null, "e": 8352, "s": 8287, "text": "Here are few important points about the above-mentioned syntax −" }, { "code": null, "e": 8512, "s": 8352, "text": "A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions." }, { "code": null, "e": 8672, "s": 8512, "text": "A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions." }, { "code": null, "e": 8747, "s": 8672, "text": "You can also provide a generic except clause, which handles any exception." }, { "code": null, "e": 8822, "s": 8747, "text": "You can also provide a generic except clause, which handles any exception." }, { "code": null, "e": 8977, "s": 8822, "text": "After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception." }, { "code": null, "e": 9132, "s": 8977, "text": "After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception." }, { "code": null, "e": 9220, "s": 9132, "text": "The else-block is a good place for code that does not need the try: block's protection." }, { "code": null, "e": 9308, "s": 9220, "text": "The else-block is a good place for code that does not need the try: block's protection." }, { "code": null, "e": 9425, "s": 9308, "text": "This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all −" }, { "code": null, "e": 9676, "s": 9425, "text": "#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\nelse:\n print \"Written content in the file successfully\"\n fh.close()" }, { "code": null, "e": 9713, "s": 9676, "text": "This produces the following result −" }, { "code": null, "e": 9755, "s": 9713, "text": "Written content in the file successfully\n" }, { "code": null, "e": 9857, "s": 9755, "text": "This example tries to open a file where you do not have write permission, so it raises an exception −" }, { "code": null, "e": 10094, "s": 9857, "text": "#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"r\")\n fh.write(\"This is my test file for exception handling!!\")\nexcept IOError:\n print \"Error: can\\'t find file or read data\"\nelse:\n print \"Written content in the file successfully\"" }, { "code": null, "e": 10131, "s": 10094, "text": "This produces the following result −" }, { "code": null, "e": 10168, "s": 10131, "text": "Error: can't find file or read data\n" }, { "code": null, "e": 10246, "s": 10168, "text": "You can also use the except statement with no exceptions defined as follows −" }, { "code": null, "e": 10459, "s": 10246, "text": "try:\n You do your operations here;\n ......................\nexcept:\n If there is any exception, then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. \n" }, { "code": null, "e": 10750, "s": 10459, "text": "This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur." }, { "code": null, "e": 10836, "s": 10750, "text": "You can also use the same except statement to handle multiple exceptions as follows −" }, { "code": null, "e": 11125, "s": 10836, "text": "try:\n You do your operations here;\n ......................\nexcept(Exception1[, Exception2[,...ExceptionN]]]):\n If there is any exception from the given exception list, \n then execute this block.\n ......................\nelse:\n If there is no exception then execute this block. " }, { "code": null, "e": 11343, "s": 11125, "text": "You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block\nraised an exception or not. The syntax of the try-finally statement is this −" }, { "code": null, "e": 11521, "s": 11343, "text": "try:\n You do your operations here;\n ......................\n Due to any exception, this may be skipped.\nfinally:\n This would always be executed.\n ......................" }, { "code": null, "e": 11585, "s": 11521, "text": "You cannot use else clause as well along with a finally clause." }, { "code": null, "e": 11757, "s": 11585, "text": "#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n fh.write(\"This is my test file for exception handling!!\")\nfinally:\n print \"Error: can\\'t find file or read data\"" }, { "code": null, "e": 11867, "s": 11757, "text": "If you do not have permission to open the file in writing mode, then this will produce the following result −" }, { "code": null, "e": 11904, "s": 11867, "text": "Error: can't find file or read data\n" }, { "code": null, "e": 11958, "s": 11904, "text": "Same example can be written more cleanly as follows −" }, { "code": null, "e": 12215, "s": 11958, "text": "#!/usr/bin/python\n\ntry:\n fh = open(\"testfile\", \"w\")\n try:\n fh.write(\"This is my test file for exception handling!!\")\n finally:\n print \"Going to close the file\"\n fh.close()\nexcept IOError:\n print \"Error: can\\'t find file or read data\"" }, { "code": null, "e": 12511, "s": 12215, "text": "When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement." }, { "code": null, "e": 12759, "s": 12511, "text": "An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −" }, { "code": null, "e": 12897, "s": 12759, "text": "try:\n You do your operations here;\n ......................\nexcept ExceptionType, Argument:\n You can print value of Argument here..." }, { "code": null, "e": 13131, "s": 12897, "text": "If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception." }, { "code": null, "e": 13397, "s": 13131, "text": "This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location." }, { "code": null, "e": 13446, "s": 13397, "text": "Following is an example for a single exception −" }, { "code": null, "e": 13690, "s": 13446, "text": "#!/usr/bin/python\n\n# Define a function here.\ndef temp_convert(var):\n try:\n return int(var)\n except ValueError, Argument:\n print \"The argument does not contain numbers\\n\", Argument\n\n# Call above function here.\ntemp_convert(\"xyz\");" }, { "code": null, "e": 13727, "s": 13690, "text": "This produces the following result −" }, { "code": null, "e": 13812, "s": 13727, "text": "The argument does not contain numbers\ninvalid literal for int() with base 10: 'xyz'\n" }, { "code": null, "e": 13941, "s": 13812, "text": "You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows." }, { "code": null, "e": 13983, "s": 13941, "text": "raise [Exception [, args [, traceback]]]\n" }, { "code": null, "e": 14176, "s": 13983, "text": "Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None." }, { "code": null, "e": 14319, "s": 14176, "text": "The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception." }, { "code": null, "e": 14553, "s": 14319, "text": "An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −" }, { "code": null, "e": 14720, "s": 14553, "text": "def functionName( level ):\n if level < 1:\n raise \"Invalid level!\", level\n # The code below to this would not be executed\n # if we raise the exception" }, { "code": null, "e": 14941, "s": 14720, "text": "Note: In order to catch an exception, an \"except\" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows −" }, { "code": null, "e": 15061, "s": 14941, "text": "try:\n Business Logic here...\nexcept \"Invalid level!\":\n Exception handling here...\nelse:\n Rest of the code here..." }, { "code": null, "e": 15173, "s": 15061, "text": "Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions." }, { "code": null, "e": 15375, "s": 15173, "text": "Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught." }, { "code": null, "e": 15534, "s": 15375, "text": "In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror." }, { "code": null, "e": 15618, "s": 15534, "text": "class Networkerror(RuntimeError):\n def __init__(self, arg):\n self.args = arg" }, { "code": null, "e": 15692, "s": 15618, "text": "So once you defined above class, you can raise the exception as follows −" }, { "code": null, "e": 15774, "s": 15692, "text": "try:\n raise Networkerror(\"Bad hostname\")\nexcept Networkerror,e:\n print e.args" }, { "code": null, "e": 15811, "s": 15774, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 15827, "s": 15811, "text": " Malhar Lathkar" }, { "code": null, "e": 15860, "s": 15827, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 15879, "s": 15860, "text": " Arnab Chakraborty" }, { "code": null, "e": 15914, "s": 15879, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 15936, "s": 15914, "text": " In28Minutes Official" }, { "code": null, "e": 15970, "s": 15936, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 15998, "s": 15970, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 16033, "s": 15998, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 16047, "s": 16033, "text": " Lets Kode It" }, { "code": null, "e": 16080, "s": 16047, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 16097, "s": 16080, "text": " Abhilash Nelson" }, { "code": null, "e": 16104, "s": 16097, "text": " Print" }, { "code": null, "e": 16115, "s": 16104, "text": " Add Notes" } ]
4 Amazing Python Libraries That You Should Try Right Now | by Ismael Araujo | Towards Data Science
I’m a big fan of Python libraries, and I really enjoy them. In fact, some of my most popular blogs are about Python libraries. They have the power to turn hours of work and countless lines of code into two or three, and the best part: they are free. However, most people focus on those most popular libraries and ignore that dozens of thousands of Python libraries can accomplish results that you would take hours to do manually. While I have a deep respect for all the brave people there who like to do things manually, which has its benefits, sometimes we need to make it more efficient. The problem is that trying new libraries can be time-consuming. You need to install, test it out, read the documentation, etc., and not always get what you wanted. As I mentioned in the beginning, I love writing about new Python libraries and sharing what I learned about them. Today I will go over some of the most remarkable libraries that I have discovered recently. With no more introduction, let’s jump into these super cool libraries. What it does: Data analysis and exploration libraryHow easy it is to use: Very EasyWho should use it: Everyone on this planet! Short story. I was writing a blog that would show 15 Python libraries that I learned about recently, and Bamboolib would be the first one I would write about. The focus of that blog was to introduce some libraries quickly, but Bamboolib impressed me so much that it felt wrong not to give the attention it deserves. Their creators say that Bamboolib is a data analysis tool where you can explore the data and get insights without having to code, which would allow people without any coding experience to enjoy the wonders that Python can do with data analysis. On top of that, it can save the time of data analysts and data scientists out there because it doesn’t need any prior coding experience. Looking at their website, it seems like there is a free and a paid version, where the paid version focuses on companies. The good news is that I tested the free version and I didn’t see find any limitations. The other thing is that Bamboolib was created by the same guys who made PyForest, a library I talked about here. Now, let’s check what check all the things that we can accomplish with Bamboolib. I recommend the use of an environment to test Bamboolib. Still, if you don’t care about it, you can install Bamboolib just by typing pip install — upgrade bamboolib — user in your terminal. Then, you will need to install the extension to Jupyter Notebook by typing python -m bamboolib install_nbextensions, and you should be good to go. If you prefer creating an environment, copy and paste the following code in your Jupyter Notebook. After a few moments, you will be ready to start exploring Bamboolib. # Create conda environment!conda create -n bamboolib python=3.7 -y# Activate the environment!conda activate bamboolib# Add the IPython kernel to Jupyter!conda install jupyter -y!conda install ipykernel -y!python -m ipykernel install — user — name bamboolib# Run this if you use Jupyterlab!conda install jupyterlab -y# Install bamboolib ...!pip install — upgrade bamboolib — user# Jupyter Notebook extensions!python -m bamboolib install_nbextensions# Run this if you use Jupyterlab: JupyterLab extensions!python -m bamboolib install_labextensions Now, let’s import Bamboolib, Pandas, and the famous Titanic dataset to explore Bamboolib a bit. # Import bamboolib, Pandas, and the Titanic datasetimport bamboolib as bamimport pandas as pddf = pd.read_csv(bam.titanic_csv) Ok, now we are ready to start using Bamboolib. All you need to do to type df, and you will see multiple options to begin exploring the dataset. From here, Bamboolib has a lot of similarities with other low-code data exploration libraries. However, two features are game-changing. The first one is that you can easily filter, join, concat, group by, change data types, rename a column, and much more. The second thing is that you can see the code and reuse it whenever way you want. Thus, this will be a lifesaver if you are learning Python or just working on a project where you need to use the code but want to save some time. And how does it work? All you need to do is choose the transformation you want to do, select the columns, the aggregations, if necessary, and Bamboolib will do all the rest. I’m doing a group by transformation using the columns Pclass, Sex, and Age as you can see below. Then, I will check the Sum and Count the values. You will also see in the cell at the top that a code shows up. You can use that table anywhere you want, even if you don’t have the Bamboolib installed. Pretty awesome, right? Take a moment to see the code below. There is some advanced code here. Even advanced Pandas users can learn a few things with this code and improve their skills. You can also create visualizations using Bamboolib, and again, you can see the code. There are multiple ways to edit your plots, and you can create very sophisticated data visualizations with it. Another cool thing is that it uses Plotly Express, which has some outstanding-looking charts. And finally, the Explore DataFrame function brings allows you to explore the dataset with a few clicks. You can even explore the features individually. Why would we type countless lines of code to get simple information if we can click a few times and get everything we need? I could spend hours talking about Bamboolib, but we need to move to the next library. I highly recommend you explore this library. Bamboolib deserves its own blog, and I will work on it soon, but for now, enjoy exploring it. What it does: Makes data exploration for machine learning more intuitiveHow easy it is to use: EasyWho should use it: For those who need to a quick look at a dataset stats. TensorFlow Data Validation is a dataset that makes data exploration when creating machine learning models easier. Although it is not as powerful as Bamboolib, it’s worth knowing about it. It’s the solution that TensorFlow found to make exploring the data less stressful and save users from typing a few lines of code. You can check for missing data, outliers, data anomalies, redundant features, features with little or no unique predictive information, labels treated as features, and more. This is what TensorFlow says on its website: TensorFlow Data Validation identifies anomalies in training and serving data, and can automatically create a schema by examining the data. The component can be configured to detect different classes of anomalies in the data. If I have convinced you to give it a try, you can install it by typing pip install tensorflow-data-validation in your terminal. Once the installation is done, we are ready to start using it. We will need Pandas to import the data. I will be using (again!) the Titanic dataset. # Import Tensorflow Data Validationimport tensorflow_data_validation as tfdv# Import Pandasimport pandas as pd# Import Titanic datasetdf = pd.read_csv('train.csv') Ok, now we are good to go. To see TFDV in action, type the following code, and once you run the cell, you will see that TFDV will return a nice-looking descriptive statistics table. stats = tfdv.generate_statistics_from_dataframe(df) tfdv.visualize_statistics(stats) We can see in the image above that, with one click, we got a table with a lot of information. Let’s now focus on the image below to see what kind of information we got. We can see here that we got descriptive statistics for each of the features. TFDV separates numeric features from categorical features. We can also see that it highlights some important information, such as a high number of missing data. In this case, it seems like Age has 19.87% missing values. We can also see features with a high number of zeros. For example, it makes sense that Survived has a high number since 0 means that the passenger did not survive. We can also see mean, standard deviation, minimum, median, and maximum values. On the right, some charts make it very easy to see the data distribution, which I will discuss a bit more. Looking at the categorical features, we can see missing, unique, and most frequent values. There is also the average string length. As I promised, let’s talk a bit more about data visualization. If you click on to expand, you will extend the data visualizations and explore the dataset. It’s important to note that the main focus of TFDV is to analyze the dataset in preparation to run a machine learning model, and for this, TFDV works well. There are some more cool features that you can explore, and TFDV has excellent documentation. As I mentioned before, it’s not as powerful as Bamboolib, but it’s more straightforward to use. What it does: Creates fake dataHow easy it is to use: EasyWho should use it: For those who need to create fake data, like fake names and fake addresses for projects Faker has a very straightforward name. It creates fake data for projects, such as name, addresses, phone number, job title, IP address, Social Security Number, and text. If you are working on a project that only has IDs, you can make it a little more personal and intuitive, creating fake names. As we worry more about privacy, this is a nice way to work with actual data without exposing people’s privacy in our projects. Even for school, a dataset would look way more realistic if we had more information about it. To install it, you can type pip install Faker in your terminal. Here is a demonstration of some cool features: # Import Fakerfrom faker import Fakerfrom faker.providers import internetfake = Faker()# Create fake namefake.name()# Create fake addressfake.address()# Create fake job titlefake.job()# Create fake SSNfake.ssn()# Create fake phone numberfake.phone_number()# Create fake timefake.date_time()# Create fake textfake.text() There are some other cool features, such as changing the results’ language, which allows you to do all the cool stuff that I just showed you in other languages. I speak Portuguese, and the names and addresses seem real enough. Faker has a well done documentation and, if you are interested, you should check it out. They have so much more fake information that they can create, so keep it in mind for your next project. What it does: Downloads Kaggle datasets to the same folder as your Jupyter NotebookHow easy it is to use: EasyWho is this for?: Everyone. Let’s say you are starting a project to practice your data analysis and machine learning skills. Where do you start? Most people go to Kaggle, find an exciting dataset, download the file, find the file in the Downloads folder, and drag the file to the folder where the notebook you are working on is. Quite a few steps, right? What if there were a better way? Well, that’s what OpenDataSets solves. OpenDataSets allows us to download the dataset from a notebook. It will create a folder with the dataset in the same folder where your notebook saves some time. Cool, right? To use it, you need to type pip install opendataset in your terminal. Then, you need to import it to the notebook by typing import opendatasets as od, and you are good to go. Kaggle will ask for your credentials, which you can quickly get on your Kaggle profile page. In the example below, I want to download the famous heart attack dataset. First, let’s install OpenDataSets. You can type pip install opendatasets, and you should be good to go. Then, in your notebook, you can copy and paste the following code: import opendatasets as odod.download('kaggle_url') Now, we can add the dataset URL on Kaggle. import opendatasets as odod.download("https://www.kaggle.com/rashikrahmanpritom/heart-attack-analysis-prediction-dataset") The folder on the left of the image didn’t have the folder with the heart attack dataset. However, as soon as I run the code, it downloads the dataset for me. You can see that the dataset comes unzipped. It could not be any easier. As we saw in this blog, libraries can have the power to make some time-consuming libraries into simple tasks. It’s amazing how much we can accomplish with one or two lines of code. Even people without much code experience can perform complex data analysis. Of course, they can’t substitute the work of a professional who study Python, but they can be used to improve even long-term professionals skills. It’s nice to remember that Python libraries should be seen as a way to improve our work. I don’t recommend you relying only on these libraries, but use them as an add-on. Let me know if you decide to test any of this libraries or if you have any recommendations that I could test. Happy coding! You might also like... 5 Python Libraries That You Don’t Know About, But Should4 Cool Python Libraries That You Should Know About3 Awesome Python Libraries That You Should Know About
[ { "code": null, "e": 761, "s": 171, "text": "I’m a big fan of Python libraries, and I really enjoy them. In fact, some of my most popular blogs are about Python libraries. They have the power to turn hours of work and countless lines of code into two or three, and the best part: they are free. However, most people focus on those most popular libraries and ignore that dozens of thousands of Python libraries can accomplish results that you would take hours to do manually. While I have a deep respect for all the brave people there who like to do things manually, which has its benefits, sometimes we need to make it more efficient." }, { "code": null, "e": 1202, "s": 761, "text": "The problem is that trying new libraries can be time-consuming. You need to install, test it out, read the documentation, etc., and not always get what you wanted. As I mentioned in the beginning, I love writing about new Python libraries and sharing what I learned about them. Today I will go over some of the most remarkable libraries that I have discovered recently. With no more introduction, let’s jump into these super cool libraries." }, { "code": null, "e": 1329, "s": 1202, "text": "What it does: Data analysis and exploration libraryHow easy it is to use: Very EasyWho should use it: Everyone on this planet!" }, { "code": null, "e": 1645, "s": 1329, "text": "Short story. I was writing a blog that would show 15 Python libraries that I learned about recently, and Bamboolib would be the first one I would write about. The focus of that blog was to introduce some libraries quickly, but Bamboolib impressed me so much that it felt wrong not to give the attention it deserves." }, { "code": null, "e": 2027, "s": 1645, "text": "Their creators say that Bamboolib is a data analysis tool where you can explore the data and get insights without having to code, which would allow people without any coding experience to enjoy the wonders that Python can do with data analysis. On top of that, it can save the time of data analysts and data scientists out there because it doesn’t need any prior coding experience." }, { "code": null, "e": 2430, "s": 2027, "text": "Looking at their website, it seems like there is a free and a paid version, where the paid version focuses on companies. The good news is that I tested the free version and I didn’t see find any limitations. The other thing is that Bamboolib was created by the same guys who made PyForest, a library I talked about here. Now, let’s check what check all the things that we can accomplish with Bamboolib." }, { "code": null, "e": 2935, "s": 2430, "text": "I recommend the use of an environment to test Bamboolib. Still, if you don’t care about it, you can install Bamboolib just by typing pip install — upgrade bamboolib — user in your terminal. Then, you will need to install the extension to Jupyter Notebook by typing python -m bamboolib install_nbextensions, and you should be good to go. If you prefer creating an environment, copy and paste the following code in your Jupyter Notebook. After a few moments, you will be ready to start exploring Bamboolib." }, { "code": null, "e": 3481, "s": 2935, "text": "# Create conda environment!conda create -n bamboolib python=3.7 -y# Activate the environment!conda activate bamboolib# Add the IPython kernel to Jupyter!conda install jupyter -y!conda install ipykernel -y!python -m ipykernel install — user — name bamboolib# Run this if you use Jupyterlab!conda install jupyterlab -y# Install bamboolib ...!pip install — upgrade bamboolib — user# Jupyter Notebook extensions!python -m bamboolib install_nbextensions# Run this if you use Jupyterlab: JupyterLab extensions!python -m bamboolib install_labextensions" }, { "code": null, "e": 3577, "s": 3481, "text": "Now, let’s import Bamboolib, Pandas, and the famous Titanic dataset to explore Bamboolib a bit." }, { "code": null, "e": 3704, "s": 3577, "text": "# Import bamboolib, Pandas, and the Titanic datasetimport bamboolib as bamimport pandas as pddf = pd.read_csv(bam.titanic_csv)" }, { "code": null, "e": 3848, "s": 3704, "text": "Ok, now we are ready to start using Bamboolib. All you need to do to type df, and you will see multiple options to begin exploring the dataset." }, { "code": null, "e": 4104, "s": 3848, "text": "From here, Bamboolib has a lot of similarities with other low-code data exploration libraries. However, two features are game-changing. The first one is that you can easily filter, join, concat, group by, change data types, rename a column, and much more." }, { "code": null, "e": 4332, "s": 4104, "text": "The second thing is that you can see the code and reuse it whenever way you want. Thus, this will be a lifesaver if you are learning Python or just working on a project where you need to use the code but want to save some time." }, { "code": null, "e": 4828, "s": 4332, "text": "And how does it work? All you need to do is choose the transformation you want to do, select the columns, the aggregations, if necessary, and Bamboolib will do all the rest. I’m doing a group by transformation using the columns Pclass, Sex, and Age as you can see below. Then, I will check the Sum and Count the values. You will also see in the cell at the top that a code shows up. You can use that table anywhere you want, even if you don’t have the Bamboolib installed. Pretty awesome, right?" }, { "code": null, "e": 4990, "s": 4828, "text": "Take a moment to see the code below. There is some advanced code here. Even advanced Pandas users can learn a few things with this code and improve their skills." }, { "code": null, "e": 5280, "s": 4990, "text": "You can also create visualizations using Bamboolib, and again, you can see the code. There are multiple ways to edit your plots, and you can create very sophisticated data visualizations with it. Another cool thing is that it uses Plotly Express, which has some outstanding-looking charts." }, { "code": null, "e": 5556, "s": 5280, "text": "And finally, the Explore DataFrame function brings allows you to explore the dataset with a few clicks. You can even explore the features individually. Why would we type countless lines of code to get simple information if we can click a few times and get everything we need?" }, { "code": null, "e": 5781, "s": 5556, "text": "I could spend hours talking about Bamboolib, but we need to move to the next library. I highly recommend you explore this library. Bamboolib deserves its own blog, and I will work on it soon, but for now, enjoy exploring it." }, { "code": null, "e": 5954, "s": 5781, "text": "What it does: Makes data exploration for machine learning more intuitiveHow easy it is to use: EasyWho should use it: For those who need to a quick look at a dataset stats." }, { "code": null, "e": 6491, "s": 5954, "text": "TensorFlow Data Validation is a dataset that makes data exploration when creating machine learning models easier. Although it is not as powerful as Bamboolib, it’s worth knowing about it. It’s the solution that TensorFlow found to make exploring the data less stressful and save users from typing a few lines of code. You can check for missing data, outliers, data anomalies, redundant features, features with little or no unique predictive information, labels treated as features, and more. This is what TensorFlow says on its website:" }, { "code": null, "e": 6716, "s": 6491, "text": "TensorFlow Data Validation identifies anomalies in training and serving data, and can automatically create a schema by examining the data. The component can be configured to detect different classes of anomalies in the data." }, { "code": null, "e": 6993, "s": 6716, "text": "If I have convinced you to give it a try, you can install it by typing pip install tensorflow-data-validation in your terminal. Once the installation is done, we are ready to start using it. We will need Pandas to import the data. I will be using (again!) the Titanic dataset." }, { "code": null, "e": 7157, "s": 6993, "text": "# Import Tensorflow Data Validationimport tensorflow_data_validation as tfdv# Import Pandasimport pandas as pd# Import Titanic datasetdf = pd.read_csv('train.csv')" }, { "code": null, "e": 7339, "s": 7157, "text": "Ok, now we are good to go. To see TFDV in action, type the following code, and once you run the cell, you will see that TFDV will return a nice-looking descriptive statistics table." }, { "code": null, "e": 7424, "s": 7339, "text": "stats = tfdv.generate_statistics_from_dataframe(df) tfdv.visualize_statistics(stats)" }, { "code": null, "e": 7593, "s": 7424, "text": "We can see in the image above that, with one click, we got a table with a lot of information. Let’s now focus on the image below to see what kind of information we got." }, { "code": null, "e": 8240, "s": 7593, "text": "We can see here that we got descriptive statistics for each of the features. TFDV separates numeric features from categorical features. We can also see that it highlights some important information, such as a high number of missing data. In this case, it seems like Age has 19.87% missing values. We can also see features with a high number of zeros. For example, it makes sense that Survived has a high number since 0 means that the passenger did not survive. We can also see mean, standard deviation, minimum, median, and maximum values. On the right, some charts make it very easy to see the data distribution, which I will discuss a bit more." }, { "code": null, "e": 8372, "s": 8240, "text": "Looking at the categorical features, we can see missing, unique, and most frequent values. There is also the average string length." }, { "code": null, "e": 8683, "s": 8372, "text": "As I promised, let’s talk a bit more about data visualization. If you click on to expand, you will extend the data visualizations and explore the dataset. It’s important to note that the main focus of TFDV is to analyze the dataset in preparation to run a machine learning model, and for this, TFDV works well." }, { "code": null, "e": 8873, "s": 8683, "text": "There are some more cool features that you can explore, and TFDV has excellent documentation. As I mentioned before, it’s not as powerful as Bamboolib, but it’s more straightforward to use." }, { "code": null, "e": 9038, "s": 8873, "text": "What it does: Creates fake dataHow easy it is to use: EasyWho should use it: For those who need to create fake data, like fake names and fake addresses for projects" }, { "code": null, "e": 9555, "s": 9038, "text": "Faker has a very straightforward name. It creates fake data for projects, such as name, addresses, phone number, job title, IP address, Social Security Number, and text. If you are working on a project that only has IDs, you can make it a little more personal and intuitive, creating fake names. As we worry more about privacy, this is a nice way to work with actual data without exposing people’s privacy in our projects. Even for school, a dataset would look way more realistic if we had more information about it." }, { "code": null, "e": 9666, "s": 9555, "text": "To install it, you can type pip install Faker in your terminal. Here is a demonstration of some cool features:" }, { "code": null, "e": 9986, "s": 9666, "text": "# Import Fakerfrom faker import Fakerfrom faker.providers import internetfake = Faker()# Create fake namefake.name()# Create fake addressfake.address()# Create fake job titlefake.job()# Create fake SSNfake.ssn()# Create fake phone numberfake.phone_number()# Create fake timefake.date_time()# Create fake textfake.text()" }, { "code": null, "e": 10213, "s": 9986, "text": "There are some other cool features, such as changing the results’ language, which allows you to do all the cool stuff that I just showed you in other languages. I speak Portuguese, and the names and addresses seem real enough." }, { "code": null, "e": 10406, "s": 10213, "text": "Faker has a well done documentation and, if you are interested, you should check it out. They have so much more fake information that they can create, so keep it in mind for your next project." }, { "code": null, "e": 10544, "s": 10406, "text": "What it does: Downloads Kaggle datasets to the same folder as your Jupyter NotebookHow easy it is to use: EasyWho is this for?: Everyone." }, { "code": null, "e": 10943, "s": 10544, "text": "Let’s say you are starting a project to practice your data analysis and machine learning skills. Where do you start? Most people go to Kaggle, find an exciting dataset, download the file, find the file in the Downloads folder, and drag the file to the folder where the notebook you are working on is. Quite a few steps, right? What if there were a better way? Well, that’s what OpenDataSets solves." }, { "code": null, "e": 11117, "s": 10943, "text": "OpenDataSets allows us to download the dataset from a notebook. It will create a folder with the dataset in the same folder where your notebook saves some time. Cool, right?" }, { "code": null, "e": 11459, "s": 11117, "text": "To use it, you need to type pip install opendataset in your terminal. Then, you need to import it to the notebook by typing import opendatasets as od, and you are good to go. Kaggle will ask for your credentials, which you can quickly get on your Kaggle profile page. In the example below, I want to download the famous heart attack dataset." }, { "code": null, "e": 11630, "s": 11459, "text": "First, let’s install OpenDataSets. You can type pip install opendatasets, and you should be good to go. Then, in your notebook, you can copy and paste the following code:" }, { "code": null, "e": 11681, "s": 11630, "text": "import opendatasets as odod.download('kaggle_url')" }, { "code": null, "e": 11724, "s": 11681, "text": "Now, we can add the dataset URL on Kaggle." }, { "code": null, "e": 11847, "s": 11724, "text": "import opendatasets as odod.download(\"https://www.kaggle.com/rashikrahmanpritom/heart-attack-analysis-prediction-dataset\")" }, { "code": null, "e": 12079, "s": 11847, "text": "The folder on the left of the image didn’t have the folder with the heart attack dataset. However, as soon as I run the code, it downloads the dataset for me. You can see that the dataset comes unzipped. It could not be any easier." }, { "code": null, "e": 12483, "s": 12079, "text": "As we saw in this blog, libraries can have the power to make some time-consuming libraries into simple tasks. It’s amazing how much we can accomplish with one or two lines of code. Even people without much code experience can perform complex data analysis. Of course, they can’t substitute the work of a professional who study Python, but they can be used to improve even long-term professionals skills." }, { "code": null, "e": 12778, "s": 12483, "text": "It’s nice to remember that Python libraries should be seen as a way to improve our work. I don’t recommend you relying only on these libraries, but use them as an add-on. Let me know if you decide to test any of this libraries or if you have any recommendations that I could test. Happy coding!" }, { "code": null, "e": 12801, "s": 12778, "text": "You might also like..." } ]
How to assign column names based on existing row in R DataFrame ? - GeeksforGeeks
30 Apr, 2021 In this article, we will discuss how assign column names or headers to a DataFrame based on rows in R Programming Language. unlist() method in R is used to simulate the conversion of a list to vector. It simplifies to produce a vector by preserving all components. Every element is the same as each of the values in that corresponding row. The as.character() method is then applied successively over this list, to deparse each of its elements individually. The as.character attempts to coerce its argument to the character type. The existing row is, therefore, assigned as a header of the data frame. The corresponding row can then be deleted or retained into the data frame. Syntax: unlist(list) Example: R # creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint("Original Data Frame")print (data_frame) # second row of the data frame is # assigned as the column namecolnames(data_frame) <- as.character(unlist(data_frame[2,])) # second row is then deleted from # the data framedata_frame = data_frame[-2, ] print("Modified Data Frame")print(data_frame) Output [1] "Original Data Frame" col1 col2 col3 1 1 8 0 2 2 9 2 3 3 5 3 4 -4 10 5 [1] "Modified Data Frame" 2 9 2 1 1 8 0 3 3 5 3 4 -4 10 5 The lapply() function in R, returns a list of the same length as an input list object, each element of which is the result of the application of FUN to each of the corresponding elements of the list over which it is applied. Syntax: lapply(X, FUN, ...) Parameter : X – The data frame or matrix FUN – Any function in R can be specified as the second argument where in both in-built and user defined functions can be used. If we use as.character as the FUN, then the variables of the data frame, all the variables of the data frame will be converted to the class “character”. The header or colnames can then be assigned to a particular row of the data frame. Example R # creating a data framedata_frame = data.frame(col1=c(1,-2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5), col4=c(1.5,4.5,6.7,8.9)) # printing original data frameprint("Original Data Frame")print (data_frame) # apply row4 as the headerdata_frame[] <- lapply(data_frame, as.character)colnames(data_frame) <- data_frame[4, ] print("Modified Data Frame")print(data_frame) Output [1] "Original Data Frame" col1 col2 col3 col4 1 1 8 0 1.5 2 -2 9 2 4.5 3 3 5 3 6.7 4 -4 10 5 8.9 [1] "Modified Data Frame" -4 10 5 8.9 1 1 8 0 1.5 2 -2 9 2 4.5 3 3 5 3 6.7 4 -4 10 5 8.9 Picked R DataFrame-Programs R-DataFrame R Language R Programs 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 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? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25366, "s": 25242, "text": "In this article, we will discuss how assign column names or headers to a DataFrame based on rows in R Programming Language." }, { "code": null, "e": 25919, "s": 25366, "text": "unlist() method in R is used to simulate the conversion of a list to vector. It simplifies to produce a vector by preserving all components. Every element is the same as each of the values in that corresponding row. The as.character() method is then applied successively over this list, to deparse each of its elements individually. The as.character attempts to coerce its argument to the character type. The existing row is, therefore, assigned as a header of the data frame. The corresponding row can then be deleted or retained into the data frame. " }, { "code": null, "e": 25927, "s": 25919, "text": "Syntax:" }, { "code": null, "e": 25940, "s": 25927, "text": "unlist(list)" }, { "code": null, "e": 25949, "s": 25940, "text": "Example:" }, { "code": null, "e": 25951, "s": 25949, "text": "R" }, { "code": "# creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint(\"Original Data Frame\")print (data_frame) # second row of the data frame is # assigned as the column namecolnames(data_frame) <- as.character(unlist(data_frame[2,])) # second row is then deleted from # the data framedata_frame = data_frame[-2, ] print(\"Modified Data Frame\")print(data_frame)", "e": 26428, "s": 25951, "text": null }, { "code": null, "e": 26435, "s": 26428, "text": "Output" }, { "code": null, "e": 26610, "s": 26435, "text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 8 0\n2 2 9 2\n3 3 5 3\n4 -4 10 5\n[1] \"Modified Data Frame\"\n 2 9 2\n1 1 8 0\n3 3 5 3\n4 -4 10 5" }, { "code": null, "e": 26836, "s": 26610, "text": "The lapply() function in R, returns a list of the same length as an input list object, each element of which is the result of the application of FUN to each of the corresponding elements of the list over which it is applied. " }, { "code": null, "e": 26864, "s": 26836, "text": "Syntax: lapply(X, FUN, ...)" }, { "code": null, "e": 26877, "s": 26864, "text": "Parameter : " }, { "code": null, "e": 26906, "s": 26877, "text": "X – The data frame or matrix" }, { "code": null, "e": 27033, "s": 26906, "text": "FUN – Any function in R can be specified as the second argument where in both in-built and user defined functions can be used." }, { "code": null, "e": 27270, "s": 27033, "text": "If we use as.character as the FUN, then the variables of the data frame, all the variables of the data frame will be converted to the class “character”. The header or colnames can then be assigned to a particular row of the data frame. " }, { "code": null, "e": 27278, "s": 27270, "text": "Example" }, { "code": null, "e": 27280, "s": 27278, "text": "R" }, { "code": "# creating a data framedata_frame = data.frame(col1=c(1,-2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5), col4=c(1.5,4.5,6.7,8.9)) # printing original data frameprint(\"Original Data Frame\")print (data_frame) # apply row4 as the headerdata_frame[] <- lapply(data_frame, as.character)colnames(data_frame) <- data_frame[4, ] print(\"Modified Data Frame\")print(data_frame)", "e": 27715, "s": 27280, "text": null }, { "code": null, "e": 27722, "s": 27715, "text": "Output" }, { "code": null, "e": 27952, "s": 27722, "text": "[1] \"Original Data Frame\"\n col1 col2 col3 col4\n1 1 8 0 1.5\n2 -2 9 2 4.5\n3 3 5 3 6.7\n4 -4 10 5 8.9\n[1] \"Modified Data Frame\"\n -4 10 5 8.9\n1 1 8 0 1.5\n2 -2 9 2 4.5\n3 3 5 3 6.7\n4 -4 10 5 8.9" }, { "code": null, "e": 27959, "s": 27952, "text": "Picked" }, { "code": null, "e": 27980, "s": 27959, "text": "R DataFrame-Programs" }, { "code": null, "e": 27992, "s": 27980, "text": "R-DataFrame" }, { "code": null, "e": 28003, "s": 27992, "text": "R Language" }, { "code": null, "e": 28014, "s": 28003, "text": "R Programs" }, { "code": null, "e": 28112, "s": 28014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28164, "s": 28112, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28202, "s": 28164, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28237, "s": 28202, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28295, "s": 28237, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28344, "s": 28295, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28402, "s": 28344, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28451, "s": 28402, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28501, "s": 28451, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28544, "s": 28501, "text": "Replace Specific Characters in String in R" } ]
React ES6 Destructuring
To illustrate destructuring, we'll make a sandwich. Do you take everything out of the refrigerator to make your sandwich? No, you only take out the items you would like to use on your sandwich. Destructuring is exactly the same. We may have an array or object that we are working with, but we only need some of the items contained in these. Destructuring makes it easy to extract only what is needed. Here is the old way of assigning array items to a variable: const vehicles = ['mustang', 'f-150', 'expedition']; // old way const car = vehicles[0]; const truck = vehicles[1]; const suv = vehicles[2]; Here is the new way of assigning array items to a variable: const vehicles = ['mustang', 'f-150', 'expedition']; const [car, truck, suv] = vehicles; When destructuring arrays, the order that variables are declared is important. If we only want the car and suv we can simply leave out the truck but keep the comma: const vehicles = ['mustang', 'f-150', 'expedition']; const [car,, suv] = vehicles; Destructuring comes in handy when a function returns an array: function calculate(a, b) { const add = a + b; const subtract = a - b; const multiply = a * b; const divide = a / b; return [add, subtract, multiply, divide]; } const [add, subtract, multiply, divide] = calculate(4, 7); Try it Yourself » Here is the old way of using an object inside a function: const vehicleOne = { brand: 'Ford', model: 'Mustang', type: 'car', year: 2021, color: 'red' } myVehicle(vehicleOne); // old way function myVehicle(vehicle) { const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.'; } Here is the new way of using an object inside a function: const vehicleOne = { brand: 'Ford', model: 'Mustang', type: 'car', year: 2021, color: 'red' } myVehicle(vehicleOne); function myVehicle({type, color, brand, model}) { const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.'; } Try it Yourself » Notice that the object properties do not have to be declared in a specific order. We can even destructure deeply nested objects by referencing the nested object then using a colon and curly braces to again destructure the items needed from the nested object: const vehicleOne = { brand: 'Ford', model: 'Mustang', type: 'car', year: 2021, color: 'red', registration: { city: 'Houston', state: 'Texas', country: 'USA' } } myVehicle(vehicleOne) function myVehicle({ model, registration: { state } }) { const message = 'My ' + model + ' is registered in ' + state + '.'; } Try it Yourself » Use destructuring to extract only the third item from the array, into a variable named suv. const vehicles = ['mustang', 'f-150', 'expedition']; const [] = vehicles; 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 194, "s": 0, "text": "To illustrate destructuring, we'll make a sandwich. Do you take everything out of the refrigerator to make your sandwich? No, you only take out the items you would like to use on your sandwich." }, { "code": null, "e": 341, "s": 194, "text": "Destructuring is exactly the same. We may have an array or object that we are working with, but we only need some of the items contained in these." }, { "code": null, "e": 401, "s": 341, "text": "Destructuring makes it easy to extract only what is needed." }, { "code": null, "e": 461, "s": 401, "text": "Here is the old way of assigning array items to a variable:" }, { "code": null, "e": 603, "s": 461, "text": "const vehicles = ['mustang', 'f-150', 'expedition'];\n\n// old way\nconst car = vehicles[0];\nconst truck = vehicles[1];\nconst suv = vehicles[2];" }, { "code": null, "e": 663, "s": 603, "text": "Here is the new way of assigning array items to a variable:" }, { "code": null, "e": 753, "s": 663, "text": "const vehicles = ['mustang', 'f-150', 'expedition'];\n\nconst [car, truck, suv] = vehicles;" }, { "code": null, "e": 832, "s": 753, "text": "When destructuring arrays, the order that variables are declared is important." }, { "code": null, "e": 918, "s": 832, "text": "If we only want the car and suv we can simply leave out the truck but keep the comma:" }, { "code": null, "e": 1002, "s": 918, "text": "const vehicles = ['mustang', 'f-150', 'expedition'];\n\nconst [car,, suv] = vehicles;" }, { "code": null, "e": 1065, "s": 1002, "text": "Destructuring comes in handy when a function returns an array:" }, { "code": null, "e": 1296, "s": 1065, "text": "function calculate(a, b) {\n const add = a + b;\n const subtract = a - b;\n const multiply = a * b;\n const divide = a / b;\n\n return [add, subtract, multiply, divide];\n}\n\nconst [add, subtract, multiply, divide] = calculate(4, 7);" }, { "code": null, "e": 1316, "s": 1296, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1374, "s": 1316, "text": "Here is the old way of using an object inside a function:" }, { "code": null, "e": 1664, "s": 1374, "text": "const vehicleOne = {\n brand: 'Ford',\n model: 'Mustang',\n type: 'car',\n year: 2021, \n color: 'red'\n}\n\nmyVehicle(vehicleOne);\n\n// old way\nfunction myVehicle(vehicle) {\n const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' + vehicle.model + '.';\n}" }, { "code": null, "e": 1722, "s": 1664, "text": "Here is the new way of using an object inside a function:" }, { "code": null, "e": 1989, "s": 1722, "text": "const vehicleOne = {\n brand: 'Ford',\n model: 'Mustang',\n type: 'car',\n year: 2021, \n color: 'red'\n}\n\nmyVehicle(vehicleOne);\n\nfunction myVehicle({type, color, brand, model}) {\n const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';\n}" }, { "code": null, "e": 2009, "s": 1989, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2091, "s": 2009, "text": "Notice that the object properties do not have to be declared in a specific order." }, { "code": null, "e": 2268, "s": 2091, "text": "We can even destructure deeply nested objects by referencing the nested object then using a colon and curly braces to again destructure the items needed from the nested object:" }, { "code": null, "e": 2609, "s": 2268, "text": "const vehicleOne = {\n brand: 'Ford',\n model: 'Mustang',\n type: 'car',\n year: 2021, \n color: 'red',\n registration: {\n city: 'Houston',\n state: 'Texas',\n country: 'USA'\n }\n}\n\nmyVehicle(vehicleOne)\n\nfunction myVehicle({ model, registration: { state } }) {\n const message = 'My ' + model + ' is registered in ' + state + '.';\n}" }, { "code": null, "e": 2629, "s": 2609, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2721, "s": 2629, "text": "Use destructuring to extract only the third item from the array, into a variable named suv." }, { "code": null, "e": 2797, "s": 2721, "text": "const vehicles = ['mustang', 'f-150', 'expedition'];\n\nconst [] = vehicles;\n" }, { "code": null, "e": 2816, "s": 2797, "text": "Start the Exercise" }, { "code": null, "e": 2849, "s": 2816, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2891, "s": 2849, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2998, "s": 2891, "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": 3017, "s": 2998, "text": "help@w3schools.com" } ]
How to handle MalformedURLException in java?
While working with client-server programming in Java (JSE), if you are using java.net.URL class object in your program, you need to instantiate this class by passing a string representing required URL to which you need to establish connection. If the url you have passed in the string which cannot be parsed or, without legal protocol a MalformedURLException is generated. In the following Java example we are tring to get establish a connection to a page and publishing the response. We have tampered the protocol part, changed it to htt, which should be http or, https. import java.util.Scanner; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetExample { public static void main(String[] args) throws IOException { String url = "ht://www.tutorialspoint.com/"; URL obj = new URL(url); //Opening a connection HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //Sending the request conn.setRequestMethod("GET"); int response = conn.getResponseCode(); if (response == 200) { //Reading the response to a StringBuffer Scanner responseReader = new Scanner(conn.getInputStream()); StringBuffer buffer = new StringBuffer(); while (responseReader.hasNextLine()) { buffer.append(responseReader.nextLine()+"\n"); } responseReader.close(); //Printing the Response System.out.println(buffer.toString()); } } } Exception in thread "main" java.net.MalformedURLException: unknown protocol: htt at java.net.URL.<init>(Unknown Source) at java.net.URL.<init>(Unknown Source) at java.net.URL.<init>(Unknown Source) at myPackage.HttpGetExample.main(HttpGetExample.java:11) The only solution for this is to make sure that the url you have passed is legal, with a proper protocol. The best way to do it is validating the URL before you proceed with your program. For validation you can use regular expression or other libraries that provide url validators. In the following program we are using exception handling itself to validate the URL. import java.util.Scanner; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; public class HttpGetExample { public static boolean isUrlValid(String url) { try { URL obj = new URL(url); obj.toURI(); return true; } catch (MalformedURLException e) { return false; } catch (URISyntaxException e) { return false; } } public static void main(String[] args) throws IOException { String url = "ht://www.tutorialspoint.com/"; if(isUrlValid(url)) { URL obj = new URL(url); //Opening a connection HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //Sending the request conn.setRequestMethod("GET"); int response = conn.getResponseCode(); if (response == 200) { //Reading the response to a StringBuffer Scanner responseReader = new Scanner(conn.getInputStream()); StringBuffer buffer = new StringBuffer(); while (responseReader.hasNextLine()) { buffer.append(responseReader.nextLine()+"\n"); } responseReader.close(); //Printing the Response System.out.println(buffer.toString()); } }else { System.out.println("Enter valid URL"); } } } Enter valid URL
[ { "code": null, "e": 1435, "s": 1062, "text": "While working with client-server programming in Java (JSE), if you are using java.net.URL class object in your program, you need to instantiate this class by passing a string representing required URL to which you need to establish connection. If the url you have passed in the string which cannot be parsed or, without legal protocol a MalformedURLException is generated." }, { "code": null, "e": 1547, "s": 1435, "text": "In the following Java example we are tring to get establish a connection to a page and publishing the response." }, { "code": null, "e": 1634, "s": 1547, "text": "We have tampered the protocol part, changed it to htt, which should be http or, https." }, { "code": null, "e": 2576, "s": 1634, "text": "import java.util.Scanner;\nimport java.io.IOException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\npublic class HttpGetExample {\n public static void main(String[] args) throws IOException {\n String url = \"ht://www.tutorialspoint.com/\";\n URL obj = new URL(url);\n //Opening a connection\n HttpURLConnection conn = (HttpURLConnection) obj.openConnection();\n //Sending the request\n conn.setRequestMethod(\"GET\");\n int response = conn.getResponseCode();\n if (response == 200) {\n //Reading the response to a StringBuffer\n Scanner responseReader = new Scanner(conn.getInputStream());\n StringBuffer buffer = new StringBuffer();\n while (responseReader.hasNextLine()) {\n buffer.append(responseReader.nextLine()+\"\\n\");\n }\n responseReader.close();\n //Printing the Response\n System.out.println(buffer.toString());\n }\n }\n}" }, { "code": null, "e": 2843, "s": 2576, "text": "Exception in thread \"main\" java.net.MalformedURLException: unknown protocol: htt\n at java.net.URL.<init>(Unknown Source)\n at java.net.URL.<init>(Unknown Source)\n at java.net.URL.<init>(Unknown Source)\n at myPackage.HttpGetExample.main(HttpGetExample.java:11)" }, { "code": null, "e": 2949, "s": 2843, "text": "The only solution for this is to make sure that the url you have passed is legal, with a proper protocol." }, { "code": null, "e": 3210, "s": 2949, "text": "The best way to do it is validating the URL before you proceed with your program. For validation you can use regular expression or other libraries that provide url validators. In the following program we are using exception handling itself to validate the URL." }, { "code": null, "e": 4655, "s": 3210, "text": "import java.util.Scanner;\nimport java.io.IOException;\nimport java.net.HttpURLConnection;\nimport java.net.MalformedURLException;\nimport java.net.URISyntaxException;\nimport java.net.URL;\npublic class HttpGetExample {\n public static boolean isUrlValid(String url) {\n try {\n URL obj = new URL(url);\n obj.toURI();\n return true;\n } catch (MalformedURLException e) {\n return false;\n } catch (URISyntaxException e) {\n return false;\n }\n }\n public static void main(String[] args) throws IOException {\n String url = \"ht://www.tutorialspoint.com/\";\n if(isUrlValid(url)) {\n URL obj = new URL(url);\n //Opening a connection\n HttpURLConnection conn = (HttpURLConnection) obj.openConnection();\n //Sending the request\n conn.setRequestMethod(\"GET\");\n int response = conn.getResponseCode();\n if (response == 200) {\n //Reading the response to a StringBuffer\n Scanner responseReader = new Scanner(conn.getInputStream());\n StringBuffer buffer = new StringBuffer();\n while (responseReader.hasNextLine()) {\n buffer.append(responseReader.nextLine()+\"\\n\");\n }\n responseReader.close();\n //Printing the Response\n System.out.println(buffer.toString());\n }\n }else {\n System.out.println(\"Enter valid URL\");\n }\n }\n}" }, { "code": null, "e": 4671, "s": 4655, "text": "Enter valid URL" } ]
GATE | GATE-CS-2016 (Set 2) | Question 47 - GeeksforGeeks
12 Aug, 2021 Consider the following program: int f(int *p, int n){ if (n <= 1) return 0; else return max(f(p+1,n-1),p[0]-p[1]);}int main(){ int a[] = {3,5,2,6,4}; printf("%d", f(a,5));} Note: max(x,y) returns the maximum of x and y. The value printed by this program is (A) 2(B) 3(C) 4(D) 5Answer: (B)Explanation: Look at the recursion stack of the given code in the below image. Assuming that the base address of array starts from 1000 and an integer takes 4 Bytes. After the last recursive call f(1016,1) returns, in the previous call we will have return max(0,2) and then return max(2,-4) and then return max(2,3) and then finally return max(3,-2) = 3. This solution is contributed by Pranjul Ahuja YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:00:08 / 1:07:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Key2RKhzRGY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2016 (Set 2) GATE-GATE-CS-2016 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2012 | Question 40 C++ Program to count Vowels in a string using Pointer
[ { "code": null, "e": 24269, "s": 24241, "text": "\n12 Aug, 2021" }, { "code": null, "e": 24301, "s": 24269, "text": "Consider the following program:" }, { "code": "int f(int *p, int n){ if (n <= 1) return 0; else return max(f(p+1,n-1),p[0]-p[1]);}int main(){ int a[] = {3,5,2,6,4}; printf(\"%d\", f(a,5));}", "e": 24454, "s": 24301, "text": null }, { "code": null, "e": 24538, "s": 24454, "text": "Note: max(x,y) returns the maximum of x and y. The value printed by this program is" }, { "code": null, "e": 24735, "s": 24538, "text": "(A) 2(B) 3(C) 4(D) 5Answer: (B)Explanation: Look at the recursion stack of the given code in the below image. Assuming that the base address of array starts from 1000 and an integer takes 4 Bytes." }, { "code": null, "e": 24924, "s": 24735, "text": "After the last recursive call f(1016,1) returns, in the previous call we will have return max(0,2) and then return max(2,-4) and then return max(2,3) and then finally return max(3,-2) = 3." }, { "code": null, "e": 24970, "s": 24924, "text": "This solution is contributed by Pranjul Ahuja" }, { "code": null, "e": 25863, "s": 24970, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:00:08 / 1:07:54•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Key2RKhzRGY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 25884, "s": 25863, "text": "GATE-CS-2016 (Set 2)" }, { "code": null, "e": 25910, "s": 25884, "text": "GATE-GATE-CS-2016 (Set 2)" }, { "code": null, "e": 25915, "s": 25910, "text": "GATE" }, { "code": null, "e": 26013, "s": 25915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26022, "s": 26013, "text": "Comments" }, { "code": null, "e": 26035, "s": 26022, "text": "Old Comments" }, { "code": null, "e": 26077, "s": 26035, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26119, "s": 26077, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 26153, "s": 26119, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 26195, "s": 26153, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 26229, "s": 26195, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 26271, "s": 26229, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 26304, "s": 26271, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26346, "s": 26304, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26380, "s": 26346, "text": "GATE | GATE CS 2012 | Question 40" } ]
Small World Model - Using Python Networkx - GeeksforGeeks
14 Jan, 2020 In this article, we will learn how to create a Small World Network using Networx module in Python. Before proceeding that let’s first understand some basics about Small World Phenomenon. What is Small World Phenomenon ?Small World Phenomenon is the study and notion that we are all connected via a small number of edges. There have been three notable experiments to prove the Small World Phenomenon : Milgram Small World Phenomenon Experiment : 296 randomly chosen persons were asked to forward a letter to a ‘target’ person (a Stockbroker in Boston). The letter was to be sent directly to him if the person was known personally, otherwise, the letter was to be sent to someone who has a higher probability of knowing him personally. 64 letters reached the target person with a median length of 6 ie. on average a random person was connected to the target person via 6 people in between.Miscrosoft Instant Messenger Experiment : There are 240 million active users of Microsoft Instant Messenger. They are connected if two users were engaged in a 2-way communication over the period of a month. For any two random people, the median distance was 7 i.e. 2 random people were connected via 7 intermediate connections.Facebook based Experiment : The experiment conducted by Facebook calculated the average path length to be 5.28 in 2008 whereas it reduced to be 4.74 in 2011. Milgram Small World Phenomenon Experiment : 296 randomly chosen persons were asked to forward a letter to a ‘target’ person (a Stockbroker in Boston). The letter was to be sent directly to him if the person was known personally, otherwise, the letter was to be sent to someone who has a higher probability of knowing him personally. 64 letters reached the target person with a median length of 6 ie. on average a random person was connected to the target person via 6 people in between. Miscrosoft Instant Messenger Experiment : There are 240 million active users of Microsoft Instant Messenger. They are connected if two users were engaged in a 2-way communication over the period of a month. For any two random people, the median distance was 7 i.e. 2 random people were connected via 7 intermediate connections. Facebook based Experiment : The experiment conducted by Facebook calculated the average path length to be 5.28 in 2008 whereas it reduced to be 4.74 in 2011. In 1998, Duncan Watts and Steven Strogatz furthered the study of Small World Model by publishing a research paper titled “Collective Dynamics of Small World Networks”. They studied three different kinds of networks: A network of film actors, where the individual nodes were film actors and they were connected only if the actors appeared in the same movie.A power grid network where nodes are generators, transformers and substations and two nodes are linked if they have a transmission line between them.A network where nodes are neurons and two nodes are linked if they have a synapse or a gap junction. A network of film actors, where the individual nodes were film actors and they were connected only if the actors appeared in the same movie. A power grid network where nodes are generators, transformers and substations and two nodes are linked if they have a transmission line between them. A network where nodes are neurons and two nodes are linked if they have a synapse or a gap junction. They concluded that Small World Networks generally has low average path length but high clustering coefficient. Watts and Strogatz came up with a model about how to construct Small World Networks. Let there be n nodes, where each node is connected to m nearest neighbors, this is known as Regular Lattice and looks like as shown in the figure below, where n = 10 and m = 4. Consider each edge (u, v) and with probability p, select a node w at random and rewire the edge (u, v) so that it becomes (u, w). For p = 0, the Regular Lattice retains its structure and has a high average distance and high clustering. For p = 1, a Random Network is formed with small average distance and low clustering. It looks like the figure shown below, where n = 10, m = 4 and p = 1.For an intermediate value of p, we would get an ideal Small World Network with small average distance and high clustering. For Python, we can easily construct a Small World Network using Networkx. import networkx as nximport matplotlib.pyplot as plt G = nx.watts_strogatz_graph(n = 10, m = 4, p = 0.5)pos = nx.circular_layout() plt.figure(figsize = (12, 12))nx.draw_networkx(G, pos) Output: The resultant Small World Network maybe a disconnected Graph. If we wish to get a connected Graph, we can modify line number 4 of the above code as follows: G = nx.connected_watts_strogatz_graph(n=10, m=4, p=0.5, t=20) It runs the original function t times (in this case t = 20) till a connected network is achieved. It will give the following network: G = nx.newman_watts_strogatz_graph(n=10, m=4, p=0.5) The above code will run a similar model but add new edges with probability p instead of rewiring already existing edges. It will produce the following network: Python Networx-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Graph Plotting in Python | Set 1 Python - Call function from another file
[ { "code": null, "e": 24947, "s": 24919, "text": "\n14 Jan, 2020" }, { "code": null, "e": 25134, "s": 24947, "text": "In this article, we will learn how to create a Small World Network using Networx module in Python. Before proceeding that let’s first understand some basics about Small World Phenomenon." }, { "code": null, "e": 25348, "s": 25134, "text": "What is Small World Phenomenon ?Small World Phenomenon is the study and notion that we are all connected via a small number of edges. There have been three notable experiments to prove the Small World Phenomenon :" }, { "code": null, "e": 26319, "s": 25348, "text": "Milgram Small World Phenomenon Experiment : 296 randomly chosen persons were asked to forward a letter to a ‘target’ person (a Stockbroker in Boston). The letter was to be sent directly to him if the person was known personally, otherwise, the letter was to be sent to someone who has a higher probability of knowing him personally. 64 letters reached the target person with a median length of 6 ie. on average a random person was connected to the target person via 6 people in between.Miscrosoft Instant Messenger Experiment : There are 240 million active users of Microsoft Instant Messenger. They are connected if two users were engaged in a 2-way communication over the period of a month. For any two random people, the median distance was 7 i.e. 2 random people were connected via 7 intermediate connections.Facebook based Experiment : The experiment conducted by Facebook calculated the average path length to be 5.28 in 2008 whereas it reduced to be 4.74 in 2011." }, { "code": null, "e": 26806, "s": 26319, "text": "Milgram Small World Phenomenon Experiment : 296 randomly chosen persons were asked to forward a letter to a ‘target’ person (a Stockbroker in Boston). The letter was to be sent directly to him if the person was known personally, otherwise, the letter was to be sent to someone who has a higher probability of knowing him personally. 64 letters reached the target person with a median length of 6 ie. on average a random person was connected to the target person via 6 people in between." }, { "code": null, "e": 27134, "s": 26806, "text": "Miscrosoft Instant Messenger Experiment : There are 240 million active users of Microsoft Instant Messenger. They are connected if two users were engaged in a 2-way communication over the period of a month. For any two random people, the median distance was 7 i.e. 2 random people were connected via 7 intermediate connections." }, { "code": null, "e": 27292, "s": 27134, "text": "Facebook based Experiment : The experiment conducted by Facebook calculated the average path length to be 5.28 in 2008 whereas it reduced to be 4.74 in 2011." }, { "code": null, "e": 27508, "s": 27292, "text": "In 1998, Duncan Watts and Steven Strogatz furthered the study of Small World Model by publishing a research paper titled “Collective Dynamics of Small World Networks”. They studied three different kinds of networks:" }, { "code": null, "e": 27898, "s": 27508, "text": "A network of film actors, where the individual nodes were film actors and they were connected only if the actors appeared in the same movie.A power grid network where nodes are generators, transformers and substations and two nodes are linked if they have a transmission line between them.A network where nodes are neurons and two nodes are linked if they have a synapse or a gap junction." }, { "code": null, "e": 28039, "s": 27898, "text": "A network of film actors, where the individual nodes were film actors and they were connected only if the actors appeared in the same movie." }, { "code": null, "e": 28189, "s": 28039, "text": "A power grid network where nodes are generators, transformers and substations and two nodes are linked if they have a transmission line between them." }, { "code": null, "e": 28290, "s": 28189, "text": "A network where nodes are neurons and two nodes are linked if they have a synapse or a gap junction." }, { "code": null, "e": 28403, "s": 28290, "text": "They concluded that Small World Networks generally has low average path length but high clustering coefficient. " }, { "code": null, "e": 28665, "s": 28403, "text": "Watts and Strogatz came up with a model about how to construct Small World Networks. Let there be n nodes, where each node is connected to m nearest neighbors, this is known as Regular Lattice and looks like as shown in the figure below, where n = 10 and m = 4." }, { "code": null, "e": 29178, "s": 28665, "text": "Consider each edge (u, v) and with probability p, select a node w at random and rewire the edge (u, v) so that it becomes (u, w). For p = 0, the Regular Lattice retains its structure and has a high average distance and high clustering. For p = 1, a Random Network is formed with small average distance and low clustering. It looks like the figure shown below, where n = 10, m = 4 and p = 1.For an intermediate value of p, we would get an ideal Small World Network with small average distance and high clustering." }, { "code": null, "e": 29252, "s": 29178, "text": "For Python, we can easily construct a Small World Network using Networkx." }, { "code": "import networkx as nximport matplotlib.pyplot as plt G = nx.watts_strogatz_graph(n = 10, m = 4, p = 0.5)pos = nx.circular_layout() plt.figure(figsize = (12, 12))nx.draw_networkx(G, pos)", "e": 29440, "s": 29252, "text": null }, { "code": null, "e": 29448, "s": 29440, "text": "Output:" }, { "code": null, "e": 29605, "s": 29448, "text": "The resultant Small World Network maybe a disconnected Graph. If we wish to get a connected Graph, we can modify line number 4 of the above code as follows:" }, { "code": "G = nx.connected_watts_strogatz_graph(n=10, m=4, p=0.5, t=20)", "e": 29667, "s": 29605, "text": null }, { "code": null, "e": 29801, "s": 29667, "text": "It runs the original function t times (in this case t = 20) till a connected network is achieved. It will give the following network:" }, { "code": "G = nx.newman_watts_strogatz_graph(n=10, m=4, p=0.5)", "e": 29854, "s": 29801, "text": null }, { "code": null, "e": 30014, "s": 29854, "text": "The above code will run a similar model but add new edges with probability p instead of rewiring already existing edges. It will produce the following network:" }, { "code": null, "e": 30036, "s": 30014, "text": "Python Networx-module" }, { "code": null, "e": 30043, "s": 30036, "text": "Python" }, { "code": null, "e": 30141, "s": 30043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30150, "s": 30141, "text": "Comments" }, { "code": null, "e": 30163, "s": 30150, "text": "Old Comments" }, { "code": null, "e": 30200, "s": 30163, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30236, "s": 30200, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 30254, "s": 30236, "text": "Python Dictionary" }, { "code": null, "e": 30277, "s": 30254, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 30299, "s": 30277, "text": "Enumerate() in Python" }, { "code": null, "e": 30338, "s": 30299, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 30371, "s": 30338, "text": "Python | Convert set into a list" }, { "code": null, "e": 30420, "s": 30371, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 30453, "s": 30420, "text": "Graph Plotting in Python | Set 1" } ]
Bitonic Travelling Salesman Problem - GeeksforGeeks
13 Jul, 2021 Given a 2D array, arr[][] denoting a list of coordinates of N vertices on 2D space that is already sorted by x-coordinates and y-coordinates, the task is to find the minimum distance of a tour that starts from the leftmost vertex, and strictly goes to the right, and then upon reaching the rightmost vertex, the tour goes strictly from right to left-back to the starting vertex. Examples: Input: N = 7, arr[][] = {{0, 6}, {1 0}, {2 3}, {5 4}, {6 1}, {7 5}, {8 2}}Output: 25.582Explanation: The TSP tour: 0-3-5-6-4-1-2-0 is not a Bitonic TSP tour because although the tour initially goes from left to right (0-3-5-6) and then goes back from right to left (6-4-1), it then makes another left to right (1-2) and then right to left (2-0) steps. The tour: 0-2-3-5-6-4-1-0 is a valid Bitonic TSP tour because it can be decomposed into two paths: 0-2-3-5-6 that goes from left to right and 6-4-1-0 that goes back from right to left. Input: N = 3, arr[][] = {{1, 1}, {2, 3}, {3, 1}}Output: 6.47 Approach: The above problem can be solved using Dynamic Programming. For the sake of understanding, the problem can be changed into two people. Both should start from the leftmost point at the same time. Walk along two different paths, and finally reach the rightmost point, except for the starting point and the endpoint. Every point happens to be passed by one person. Here, dp[i][j] represents how far the first person walks to i and the second person walks to j. In the solution, dp[i][j] means that 1 to max(i, j) have all been walked, and the current positions of the two people are i and j respectively, and how far they need to go. Also, it can be inferred that dp[i][j] is equal to dp[j][i], so from now on it is stipulated that i is always greater than j i.e. i>j in the state. In this way, no matter that person, the next step can only go to i+1, i+2,... these points. So, the state dp[i][j] can only be transferred to dp[i+1][j] or dp[i][i+1]. Follow the steps below to solve the problem: Create a 2D array, dp[][] of size N*N. Iterate the last row of the table, dp, and update dp[N-1][i] to the sum of distance(N-1, N) and distance(i, N), where distance(x, y) represents the Euclidean distance between xth and yth points of arr. Create a recursive function findTour(i, j) to fill all other cellsUpdate dp[i][j] to minimum of findTour(i+1, j)+distance(i, i+1) and findTour(i+1, i)+distance(j, i+1). Update dp[i][j] to minimum of findTour(i+1, j)+distance(i, i+1) and findTour(i+1, i)+distance(j, i+1). Below is the implementation of the above approach: C++ // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Size of the array a[]const int mxN = 1005; // Structure to store the x and// y coordinates of a pointstruct Coordinates { double x, y;} a[mxN]; // Declare a 2-D dp arrayfloat dp[mxN][mxN]; // Function to calculate the// distance between two points// in a Euclidian planefloat distance(int i, int j){ // Return the distance return sqrt( (a[i].x - a[j].x) * (a[i].x - a[j].x) + (a[i].y - a[j].y) * (a[i].y - a[j].y));} // Utility recursive function to find// the bitonic tour distancefloat findTourDistance(int i, int j){ // Memoization if (dp[i][j] > 0) return dp[i][j]; // Update dp[i][j] dp[i][j] = min( findTourDistance(i + 1, j) + distance(i, i + 1), findTourDistance(i + 1, i) + distance(j, i + 1)); return dp[i][j];} // Function to find the// bitonic tour distancevoid bitonicTSP(int N){ // Initialize the dp array memset(dp, 0, sizeof(dp)); // Base Case for (int j = 1; j < N - 1; j++) dp[N - 1][j] = distance(N - 1, N) + distance(j, N); // Print the answer printf("%.2f\n", findTourDistance(1, 1));} // Driver Codeint main(){ // Given Input int N = 3; a[1].x = 1, a[1].y = 1; a[2].x = 2, a[2].y = 3; a[3].x = 3, a[3].y = 1; // Function Call bitonicTSP(N);} 6.47 Time Complexity: O(N2)Auxiliary Space: O(N2) sooda367 Arrays Competitive Programming Dynamic Programming Recursion Arrays Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26041, "s": 26013, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26421, "s": 26041, "text": "Given a 2D array, arr[][] denoting a list of coordinates of N vertices on 2D space that is already sorted by x-coordinates and y-coordinates, the task is to find the minimum distance of a tour that starts from the leftmost vertex, and strictly goes to the right, and then upon reaching the rightmost vertex, the tour goes strictly from right to left-back to the starting vertex. " }, { "code": null, "e": 26431, "s": 26421, "text": "Examples:" }, { "code": null, "e": 26533, "s": 26431, "text": "Input: N = 7, arr[][] = {{0, 6}, {1 0}, {2 3}, {5 4}, {6 1}, {7 5}, {8 2}}Output: 25.582Explanation: " }, { "code": null, "e": 26969, "s": 26533, "text": "The TSP tour: 0-3-5-6-4-1-2-0 is not a Bitonic TSP tour because although the tour initially goes from left to right (0-3-5-6) and then goes back from right to left (6-4-1), it then makes another left to right (1-2) and then right to left (2-0) steps. The tour: 0-2-3-5-6-4-1-0 is a valid Bitonic TSP tour because it can be decomposed into two paths: 0-2-3-5-6 that goes from left to right and 6-4-1-0 that goes back from right to left." }, { "code": null, "e": 27030, "s": 26969, "text": "Input: N = 3, arr[][] = {{1, 1}, {2, 3}, {3, 1}}Output: 6.47" }, { "code": null, "e": 27353, "s": 27030, "text": "Approach: The above problem can be solved using Dynamic Programming. For the sake of understanding, the problem can be changed into two people. Both should start from the leftmost point at the same time. Walk along two different paths, and finally reach the rightmost point, except for the starting point and the endpoint." }, { "code": null, "e": 27497, "s": 27353, "text": "Every point happens to be passed by one person. Here, dp[i][j] represents how far the first person walks to i and the second person walks to j." }, { "code": null, "e": 27670, "s": 27497, "text": "In the solution, dp[i][j] means that 1 to max(i, j) have all been walked, and the current positions of the two people are i and j respectively, and how far they need to go." }, { "code": null, "e": 27818, "s": 27670, "text": "Also, it can be inferred that dp[i][j] is equal to dp[j][i], so from now on it is stipulated that i is always greater than j i.e. i>j in the state." }, { "code": null, "e": 27910, "s": 27818, "text": "In this way, no matter that person, the next step can only go to i+1, i+2,... these points." }, { "code": null, "e": 27986, "s": 27910, "text": "So, the state dp[i][j] can only be transferred to dp[i+1][j] or dp[i][i+1]." }, { "code": null, "e": 28031, "s": 27986, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 28071, "s": 28031, "text": "Create a 2D array, dp[][] of size N*N. " }, { "code": null, "e": 28273, "s": 28071, "text": "Iterate the last row of the table, dp, and update dp[N-1][i] to the sum of distance(N-1, N) and distance(i, N), where distance(x, y) represents the Euclidean distance between xth and yth points of arr." }, { "code": null, "e": 28442, "s": 28273, "text": "Create a recursive function findTour(i, j) to fill all other cellsUpdate dp[i][j] to minimum of findTour(i+1, j)+distance(i, i+1) and findTour(i+1, i)+distance(j, i+1)." }, { "code": null, "e": 28545, "s": 28442, "text": "Update dp[i][j] to minimum of findTour(i+1, j)+distance(i, i+1) and findTour(i+1, i)+distance(j, i+1)." }, { "code": null, "e": 28596, "s": 28545, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28600, "s": 28596, "text": "C++" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Size of the array a[]const int mxN = 1005; // Structure to store the x and// y coordinates of a pointstruct Coordinates { double x, y;} a[mxN]; // Declare a 2-D dp arrayfloat dp[mxN][mxN]; // Function to calculate the// distance between two points// in a Euclidian planefloat distance(int i, int j){ // Return the distance return sqrt( (a[i].x - a[j].x) * (a[i].x - a[j].x) + (a[i].y - a[j].y) * (a[i].y - a[j].y));} // Utility recursive function to find// the bitonic tour distancefloat findTourDistance(int i, int j){ // Memoization if (dp[i][j] > 0) return dp[i][j]; // Update dp[i][j] dp[i][j] = min( findTourDistance(i + 1, j) + distance(i, i + 1), findTourDistance(i + 1, i) + distance(j, i + 1)); return dp[i][j];} // Function to find the// bitonic tour distancevoid bitonicTSP(int N){ // Initialize the dp array memset(dp, 0, sizeof(dp)); // Base Case for (int j = 1; j < N - 1; j++) dp[N - 1][j] = distance(N - 1, N) + distance(j, N); // Print the answer printf(\"%.2f\\n\", findTourDistance(1, 1));} // Driver Codeint main(){ // Given Input int N = 3; a[1].x = 1, a[1].y = 1; a[2].x = 2, a[2].y = 3; a[3].x = 3, a[3].y = 1; // Function Call bitonicTSP(N);}", "e": 29958, "s": 28600, "text": null }, { "code": null, "e": 29966, "s": 29961, "text": "6.47" }, { "code": null, "e": 30013, "s": 29968, "text": "Time Complexity: O(N2)Auxiliary Space: O(N2)" }, { "code": null, "e": 30024, "s": 30015, "text": "sooda367" }, { "code": null, "e": 30031, "s": 30024, "text": "Arrays" }, { "code": null, "e": 30055, "s": 30031, "text": "Competitive Programming" }, { "code": null, "e": 30075, "s": 30055, "text": "Dynamic Programming" }, { "code": null, "e": 30085, "s": 30075, "text": "Recursion" }, { "code": null, "e": 30092, "s": 30085, "text": "Arrays" }, { "code": null, "e": 30112, "s": 30092, "text": "Dynamic Programming" }, { "code": null, "e": 30122, "s": 30112, "text": "Recursion" }, { "code": null, "e": 30220, "s": 30122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30251, "s": 30220, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 30276, "s": 30251, "text": "Window Sliding Technique" }, { "code": null, "e": 30314, "s": 30276, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30335, "s": 30314, "text": "Next Greater Element" }, { "code": null, "e": 30393, "s": 30335, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30436, "s": 30393, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 30479, "s": 30436, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 30520, "s": 30479, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30598, "s": 30520, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Scala Map toList() method with example - GeeksforGeeks
26 Jul, 2019 The toList() method is utilized to display the elements of the map in the list. Method Definition: def toList: List[A] Return Type: It returns all the elements of the map in the list. Example #1: // Scala program of toList()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // Applying toList method val result = m1.toList // Displays output println(result) }} List((3, geeks), (4, for), (2, cs)) Example #2: // Scala program of toList()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 4 -> "for") // Applying toList method val result = m1.toList // Displays output println(result) }} List((3, geeks), (4, for)) Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala Lists Class and Object in Scala Scala Constructors Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala | Arrays How to get the first element of List in Scala Scala Map get() method with example Scala String substring() method with example Lambda Expression in Scala
[ { "code": null, "e": 25333, "s": 25305, "text": "\n26 Jul, 2019" }, { "code": null, "e": 25413, "s": 25333, "text": "The toList() method is utilized to display the elements of the map in the list." }, { "code": null, "e": 25452, "s": 25413, "text": "Method Definition: def toList: List[A]" }, { "code": null, "e": 25517, "s": 25452, "text": "Return Type: It returns all the elements of the map in the list." }, { "code": null, "e": 25529, "s": 25517, "text": "Example #1:" }, { "code": "// Scala program of toList()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying toList method val result = m1.toList // Displays output println(result) }}", "e": 25888, "s": 25529, "text": null }, { "code": null, "e": 25925, "s": 25888, "text": "List((3, geeks), (4, for), (2, cs))\n" }, { "code": null, "e": 25937, "s": 25925, "text": "Example #2:" }, { "code": "// Scala program of toList()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 4 -> \"for\") // Applying toList method val result = m1.toList // Displays output println(result) }}", "e": 26297, "s": 25937, "text": null }, { "code": null, "e": 26325, "s": 26297, "text": "List((3, geeks), (4, for))\n" }, { "code": null, "e": 26331, "s": 26325, "text": "Scala" }, { "code": null, "e": 26341, "s": 26331, "text": "Scala-Map" }, { "code": null, "e": 26354, "s": 26341, "text": "Scala-Method" }, { "code": null, "e": 26360, "s": 26354, "text": "Scala" }, { "code": null, "e": 26458, "s": 26360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26470, "s": 26458, "text": "Scala Lists" }, { "code": null, "e": 26496, "s": 26470, "text": "Class and Object in Scala" }, { "code": null, "e": 26515, "s": 26496, "text": "Scala Constructors" }, { "code": null, "e": 26568, "s": 26515, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 26587, "s": 26568, "text": "Operators in Scala" }, { "code": null, "e": 26602, "s": 26587, "text": "Scala | Arrays" }, { "code": null, "e": 26648, "s": 26602, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 26684, "s": 26648, "text": "Scala Map get() method with example" }, { "code": null, "e": 26729, "s": 26684, "text": "Scala String substring() method with example" } ]
C++ Program to Check Whether a Hamiltonian Cycle or Path Exists in a Given Graph
A Hamiltonian cycle is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. It is in an undirected graph is a path that visits each vertex of the graph exactly once. Begin 1.function isSafe() is used to check for whether it is adjacent to the previously added vertex and already not added. 2. function hamiltonianCycle() solves the hamiltonian problem. 3. function hamCycle() uses hamiltonianCycle() to solve the hamiltonian problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. End #include <iostream> #include <cstdio> #include <cstdlib> #define N 5 using namespace std; void displaytheSolution(int path[]); bool isSafe(int n, bool g[N][N], int path[], int pos) { if (g [path[pos-1]][n] == 0) return false; for (int i = 0; i < pos; i++) if (path[i] == n) return false; return true; } bool hamiltonianCycle(bool g[N][N], int path[], int pos) { //If all vertices are included in Hamiltonian Cycle if (pos == N) { if (g[ path[pos-1] ][ path[0] ] == 1) return true; else return false; } for (int n = 1; n < N; n++) { if (isSafe(n, g, path, pos)) //Check if this vertex can be added to Hamiltonian Cycle { path[pos] = n; //recur to construct rest of the path if (hamiltonianCycle (g, path, pos+1) == true) return true; path[pos] = -1; //remove vertex if it doesn’t lead to the solution } } return false; } bool hamCycle(bool g[N][N]) { int *path = new int[N]; for (int i = 0; i < N; i++) path[i] = -1; //put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point //of the cycle as the graph is undirected path[0] = 0; if (hamiltonianCycle(g, path, 1) == false) { cout<<"\nCycle does not exist"<<endl; return false; } displaytheSolution(path); return true; } void displaytheSolution(int p[]) { cout<<"Cycle Exists:"; cout<<" Following is one Hamiltonian Cycle \n"<<endl; for (int i = 0; i < N; i++) cout<<p[i]<<" "; cout<< p[0]<<endl; } int main() { bool g[N][N] = { {0, 1, 0, 1, 1}, {0, 0, 1, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 1, 0, 1}, {0, 1, 1, 0, 0}, }; hamCycle(g); return 0; } Cycle Exists: Following is one Hamiltonian Cycle 0 4 1 2 3 0
[ { "code": null, "e": 1298, "s": 1062, "text": "A Hamiltonian cycle is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. It is in an undirected graph is a path that visits each vertex of the graph exactly once." }, { "code": null, "e": 1688, "s": 1298, "text": "Begin\n 1.function isSafe() is used to check for whether it is adjacent to the previously added vertex and already not added.\n 2. function hamiltonianCycle() solves the hamiltonian problem.\n 3. function hamCycle() uses hamiltonianCycle() to solve the hamiltonian problem.\n It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path.\nEnd" }, { "code": null, "e": 3501, "s": 1688, "text": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#define N 5\nusing namespace std;\nvoid displaytheSolution(int path[]);\nbool isSafe(int n, bool g[N][N], int path[], int pos) {\n if (g [path[pos-1]][n] == 0)\n return false;\n for (int i = 0; i < pos; i++)\n if (path[i] == n)\n return false;\n return true;\n}\nbool hamiltonianCycle(bool g[N][N], int path[], int pos) {\n //If all vertices are included in Hamiltonian Cycle\n if (pos == N) {\n if (g[ path[pos-1] ][ path[0] ] == 1)\n return true;\n else\n return false;\n }\n for (int n = 1; n < N; n++) {\n if (isSafe(n, g, path, pos)) //Check if this vertex can be added to Hamiltonian Cycle\n {\n path[pos] = n;\n //recur to construct rest of the path\n if (hamiltonianCycle (g, path, pos+1) == true)\n return true;\n path[pos] = -1; //remove vertex if it doesn’t lead to the solution\n }\n }\n return false;\n}\nbool hamCycle(bool g[N][N]) {\n int *path = new int[N];\n for (int i = 0; i < N; i++)\n path[i] = -1;\n //put vertex 0 as the first vertex in the path.\n If there is a Hamiltonian Cycle, then the path can be started from any point\n //of the cycle as the graph is undirected\n path[0] = 0;\n if (hamiltonianCycle(g, path, 1) == false) {\n cout<<\"\\nCycle does not exist\"<<endl;\n return false;\n }\n displaytheSolution(path);\n return true;\n}\nvoid displaytheSolution(int p[]) {\n cout<<\"Cycle Exists:\";\n cout<<\" Following is one Hamiltonian Cycle \\n\"<<endl;\n for (int i = 0; i < N; i++)\n cout<<p[i]<<\" \";\n cout<< p[0]<<endl;\n}\nint main() {\n bool g[N][N] = {\n {0, 1, 0, 1, 1},\n {0, 0, 1, 1, 0},\n {0, 1, 0, 1, 1},\n {1, 1, 1, 0, 1},\n {0, 1, 1, 0, 0},\n };\n hamCycle(g);\n return 0;\n}" }, { "code": null, "e": 3562, "s": 3501, "text": "Cycle Exists: Following is one Hamiltonian Cycle\n0 4 1 2 3 0" } ]
How to create a User Menu in PowerShell?
When you are writing a script and if you want to provide the user to select one option among multiple values and based on it to execute the command, we can generally use the Switch command and for it, we will ask the user choice in the below script. There is another .Net method to create a user menu, we will see it after the example from the description mentioned above. For the Switch command-based user selection, we will first display the message for the user and then give him a choice for the selection through Read-Host command as shown below. Write-Host "============= Pick the Server environment==============" Write-Host "`ta. 'P' for the Prod servers" Write-Host "`tb. 'T' for the Test servers" Write-Host "`tc. 'D for the Dev Servers'" Write-Host "`td. 'Q to Quit'" Write-Host "========================================================" $choice = Read-Host "`nEnter Choice" Once we have the blueprint ready, we will use the Switch command to execute steps based on the user selection. switch ($choice) { 'P'{ Write-Host "`nYou have selected a Prod Environment" } 'T'{ Write-Host "`nYou have selected a Test Environment" } 'D'{ Write-Host "`nYou have selected a Dev Environment" } 'Q'{Return} } If you want users restriction to select among the given values then you can use the do-until loop. You can also set the condition using different cmdlets and as per your criteria. We will write below the entire script and with user choice restriction. do { Write-Host "`n============= Pick the Server environment==============" Write-Host "`ta. 'P' for the Prod servers" Write-Host "`tb. 'T' for the Test servers" Write-Host "`tc. 'D for the Dev Servers'" Write-Host "`td. 'Q to Quit'" Write-Host "========================================================" $choice = Read-Host "`nEnter Choice" } until (($choice -eq 'P') -or ($choice -eq 'T') -or ($choice -eq 'D') -or ($choice -eq 'Q') ) switch ($choice) { 'P'{ Write-Host "`nYou have selected a Prod Environment" } 'T'{ Write-Host "`nYou have selected a Test Environment" } 'D'{ Write-Host "`nYou have selected a Dev Environment" } 'Q'{ Return } } ============= Pick the Server environment============== a. 'P' for the Prod servers b. 'T' for the Test servers c. 'D for the Dev Servers' d. 'Q to Quit' ======================================================== Enter Choice: r ============= Pick the Server environment============== a. 'P' for the Prod servers b. 'T' for the Test servers c. 'D for the Dev Servers' d. 'Q to Quit' ======================================================== Enter Choice: T You have selected a Test Environment With the .Net namespace, we can also automate the same above selection menu and this is the actual standard process. For that, we will leverage the System.Management.Automation.Host namespace of the .Net framework and then we need to use class [ChoiceDescription] of it. Its syntax is as below. [ChoiceDescription]::new('Label', 'HelpMessage') You can learn more about the above class from the URL given below. https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.choicedescription?view=powershellsdk-7.0.0 using namespace System.Management.Automation.Host $Prod = [ChoiceDescription]::new('&Prod', 'Environment:Prod') $Test = [ChoiceDescription]::new('&Test', 'Environment:Test') $Dev = [ChoiceDescription]::new('&Dev', 'Environment:Dev') $Envs = [ChoiceDescription[]]($prod,$Test,$Dev) $choice = $host.ui.PromptForChoice("Select Environment", "Prod?, Dev?, Test?", $envs, 0) In the above example, we are creating different variables for the environment and merging them to the array called $envs, and later to show UI prompt we need to use PromptForChoice class or function. Syntax for PromptForChoice class. PSHostUserInterface.PromptForChoice(String, String, Collection<ChoiceDescription>, Int32) Below URL for more information about the PromptForChoice class. https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.promptforchoice?view=powershellsdk-7.0.0 So, the entire script will be like, using namespace System.Management.Automation.Host $Prod = [ChoiceDescription]::new('&Prod', 'Environment:Prod') $Test = [ChoiceDescription]::new('&Test', 'Environment:Test') $Dev = [ChoiceDescription]::new('&Dev', 'Environment:Dev') $Envs = [ChoiceDescription[]]($prod,$Test,$Dev) $choice = $host.ui.PromptForChoice("Select Environment", "Prod?, Dev?, Test?", $envs, 0) switch ($choice) { 0{ Write-Host "`nYou have selected a Prod Environment" } 1{ Write-Host "`nYou have selected a Test Environment" } 2{ Write-Host "`nYou have selected a Dev Environment" } } You have selected a Dev Environment If you have noticed the difference between the two switch commands in both the methods mentioned above, in the first case we have used Read-Host parameter to read the choice and then passed it to the Switch command and based on the choice it selects the Switch command condition but in the second example, we have used the numbering, It is related to the choice that user enters. If the user selected the first choice, here “Prod” then it goes to the value ‘0’ and for the second value it’s ‘1’ and for the third value, it is ‘2’ and so on.
[ { "code": null, "e": 1312, "s": 1062, "text": "When you are writing a script and if you want to provide the user to select one option among multiple values and based on it to execute the command, we can generally use the Switch command and for it, we will ask the user choice in the below script." }, { "code": null, "e": 1435, "s": 1312, "text": "There is another .Net method to create a user menu, we will see it after the example from the description mentioned above." }, { "code": null, "e": 1614, "s": 1435, "text": "For the Switch command-based user selection, we will first display the message for the user and then give him a choice for the selection through Read-Host command as shown below." }, { "code": null, "e": 1949, "s": 1614, "text": "Write-Host \"============= Pick the Server environment==============\"\nWrite-Host \"`ta. 'P' for the Prod servers\"\nWrite-Host \"`tb. 'T' for the Test servers\"\nWrite-Host \"`tc. 'D for the Dev Servers'\"\n Write-Host \"`td. 'Q to Quit'\"\nWrite-Host \"========================================================\"\n$choice = Read-Host \"`nEnter Choice\"" }, { "code": null, "e": 2060, "s": 1949, "text": "Once we have the blueprint ready, we will use the Switch command to execute steps based on the user selection." }, { "code": null, "e": 2317, "s": 2060, "text": "switch ($choice) {\n 'P'{\n Write-Host \"`nYou have selected a Prod Environment\"\n }\n 'T'{\n Write-Host \"`nYou have selected a Test Environment\"\n }\n 'D'{\n Write-Host \"`nYou have selected a Dev Environment\"\n }\n 'Q'{Return}\n}" }, { "code": null, "e": 2569, "s": 2317, "text": "If you want users restriction to select among the given values then you can use the do-until loop. You can also set the condition using different cmdlets and as per your criteria. We will write below the entire script and with user choice restriction." }, { "code": null, "e": 3268, "s": 2569, "text": "do {\nWrite-Host \"`n============= Pick the Server environment==============\"\nWrite-Host \"`ta. 'P' for the Prod servers\"\nWrite-Host \"`tb. 'T' for the Test servers\"\nWrite-Host \"`tc. 'D for the Dev Servers'\"\nWrite-Host \"`td. 'Q to Quit'\"\nWrite-Host \"========================================================\"\n$choice = Read-Host \"`nEnter Choice\"\n} until (($choice -eq 'P') -or ($choice -eq 'T') -or ($choice -eq 'D') -or ($choice -eq 'Q') )\nswitch ($choice) {\n 'P'{\n Write-Host \"`nYou have selected a Prod Environment\"\n }\n 'T'{\n Write-Host \"`nYou have selected a Test Environment\"\n }\n 'D'{\n Write-Host \"`nYou have selected a Dev Environment\"\n }\n 'Q'{\n Return\n }\n}" }, { "code": null, "e": 3834, "s": 3268, "text": "============= Pick the Server environment==============\n a. 'P' for the Prod servers\n b. 'T' for the Test servers\n c. 'D for the Dev Servers'\n d. 'Q to Quit'\n ========================================================\n Enter Choice: r\n============= Pick the Server environment==============\n a. 'P' for the Prod servers\n b. 'T' for the Test servers\n c. 'D for the Dev Servers'\n d. 'Q to Quit'\n ========================================================\nEnter Choice: T\nYou have selected a Test Environment" }, { "code": null, "e": 4129, "s": 3834, "text": "With the .Net namespace, we can also automate the same above selection menu and this is the actual standard process. For that, we will leverage the System.Management.Automation.Host namespace of the .Net framework and then we need to use class [ChoiceDescription] of it. Its syntax is as below." }, { "code": null, "e": 4178, "s": 4129, "text": "[ChoiceDescription]::new('Label', 'HelpMessage')" }, { "code": null, "e": 4245, "s": 4178, "text": "You can learn more about the above class from the URL given below." }, { "code": null, "e": 4366, "s": 4245, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.choicedescription?view=powershellsdk-7.0.0" }, { "code": null, "e": 4737, "s": 4366, "text": "using namespace System.Management.Automation.Host\n$Prod = [ChoiceDescription]::new('&Prod', 'Environment:Prod')\n$Test = [ChoiceDescription]::new('&Test', 'Environment:Test')\n $Dev = [ChoiceDescription]::new('&Dev', 'Environment:Dev')\n$Envs = [ChoiceDescription[]]($prod,$Test,$Dev)\n$choice = $host.ui.PromptForChoice(\"Select Environment\", \"Prod?, Dev?, Test?\", $envs, 0)" }, { "code": null, "e": 4937, "s": 4737, "text": "In the above example, we are creating different variables for the environment and merging them to the array called $envs, and later to show UI prompt we need to use PromptForChoice class or function." }, { "code": null, "e": 4971, "s": 4937, "text": "Syntax for PromptForChoice class." }, { "code": null, "e": 5061, "s": 4971, "text": "PSHostUserInterface.PromptForChoice(String, String, Collection<ChoiceDescription>, Int32)" }, { "code": null, "e": 5125, "s": 5061, "text": "Below URL for more information about the PromptForChoice class." }, { "code": null, "e": 5264, "s": 5125, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshostuserinterface.promptforchoice?view=powershellsdk-7.0.0" }, { "code": null, "e": 5300, "s": 5264, "text": "So, the entire script will be like," }, { "code": null, "e": 5861, "s": 5300, "text": "using namespace System.Management.Automation.Host $Prod = [ChoiceDescription]::new('&Prod', 'Environment:Prod') $Test = [ChoiceDescription]::new('&Test', 'Environment:Test') $Dev = [ChoiceDescription]::new('&Dev', 'Environment:Dev') $Envs = [ChoiceDescription[]]($prod,$Test,$Dev) $choice = $host.ui.PromptForChoice(\"Select Environment\", \"Prod?, Dev?, Test?\", $envs, 0) switch ($choice) { 0{ Write-Host \"`nYou have selected a Prod Environment\" } 1{ Write-Host \"`nYou have selected a Test Environment\" } 2{ Write-Host \"`nYou have selected a Dev Environment\" } }" }, { "code": null, "e": 5897, "s": 5861, "text": "You have selected a Dev Environment" }, { "code": null, "e": 6438, "s": 5897, "text": "If you have noticed the difference between the two switch commands in both the methods mentioned above, in the first case we have used Read-Host parameter to read the choice and then passed it to the Switch command and based on the choice it selects the Switch command condition but in the second example, we have used the numbering, It is related to the choice that user enters. If the user selected the first choice, here “Prod” then it goes to the value ‘0’ and for the second value it’s ‘1’ and for the third value, it is ‘2’ and so on." } ]
Legal and illegal declaration and initializations in C
Mention some of the legal and illegal declarations and initializations while doing C programming? Before discussing the legal and illegal statements let’s see how to declare and initialize the variables in C. Following is the syntax of variable declaration − Datatype v1,v2,... vn; Where v1, v2,...vn are names of the variables. For example, int sum; float a,b; Variable can be declared in two ways − local declaration local declaration global declaration global declaration The ‘local declaration’ is declaring a variable inside the main block and its value is available within that block. The ‘global declaration’ is declaring a variable outside the main block and its value is available throughout the program. For example, int a, b; /* global declaration*/ main ( ){ int c; /* local declaration*/ - - - } Following is the syntax of variable initialization − Datatype v1=number; For example, int sum=0; float a=1,b=4.5; Declare the variables by using data types, we can initialize the value at the time of declaration. So, while initializing and declaring the values we need to follow the rules Let’s see some of the examples of legal and illegal declarations and initializations in C. Char a=65;It is a legal statement because we can initialize a variable with a constant. Char a=65; It is a legal statement because we can initialize a variable with a constant. Static int p=20, q=p*pIt is an illegal statement because static variable has to be initialized by a constant but here q is not initialized with a constant. Static int p=20, q=p*p It is an illegal statement because static variable has to be initialized by a constant but here q is not initialized with a constant. Double x=30 *PIIt is a legal statement because here we initialized a variable with a constant expression. Double x=30 *PI It is a legal statement because here we initialized a variable with a constant expression. Double diameter []={1,PI/2, PI, 2*PI/2}It is a legal statement, here we initialized array elements with constant. Double diameter []={1,PI/2, PI, 2*PI/2} It is a legal statement, here we initialized array elements with constant. With legal declaration & initialization − Live Demo #include<stdio.h> void main ( ){ int a,b; a= 10, b = 20; printf (" %d", a<b); printf (" %d", a<=b); printf (" %d", a>b); printf (" %d", a>=b); printf (" %d", a = =b); printf (" %d", a ! =b); } 1 1 0 0 0 1 With illegal declaration & initialization − #include <stdio.h> int main(){ static int p=20, q=p*p;//illegal initialization printf("%d%d",p,q); return 0; } error will be occurred error: initializer element is not constant static int p=20, q=p*p;
[ { "code": null, "e": 1160, "s": 1062, "text": "Mention some of the legal and illegal declarations and initializations while doing C programming?" }, { "code": null, "e": 1271, "s": 1160, "text": "Before discussing the legal and illegal statements let’s see how to declare and initialize the variables in C." }, { "code": null, "e": 1321, "s": 1271, "text": "Following is the syntax of variable declaration −" }, { "code": null, "e": 1344, "s": 1321, "text": "Datatype v1,v2,... vn;" }, { "code": null, "e": 1391, "s": 1344, "text": "Where v1, v2,...vn are names of the variables." }, { "code": null, "e": 1413, "s": 1391, "text": "For example, int sum;" }, { "code": null, "e": 1424, "s": 1413, "text": "float a,b;" }, { "code": null, "e": 1463, "s": 1424, "text": "Variable can be declared in two ways −" }, { "code": null, "e": 1481, "s": 1463, "text": "local declaration" }, { "code": null, "e": 1499, "s": 1481, "text": "local declaration" }, { "code": null, "e": 1518, "s": 1499, "text": "global declaration" }, { "code": null, "e": 1537, "s": 1518, "text": "global declaration" }, { "code": null, "e": 1653, "s": 1537, "text": "The ‘local declaration’ is declaring a variable inside the main block and its value is available within that block." }, { "code": null, "e": 1776, "s": 1653, "text": "The ‘global declaration’ is declaring a variable outside the main block and its value is available throughout the program." }, { "code": null, "e": 1789, "s": 1776, "text": "For example," }, { "code": null, "e": 1877, "s": 1789, "text": "int a, b; /* global declaration*/\nmain ( ){\n int c; /* local declaration*/\n - - -\n}" }, { "code": null, "e": 1930, "s": 1877, "text": "Following is the syntax of variable initialization −" }, { "code": null, "e": 1950, "s": 1930, "text": "Datatype v1=number;" }, { "code": null, "e": 1963, "s": 1950, "text": "For example," }, { "code": null, "e": 1991, "s": 1963, "text": "int sum=0;\nfloat a=1,b=4.5;" }, { "code": null, "e": 2166, "s": 1991, "text": "Declare the variables by using data types, we can initialize the value at the time of declaration. So, while initializing and declaring the values we need to follow the rules" }, { "code": null, "e": 2257, "s": 2166, "text": "Let’s see some of the examples of legal and illegal declarations and initializations in C." }, { "code": null, "e": 2345, "s": 2257, "text": "Char a=65;It is a legal statement because we can initialize a variable with a constant." }, { "code": null, "e": 2356, "s": 2345, "text": "Char a=65;" }, { "code": null, "e": 2434, "s": 2356, "text": "It is a legal statement because we can initialize a variable with a constant." }, { "code": null, "e": 2590, "s": 2434, "text": "Static int p=20, q=p*pIt is an illegal statement because static variable has to be initialized by a constant but here q is not initialized with a constant." }, { "code": null, "e": 2613, "s": 2590, "text": "Static int p=20, q=p*p" }, { "code": null, "e": 2747, "s": 2613, "text": "It is an illegal statement because static variable has to be initialized by a constant but here q is not initialized with a constant." }, { "code": null, "e": 2853, "s": 2747, "text": "Double x=30 *PIIt is a legal statement because here we initialized a variable with a constant expression." }, { "code": null, "e": 2869, "s": 2853, "text": "Double x=30 *PI" }, { "code": null, "e": 2960, "s": 2869, "text": "It is a legal statement because here we initialized a variable with a constant expression." }, { "code": null, "e": 3074, "s": 2960, "text": "Double diameter []={1,PI/2, PI, 2*PI/2}It is a legal statement, here we initialized array elements with constant." }, { "code": null, "e": 3114, "s": 3074, "text": "Double diameter []={1,PI/2, PI, 2*PI/2}" }, { "code": null, "e": 3189, "s": 3114, "text": "It is a legal statement, here we initialized array elements with constant." }, { "code": null, "e": 3231, "s": 3189, "text": "With legal declaration & initialization −" }, { "code": null, "e": 3242, "s": 3231, "text": " Live Demo" }, { "code": null, "e": 3459, "s": 3242, "text": "#include<stdio.h>\nvoid main ( ){\n int a,b;\n a= 10, b = 20;\n printf (\" %d\", a<b);\n printf (\" %d\", a<=b);\n printf (\" %d\", a>b);\n printf (\" %d\", a>=b);\n printf (\" %d\", a = =b);\n printf (\" %d\", a ! =b);\n}" }, { "code": null, "e": 3471, "s": 3459, "text": "1 1 0 0 0 1" }, { "code": null, "e": 3515, "s": 3471, "text": "With illegal declaration & initialization −" }, { "code": null, "e": 3635, "s": 3515, "text": "#include <stdio.h>\nint main(){\n static int p=20, q=p*p;//illegal initialization\n printf(\"%d%d\",p,q);\n return 0;\n}" }, { "code": null, "e": 3728, "s": 3635, "text": "error will be occurred\nerror: initializer element is not constant\n static int p=20, q=p*p;" } ]
Sum of fifth powers of the first n natural numbers
26 Mar, 2021 Write a program to find the sum of Fifth powers of the first n natural numbers 15 + 25+ 35 + 45+ .......+ n5 till n-th term. Examples: Input : 4 Output : 1300 15 + 25 + 35 + 45 = 1300 Input : 6 Output : 15 + 25 + 35 + 45 + 52 + 65 Naive Approach :- In this Simple finding the fifth powers of the first n natural numbers is iterate a loop from 1 to n time. like suppose n=5. and store in sum variable. (1*1*1*1*1)+(2*2*2*2*2)+(3*3*3*3*3)+(4*4*4*4*4) = 1300 C++ Java Python3 C# PHP Javascript // CPP Program to find the sum of fifth powers// of first n natural numbers#include <bits/stdc++.h>using namespace std; // calculate the sum of fifth power of// first n natural numberslong long int fifthPowerSum(int n){ long long int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum;} // Driven Programint main(){ int n = 6; cout << fifthPowerSum(n) << endl; return 0;} // Java Program to find the// sum of fifth powers of// first n natural numbersimport java.io.*; class GFG{ // calculate the sum of fifth // power of first n natural // numbers static long fifthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum; } // Driven Program public static void main(String args[]) { int n = 6; System.out.println(fifthPowerSum(n)); }} // This code is contributed by// Nikita Tiwari. # Python 3 Program to find the# sum of fifth powers of first# n natural numbers # calculate the sum of fifth# power of first n natural# numbersdef fifthPowerSum(n) : sm = 0 for i in range(1, n+1) : sm = sm + (i * i * i * i * i) return sm # Driven Programn = 6print(fifthPowerSum(n)) # This code is contributed# by Nikita Tiwari. // C# Program to find the// sum of fifth powers of// first n natural numbersusing System; class GFG{ // calculate the sum of fifth // power of first n natural // numbers static long fifthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum; } // Driven Program public static void Main() { int n = 6; Console.Write(fifthPowerSum(n)); }} // This code is contributed by// vt_m. <?php// PHP Program to find// the sum of fifth powers// of first n natural numbers // calculate the sum of// fifth power of// first n natural numbersfunction fifthPowerSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + ($i * $i * $i * $i * $i); return $sum;} // Driver Code$n = 6;echo(fifthPowerSum($n)); // This code is contributed by Ajit.?> <script> // javascript Program to find the sum of fifth powers// of first n natural numbers // calculate the sum of fifth power of// first n natural numbersfunction fifthPowerSum( n){ let sum = 0; for (let i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum;} // Driven Program let n = 6; document.write(fifthPowerSum(n)); // This code contributed by aashish1995 </script> Output: 12201 Time complexity : O(N) Efficient Approach :- An efficient solution is to use direct mathematical formula which is : (2*n6+6*n5+5*n4 - n2)/12 OR (Can also be written as) (1/6)n6 + (1/2)n5 + (5/12)n4 – (1/12)n2. C++ Java Python3 C# PHP Javascript // CPP Program to find the sum of fifth power// of first n natural numbers#include <bits/stdc++.h>using namespace std; // calculate the sum of fifth power of first n natural numberslong long int fifthPowerSum(int n){ return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12;} // Driven Programint main(){ int n = 5; cout << fifthPowerSum(n) << endl; return 0;} // Java Program to find the sum of fifth power// of first n natural numbersimport java.io.*; class GFG { // calculate the sum of fifth power //of first n natural numbers static long fifthPowerSum(int n) { return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12; } // Driven Program public static void main(String args[]) { int n = 5; System.out.println(fifthPowerSum(n)); }} /*This code is contributed by Nikita Tiwari.*/ # Python 3 Program to find the# sum of fifth power of first# n natural numbers # Calculate the sum of fifth# power of first n natural# numbersdef fifthPowerSum(n) : return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) // 12 # Driven Programn = 5print(fifthPowerSum(n)) # This code is contributed by Nikita Tiwari. // C# Program to find the sum// of fifth power of first n// natural numbersusing System; class GFG { // calculate the sum of fifth power // of first n natural numbers static long fifthPowerSum(int n) { return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12; } // Driven Program public static void Main() { int n = 5; Console.Write(fifthPowerSum(n)); }} /*This code is contributed by vt_m.*/ <?php// PHP Program to find// the sum of fifth power// of first n natural numbers // calculate the sum of// fifth power of first// n natural numbersfunction fifthPowerSum($n){ return ((2 * $n * $n * $n * $n * $n * $n) + (6 * $n * $n * $n * $n * $n) + (5 * $n * $n * $n * $n) - ($n * $n)) / 12;} // Driver Code$n = 5;echo(fifthPowerSum($n)); // This code is contributed by Ajit.?> <script>// JavaScript Program to find the sum of fifth power// of first n natural numbers // calculate the sum of fifth power of first n natural numbersfunction fifthPowerSum(n){ return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12;} // Driven Program let n = 5; document.write(fifthPowerSum(n) + "<br>"); // This code is contributed by Mayank Tyagi </script> Output: 4425 Time complexity : O(1) jit_t aashish1995 mayanktyagi1709 number-theory series series-sum Mathematical number-theory Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Mar, 2021" }, { "code": null, "e": 190, "s": 53, "text": "Write a program to find the sum of Fifth powers of the first n natural numbers 15 + 25+ 35 + 45+ .......+ n5 till n-th term. Examples: " }, { "code": null, "e": 293, "s": 190, "text": " \nInput : 4\nOutput : 1300\n15 + 25 + 35 + 45 = 1300 \n\nInput : 6\nOutput : \n15 + 25 + 35 + 45 + 52 + 65" }, { "code": null, "e": 522, "s": 295, "text": "Naive Approach :- In this Simple finding the fifth powers of the first n natural numbers is iterate a loop from 1 to n time. like suppose n=5. and store in sum variable. (1*1*1*1*1)+(2*2*2*2*2)+(3*3*3*3*3)+(4*4*4*4*4) = 1300 " }, { "code": null, "e": 526, "s": 522, "text": "C++" }, { "code": null, "e": 531, "s": 526, "text": "Java" }, { "code": null, "e": 539, "s": 531, "text": "Python3" }, { "code": null, "e": 542, "s": 539, "text": "C#" }, { "code": null, "e": 546, "s": 542, "text": "PHP" }, { "code": null, "e": 557, "s": 546, "text": "Javascript" }, { "code": "// CPP Program to find the sum of fifth powers// of first n natural numbers#include <bits/stdc++.h>using namespace std; // calculate the sum of fifth power of// first n natural numberslong long int fifthPowerSum(int n){ long long int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum;} // Driven Programint main(){ int n = 6; cout << fifthPowerSum(n) << endl; return 0;}", "e": 985, "s": 557, "text": null }, { "code": "// Java Program to find the// sum of fifth powers of// first n natural numbersimport java.io.*; class GFG{ // calculate the sum of fifth // power of first n natural // numbers static long fifthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum; } // Driven Program public static void main(String args[]) { int n = 6; System.out.println(fifthPowerSum(n)); }} // This code is contributed by// Nikita Tiwari.", "e": 1527, "s": 985, "text": null }, { "code": "# Python 3 Program to find the# sum of fifth powers of first# n natural numbers # calculate the sum of fifth# power of first n natural# numbersdef fifthPowerSum(n) : sm = 0 for i in range(1, n+1) : sm = sm + (i * i * i * i * i) return sm # Driven Programn = 6print(fifthPowerSum(n)) # This code is contributed# by Nikita Tiwari.", "e": 1883, "s": 1527, "text": null }, { "code": "// C# Program to find the// sum of fifth powers of// first n natural numbersusing System; class GFG{ // calculate the sum of fifth // power of first n natural // numbers static long fifthPowerSum(int n) { long sum = 0; for (int i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum; } // Driven Program public static void Main() { int n = 6; Console.Write(fifthPowerSum(n)); }} // This code is contributed by// vt_m.", "e": 2392, "s": 1883, "text": null }, { "code": "<?php// PHP Program to find// the sum of fifth powers// of first n natural numbers // calculate the sum of// fifth power of// first n natural numbersfunction fifthPowerSum($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + ($i * $i * $i * $i * $i); return $sum;} // Driver Code$n = 6;echo(fifthPowerSum($n)); // This code is contributed by Ajit.?>", "e": 2791, "s": 2392, "text": null }, { "code": "<script> // javascript Program to find the sum of fifth powers// of first n natural numbers // calculate the sum of fifth power of// first n natural numbersfunction fifthPowerSum( n){ let sum = 0; for (let i = 1; i <= n; i++) sum = sum + (i * i * i * i * i); return sum;} // Driven Program let n = 6; document.write(fifthPowerSum(n)); // This code contributed by aashish1995 </script>", "e": 3201, "s": 2791, "text": null }, { "code": null, "e": 3211, "s": 3201, "text": "Output: " }, { "code": null, "e": 3218, "s": 3211, "text": " 12201" }, { "code": null, "e": 3336, "s": 3218, "text": "Time complexity : O(N) Efficient Approach :- An efficient solution is to use direct mathematical formula which is : " }, { "code": null, "e": 3435, "s": 3336, "text": "(2*n6+6*n5+5*n4 - n2)/12 \n\nOR (Can also be written as)\n\n(1/6)n6 + (1/2)n5 + (5/12)n4 – (1/12)n2. " }, { "code": null, "e": 3441, "s": 3437, "text": "C++" }, { "code": null, "e": 3446, "s": 3441, "text": "Java" }, { "code": null, "e": 3454, "s": 3446, "text": "Python3" }, { "code": null, "e": 3457, "s": 3454, "text": "C#" }, { "code": null, "e": 3461, "s": 3457, "text": "PHP" }, { "code": null, "e": 3472, "s": 3461, "text": "Javascript" }, { "code": "// CPP Program to find the sum of fifth power// of first n natural numbers#include <bits/stdc++.h>using namespace std; // calculate the sum of fifth power of first n natural numberslong long int fifthPowerSum(int n){ return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12;} // Driven Programint main(){ int n = 5; cout << fifthPowerSum(n) << endl; return 0;}", "e": 3918, "s": 3472, "text": null }, { "code": "// Java Program to find the sum of fifth power// of first n natural numbersimport java.io.*; class GFG { // calculate the sum of fifth power //of first n natural numbers static long fifthPowerSum(int n) { return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12; } // Driven Program public static void main(String args[]) { int n = 5; System.out.println(fifthPowerSum(n)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 4476, "s": 3918, "text": null }, { "code": "# Python 3 Program to find the# sum of fifth power of first# n natural numbers # Calculate the sum of fifth# power of first n natural# numbersdef fifthPowerSum(n) : return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) // 12 # Driven Programn = 5print(fifthPowerSum(n)) # This code is contributed by Nikita Tiwari.", "e": 4869, "s": 4476, "text": null }, { "code": "// C# Program to find the sum// of fifth power of first n// natural numbersusing System; class GFG { // calculate the sum of fifth power // of first n natural numbers static long fifthPowerSum(int n) { return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12; } // Driven Program public static void Main() { int n = 5; Console.Write(fifthPowerSum(n)); }} /*This code is contributed by vt_m.*/", "e": 5396, "s": 4869, "text": null }, { "code": "<?php// PHP Program to find// the sum of fifth power// of first n natural numbers // calculate the sum of// fifth power of first// n natural numbersfunction fifthPowerSum($n){ return ((2 * $n * $n * $n * $n * $n * $n) + (6 * $n * $n * $n * $n * $n) + (5 * $n * $n * $n * $n) - ($n * $n)) / 12;} // Driver Code$n = 5;echo(fifthPowerSum($n)); // This code is contributed by Ajit.?>", "e": 5812, "s": 5396, "text": null }, { "code": "<script>// JavaScript Program to find the sum of fifth power// of first n natural numbers // calculate the sum of fifth power of first n natural numbersfunction fifthPowerSum(n){ return ((2 * n * n * n * n * n * n) + (6 * n * n * n * n * n) + (5 * n * n * n * n) - (n * n)) / 12;} // Driven Program let n = 5; document.write(fifthPowerSum(n) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 6254, "s": 5812, "text": null }, { "code": null, "e": 6263, "s": 6254, "text": "Output: " }, { "code": null, "e": 6269, "s": 6263, "text": " 4425" }, { "code": null, "e": 6293, "s": 6269, "text": "Time complexity : O(1) " }, { "code": null, "e": 6299, "s": 6293, "text": "jit_t" }, { "code": null, "e": 6311, "s": 6299, "text": "aashish1995" }, { "code": null, "e": 6327, "s": 6311, "text": "mayanktyagi1709" }, { "code": null, "e": 6341, "s": 6327, "text": "number-theory" }, { "code": null, "e": 6348, "s": 6341, "text": "series" }, { "code": null, "e": 6359, "s": 6348, "text": "series-sum" }, { "code": null, "e": 6372, "s": 6359, "text": "Mathematical" }, { "code": null, "e": 6386, "s": 6372, "text": "number-theory" }, { "code": null, "e": 6399, "s": 6386, "text": "Mathematical" }, { "code": null, "e": 6406, "s": 6399, "text": "series" } ]
Sync your fork with master in GitHub
12 Jun, 2020 GitHub is a major platform for open source contributions and also an amazing way to gain knowledge contributing to others projects. One learns about the latest modules used, different coding styles and also get in touch with various developers around the world and build the community. While using GitHub and contributing to various apps, it is important we keep our fork repository updated with the master repository as there might be various changes done by various contributors and if we have that updated, it will help us in our future issues and contributions and also use the updated version of the project. Here is the official definition of syncing fork with master “Getting the latest changes in the master repository after you have forked it without losing the current changes you have made in your local repository.” So, how do we do it?! If you are a new developer and also new to open source, then this is an important command structure you got to learn which will make your path to open source contribution smooth. Following are the steps to Sync your fork with the master: Step 1: Open your command line or terminal in git bash. Step 2: Run the following command in your terminal to see the current configured remote repository in your fork: git remote -v Step 3: Run the following command: git remote add upstream https://github.com/(original_owner_or_organisation/(original_repository).git This particular command will help you add the upstream which means the link to master repository from which you have forked. Step 4: Check your remote now by running the following command again: git remote -v It will show something like this, which indicates your own local repository and also your master repository. Step 5: Fetch the changes from the upstream with following command: git fetch upstream Now, that you’ve set the upstream, it’s time to fetch the changes from the upstream(master repository) that have been made since the time you forked. But make sure, you are in your master branch or any main branch before you run this command. Step 6: Merge the fetched changes: git merge upstream/master We’ve reached the milestone finally and now it’s all left to merge the changes that you’ve have fetched from your master to the local repository. This command will help you do that. After you have run all these commands in stepwise order correctly, you will have all the changes made in the master updated in your local repository successfully. Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2020" }, { "code": null, "e": 314, "s": 28, "text": "GitHub is a major platform for open source contributions and also an amazing way to gain knowledge contributing to others projects. One learns about the latest modules used, different coding styles and also get in touch with various developers around the world and build the community." }, { "code": null, "e": 702, "s": 314, "text": "While using GitHub and contributing to various apps, it is important we keep our fork repository updated with the master repository as there might be various changes done by various contributors and if we have that updated, it will help us in our future issues and contributions and also use the updated version of the project. Here is the official definition of syncing fork with master" }, { "code": null, "e": 856, "s": 702, "text": "“Getting the latest changes in the master repository after you have forked it without losing the current changes you have made in your local repository.”" }, { "code": null, "e": 1058, "s": 856, "text": "So, how do we do it?! If you are a new developer and also new to open source, then this is an important command structure you got to learn which will make your path to open source contribution smooth. " }, { "code": null, "e": 1117, "s": 1058, "text": "Following are the steps to Sync your fork with the master:" }, { "code": null, "e": 1173, "s": 1117, "text": "Step 1: Open your command line or terminal in git bash." }, { "code": null, "e": 1286, "s": 1173, "text": "Step 2: Run the following command in your terminal to see the current configured remote repository in your fork:" }, { "code": null, "e": 1300, "s": 1286, "text": "git remote -v" }, { "code": null, "e": 1336, "s": 1300, "text": " Step 3: Run the following command:" }, { "code": null, "e": 1437, "s": 1336, "text": "git remote add upstream https://github.com/(original_owner_or_organisation/(original_repository).git" }, { "code": null, "e": 1562, "s": 1437, "text": "This particular command will help you add the upstream which means the link to master repository from which you have forked." }, { "code": null, "e": 1633, "s": 1562, "text": " Step 4: Check your remote now by running the following command again:" }, { "code": null, "e": 1647, "s": 1633, "text": "git remote -v" }, { "code": null, "e": 1756, "s": 1647, "text": "It will show something like this, which indicates your own local repository and also your master repository." }, { "code": null, "e": 1825, "s": 1756, "text": " Step 5: Fetch the changes from the upstream with following command:" }, { "code": null, "e": 1844, "s": 1825, "text": "git fetch upstream" }, { "code": null, "e": 2087, "s": 1844, "text": "Now, that you’ve set the upstream, it’s time to fetch the changes from the upstream(master repository) that have been made since the time you forked. But make sure, you are in your master branch or any main branch before you run this command." }, { "code": null, "e": 2123, "s": 2087, "text": " Step 6: Merge the fetched changes:" }, { "code": null, "e": 2149, "s": 2123, "text": "git merge upstream/master" }, { "code": null, "e": 2332, "s": 2149, "text": "We’ve reached the milestone finally and now it’s all left to merge the changes that you’ve have fetched from your master to the local repository. This command will help you do that. " }, { "code": null, "e": 2495, "s": 2332, "text": "After you have run all these commands in stepwise order correctly, you will have all the changes made in the master updated in your local repository successfully." }, { "code": null, "e": 2499, "s": 2495, "text": "Git" } ]
Finding Minimum of Two Numbers in Golang
13 Apr, 2020 Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the smallest number among the given two numbers with the help of Min() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Min() function. Syntax: func Min(a, b float64) float64 If you pass -Inf in this function like Min(-Inf, b) or Min(a, -Inf), then this function will return -Inf. If you pass NaN in this function like Min(NaN, b) or Min(a, NaN), then this function will return NaN. If you pass -0 or +0 in this function like Min(-0, -0) or Min(-0, +0) or Min(-0, -0) or Min(+0, -0), then this function will return -0. Example 1: // Golang program to illustrate how// to find the smallest number package main import ( "fmt" "math") // Main functionfunc main() { // Finding smallest number // among the given numbers // Using Min() function res_1 := math.Min(0, -0) res_2 := math.Min(-100, 100) res_3 := math.Min(45.6, 8.9) res_4 := math.Min(math.NaN(), 67) // Displaying the result fmt.Printf("Result 1: %.1f", res_1) fmt.Printf("\nResult 2: %.1f", res_2) fmt.Printf("\nResult 3: %.1f", res_3) fmt.Printf("\nResult 4: %.1f", res_4) } Output: Result 1: 0.0 Result 2: -100.0 Result 3: 8.9 Result 4: NaN Example 2: // Golang program to illustrate how// to find the smallest number package main import ( "fmt" "math") // Main functionfunc main() { // Finding smallest number // among the given numbers // Using Min() function nvalue_1 := math.Min(34, 67) nvalue_2 := math.Min(56.7, 90.8) // Adding minimum numbers res := nvalue_1 + nvalue_2 fmt.Printf("%.2f + %.2f = %.2f", nvalue_1, nvalue_2, res) } Output: 34.00 + 56.70 = 90.70 Golang-Math Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? Constants- Go Language Go Variables Loops in Go Language Time Durations in Golang Structures in Golang Strings in Golang How to iterate over an Array using for loop in Golang? time.Parse() Function in Golang With Examples Golang | Goroutine vs Thread
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2020" }, { "code": null, "e": 424, "s": 28, "text": "Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the smallest number among the given two numbers with the help of Min() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Min() function." }, { "code": null, "e": 432, "s": 424, "text": "Syntax:" }, { "code": null, "e": 463, "s": 432, "text": "func Min(a, b float64) float64" }, { "code": null, "e": 569, "s": 463, "text": "If you pass -Inf in this function like Min(-Inf, b) or Min(a, -Inf), then this function will return -Inf." }, { "code": null, "e": 671, "s": 569, "text": "If you pass NaN in this function like Min(NaN, b) or Min(a, NaN), then this function will return NaN." }, { "code": null, "e": 807, "s": 671, "text": "If you pass -0 or +0 in this function like Min(-0, -0) or Min(-0, +0) or Min(-0, -0) or Min(+0, -0), then this function will return -0." }, { "code": null, "e": 818, "s": 807, "text": "Example 1:" }, { "code": "// Golang program to illustrate how// to find the smallest number package main import ( \"fmt\" \"math\") // Main functionfunc main() { // Finding smallest number // among the given numbers // Using Min() function res_1 := math.Min(0, -0) res_2 := math.Min(-100, 100) res_3 := math.Min(45.6, 8.9) res_4 := math.Min(math.NaN(), 67) // Displaying the result fmt.Printf(\"Result 1: %.1f\", res_1) fmt.Printf(\"\\nResult 2: %.1f\", res_2) fmt.Printf(\"\\nResult 3: %.1f\", res_3) fmt.Printf(\"\\nResult 4: %.1f\", res_4) }", "e": 1373, "s": 818, "text": null }, { "code": null, "e": 1381, "s": 1373, "text": "Output:" }, { "code": null, "e": 1441, "s": 1381, "text": "Result 1: 0.0\nResult 2: -100.0\nResult 3: 8.9\nResult 4: NaN\n" }, { "code": null, "e": 1452, "s": 1441, "text": "Example 2:" }, { "code": "// Golang program to illustrate how// to find the smallest number package main import ( \"fmt\" \"math\") // Main functionfunc main() { // Finding smallest number // among the given numbers // Using Min() function nvalue_1 := math.Min(34, 67) nvalue_2 := math.Min(56.7, 90.8) // Adding minimum numbers res := nvalue_1 + nvalue_2 fmt.Printf(\"%.2f + %.2f = %.2f\", nvalue_1, nvalue_2, res) }", "e": 1886, "s": 1452, "text": null }, { "code": null, "e": 1894, "s": 1886, "text": "Output:" }, { "code": null, "e": 1916, "s": 1894, "text": "34.00 + 56.70 = 90.70" }, { "code": null, "e": 1928, "s": 1916, "text": "Golang-Math" }, { "code": null, "e": 1940, "s": 1928, "text": "Go Language" }, { "code": null, "e": 2038, "s": 1940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2067, "s": 2038, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 2090, "s": 2067, "text": "Constants- Go Language" }, { "code": null, "e": 2103, "s": 2090, "text": "Go Variables" }, { "code": null, "e": 2124, "s": 2103, "text": "Loops in Go Language" }, { "code": null, "e": 2149, "s": 2124, "text": "Time Durations in Golang" }, { "code": null, "e": 2170, "s": 2149, "text": "Structures in Golang" }, { "code": null, "e": 2188, "s": 2170, "text": "Strings in Golang" }, { "code": null, "e": 2243, "s": 2188, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 2289, "s": 2243, "text": "time.Parse() Function in Golang With Examples" } ]
Python | Grouping dictionary keys by value
20 Aug, 2020 While performing computations over dictionary, we can come across a problem in which we might have to perform the task of grouping keys according to value, i.e create a list of keys, it is value of. This can other in cases of organising data in case of machine learning. Let’s discuss certain way in which this task can be performed.Method : Using sorted() + items() + defaultdict() This task can be performed by combining the tasks which can be done by above functions. The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted(). Python3 # Python3 code to demonstrate working of# Grouping dictionary keys by value# Using sorted() + items() + defaultdict()from collections import defaultdict # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 1, 'for' : 3, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using sorted() + items() + defaultdict()# Grouping dictionary keys by valueres = defaultdict(list)for key, val in sorted(test_dict.items()): res[val].append(key) # printing resultprint("Grouped dictionary is : " + str(dict(res))) Output: The original dictionary : {'gfg': 1, 'is': 2, 'best': 1, 'for': 3, 'CS': 2} Grouped dictionary is : {2: ['CS', 'is'], 1: ['best', 'gfg'], 3: ['for']} Method 2: Additionally, This task can also be performed without using any module. So the logic here is: We can check if the keys are present or not 1. No, then we can create key res[v] = [i] 2. Yes, we can append value on the key res[v] + [i] Python3 d_input = {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'}res = {}for i, v in d_input.items(): res[v] = [i] if v not in res.keys() else res[v] + [i]print(res) Output: {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']} mrathore05 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2020" }, { "code": null, "e": 641, "s": 28, "text": "While performing computations over dictionary, we can come across a problem in which we might have to perform the task of grouping keys according to value, i.e create a list of keys, it is value of. This can other in cases of organising data in case of machine learning. Let’s discuss certain way in which this task can be performed.Method : Using sorted() + items() + defaultdict() This task can be performed by combining the tasks which can be done by above functions. The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted(). " }, { "code": null, "e": 649, "s": 641, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Grouping dictionary keys by value# Using sorted() + items() + defaultdict()from collections import defaultdict # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 1, 'for' : 3, 'CS' : 2} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using sorted() + items() + defaultdict()# Grouping dictionary keys by valueres = defaultdict(list)for key, val in sorted(test_dict.items()): res[val].append(key) # printing resultprint(\"Grouped dictionary is : \" + str(dict(res)))", "e": 1215, "s": 649, "text": null }, { "code": null, "e": 1223, "s": 1215, "text": "Output:" }, { "code": null, "e": 1373, "s": 1223, "text": "The original dictionary : {'gfg': 1, 'is': 2, 'best': 1, 'for': 3, 'CS': 2}\nGrouped dictionary is : {2: ['CS', 'is'], 1: ['best', 'gfg'], 3: ['for']}" }, { "code": null, "e": 1383, "s": 1373, "text": "Method 2:" }, { "code": null, "e": 1618, "s": 1383, "text": "Additionally, This task can also be performed without using any module. So the logic here is: We can check if the keys are present or not 1. No, then we can create key res[v] = [i] 2. Yes, we can append value on the key res[v] + [i] " }, { "code": null, "e": 1626, "s": 1618, "text": "Python3" }, { "code": "d_input = {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'}res = {}for i, v in d_input.items(): res[v] = [i] if v not in res.keys() else res[v] + [i]print(res)", "e": 1804, "s": 1626, "text": null }, { "code": null, "e": 1812, "s": 1804, "text": "Output:" }, { "code": null, "e": 1872, "s": 1812, "text": "{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}" }, { "code": null, "e": 1883, "s": 1872, "text": "mrathore05" }, { "code": null, "e": 1910, "s": 1883, "text": "Python dictionary-programs" }, { "code": null, "e": 1917, "s": 1910, "text": "Python" }, { "code": null, "e": 1933, "s": 1917, "text": "Python Programs" } ]
Implementation of Access Matrix in Distributed OS
08 Jan, 2020 As earlier discussed access matrix is likely to be very sparse and takes up a large chunk of memory. Therefore direct implementation of access matrix for access control is storage inefficient. The inefficiency can be removed by decomposing the access matrix into rows or columns.Rows can be collapsed by deleting null values and so for the columns to increase efficiency. From these approaches of decomposition three implementation of access matrix can be formed which are widely used. They are as follows: 1. Capabilities 2. Access Control List 3. Lock and Key Method So we are going to discuss in brief about the above implementation.Its worth remembering that we are denoting subjects by s and objects by O and putting them on columns and rows respectively. Capabilities:This method refers to row wise decomposition of the access matrix. Each Subject is assigned with a list of tuples (o, M[s, o]) for all objects o that it is allowed to access. This tuples are called Capabilities. If a subject possess a capability (o, M[s, o]) then it is allowed to access object o in the manner which is described in M[s, o]. A subject is allowed to access any objects for which it holds the capabilities.Capabilities are not meant to be forged.Capabilities contain two fields:(i) Object Descriptor, (ii) Access Rights Object Descriptor may contain the address of the objects and Access Rights may contain the rights which the subject has on object, mainly read write, execute. Since object Descriptor contains address it may be used as an addressing mechanism also.Below is the format of capability.Access Control List:This method refers to column wise decomposition of the access matrix . Each object o has a list containing tuples like (s, M[s, o]) for all subjects s which can access the object.P[s, o] denotes the rights of the subject s on the object o.when a subject s request to access to the object o it is executed in the following manner.The system searches the access control list of o to find out if an entry (s, ) exist for subject sIf and entry (s, ) exists for subject s then the system checks to see if the requested access is permitted or not.(i.e., )If the requested access is permitted then the request is executed else an appropriate exception is raised.Below is a sample implementation of Access Control List of an object o.;SubjectsAccess RightraviRead, Write, ExecuteranaReadjeffyWritealiceExecuteEasy revocation and Easy review of an access are the major feature of access control list.Lock and key Method:The lock and key method is an hybrid of the access control list and capabilities method.In the lock and key method, every subject has a capability list that contains tuples of the form (o, key), indicating the subject can access object o using key key. Objects has an access control list that contains tuples of the form (lock, ), called a lock entry indicating lock lock can be accessed by modes in the set .When the subject makes the request to access object o in mode , the system executes in the following manner.The system locates the tuple (o, key) in the capability list of the subject. If no such tuple id found, the access is not permitted.Otherwise the access is permitted only if there exists a lock entry (lock, ) in the access control list of object o such that key=lock and Capabilities:This method refers to row wise decomposition of the access matrix. Each Subject is assigned with a list of tuples (o, M[s, o]) for all objects o that it is allowed to access. This tuples are called Capabilities. If a subject possess a capability (o, M[s, o]) then it is allowed to access object o in the manner which is described in M[s, o]. A subject is allowed to access any objects for which it holds the capabilities.Capabilities are not meant to be forged.Capabilities contain two fields:(i) Object Descriptor, (ii) Access Rights Object Descriptor may contain the address of the objects and Access Rights may contain the rights which the subject has on object, mainly read write, execute. Since object Descriptor contains address it may be used as an addressing mechanism also.Below is the format of capability. Capabilities contain two fields: (i) Object Descriptor, (ii) Access Rights Object Descriptor may contain the address of the objects and Access Rights may contain the rights which the subject has on object, mainly read write, execute. Since object Descriptor contains address it may be used as an addressing mechanism also. Below is the format of capability. Access Control List:This method refers to column wise decomposition of the access matrix . Each object o has a list containing tuples like (s, M[s, o]) for all subjects s which can access the object.P[s, o] denotes the rights of the subject s on the object o.when a subject s request to access to the object o it is executed in the following manner.The system searches the access control list of o to find out if an entry (s, ) exist for subject sIf and entry (s, ) exists for subject s then the system checks to see if the requested access is permitted or not.(i.e., )If the requested access is permitted then the request is executed else an appropriate exception is raised.Below is a sample implementation of Access Control List of an object o.;SubjectsAccess RightraviRead, Write, ExecuteranaReadjeffyWritealiceExecuteEasy revocation and Easy review of an access are the major feature of access control list. when a subject s request to access to the object o it is executed in the following manner. The system searches the access control list of o to find out if an entry (s, ) exist for subject s If and entry (s, ) exists for subject s then the system checks to see if the requested access is permitted or not.(i.e., ) If the requested access is permitted then the request is executed else an appropriate exception is raised. Below is a sample implementation of Access Control List of an object o. ; Easy revocation and Easy review of an access are the major feature of access control list. Lock and key Method:The lock and key method is an hybrid of the access control list and capabilities method.In the lock and key method, every subject has a capability list that contains tuples of the form (o, key), indicating the subject can access object o using key key. Objects has an access control list that contains tuples of the form (lock, ), called a lock entry indicating lock lock can be accessed by modes in the set .When the subject makes the request to access object o in mode , the system executes in the following manner.The system locates the tuple (o, key) in the capability list of the subject. If no such tuple id found, the access is not permitted.Otherwise the access is permitted only if there exists a lock entry (lock, ) in the access control list of object o such that key=lock and In the lock and key method, every subject has a capability list that contains tuples of the form (o, key), indicating the subject can access object o using key key. Objects has an access control list that contains tuples of the form (lock, ), called a lock entry indicating lock lock can be accessed by modes in the set . When the subject makes the request to access object o in mode , the system executes in the following manner. The system locates the tuple (o, key) in the capability list of the subject. If no such tuple id found, the access is not permitted. Otherwise the access is permitted only if there exists a lock entry (lock, ) in the access control list of object o such that key=lock and So this were the the implementations of the access matrix that are most commonly used . We have have Discussed the Processes in a brief and compact way. The usage, advantages and disadvantages can be covered in later posts. Distributed System Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2020" }, { "code": null, "e": 221, "s": 28, "text": "As earlier discussed access matrix is likely to be very sparse and takes up a large chunk of memory. Therefore direct implementation of access matrix for access control is storage inefficient." }, { "code": null, "e": 535, "s": 221, "text": "The inefficiency can be removed by decomposing the access matrix into rows or columns.Rows can be collapsed by deleting null values and so for the columns to increase efficiency. From these approaches of decomposition three implementation of access matrix can be formed which are widely used. They are as follows:" }, { "code": null, "e": 598, "s": 535, "text": "1. Capabilities\n2. Access Control List\n3. Lock and Key Method " }, { "code": null, "e": 790, "s": 598, "text": "So we are going to discuss in brief about the above implementation.Its worth remembering that we are denoting subjects by s and objects by O and putting them on columns and rows respectively." }, { "code": null, "e": 3341, "s": 790, "text": "Capabilities:This method refers to row wise decomposition of the access matrix. Each Subject is assigned with a list of tuples (o, M[s, o]) for all objects o that it is allowed to access. This tuples are called Capabilities. If a subject possess a capability (o, M[s, o]) then it is allowed to access object o in the manner which is described in M[s, o]. A subject is allowed to access any objects for which it holds the capabilities.Capabilities are not meant to be forged.Capabilities contain two fields:(i) Object Descriptor, \n(ii) Access Rights Object Descriptor may contain the address of the objects and Access Rights may contain the rights which the subject has on object, mainly read write, execute. Since object Descriptor contains address it may be used as an addressing mechanism also.Below is the format of capability.Access Control List:This method refers to column wise decomposition of the access matrix . Each object o has a list containing tuples like (s, M[s, o]) for all subjects s which can access the object.P[s, o] denotes the rights of the subject s on the object o.when a subject s request to access to the object o it is executed in the following manner.The system searches the access control list of o to find out if an entry (s, ) exist for subject sIf and entry (s, ) exists for subject s then the system checks to see if the requested access is permitted or not.(i.e., )If the requested access is permitted then the request is executed else an appropriate exception is raised.Below is a sample implementation of Access Control List of an object o.;SubjectsAccess RightraviRead, Write, ExecuteranaReadjeffyWritealiceExecuteEasy revocation and Easy review of an access are the major feature of access control list.Lock and key Method:The lock and key method is an hybrid of the access control list and capabilities method.In the lock and key method, every subject has a capability list that contains tuples of the form (o, key), indicating the subject can access object o using key key. Objects has an access control list that contains tuples of the form (lock, ), called a lock entry indicating lock lock can be accessed by modes in the set .When the subject makes the request to access object o in mode , the system executes in the following manner.The system locates the tuple (o, key) in the capability list of the subject. If no such tuple id found, the access is not permitted.Otherwise the access is permitted only if there exists a lock entry (lock, ) in the access control list of object o such that key=lock and " }, { "code": null, "e": 4172, "s": 3341, "text": "Capabilities:This method refers to row wise decomposition of the access matrix. Each Subject is assigned with a list of tuples (o, M[s, o]) for all objects o that it is allowed to access. This tuples are called Capabilities. If a subject possess a capability (o, M[s, o]) then it is allowed to access object o in the manner which is described in M[s, o]. A subject is allowed to access any objects for which it holds the capabilities.Capabilities are not meant to be forged.Capabilities contain two fields:(i) Object Descriptor, \n(ii) Access Rights Object Descriptor may contain the address of the objects and Access Rights may contain the rights which the subject has on object, mainly read write, execute. Since object Descriptor contains address it may be used as an addressing mechanism also.Below is the format of capability." }, { "code": null, "e": 4205, "s": 4172, "text": "Capabilities contain two fields:" }, { "code": null, "e": 4249, "s": 4205, "text": "(i) Object Descriptor, \n(ii) Access Rights " }, { "code": null, "e": 4497, "s": 4249, "text": "Object Descriptor may contain the address of the objects and Access Rights may contain the rights which the subject has on object, mainly read write, execute. Since object Descriptor contains address it may be used as an addressing mechanism also." }, { "code": null, "e": 4532, "s": 4497, "text": "Below is the format of capability." }, { "code": null, "e": 5445, "s": 4532, "text": "Access Control List:This method refers to column wise decomposition of the access matrix . Each object o has a list containing tuples like (s, M[s, o]) for all subjects s which can access the object.P[s, o] denotes the rights of the subject s on the object o.when a subject s request to access to the object o it is executed in the following manner.The system searches the access control list of o to find out if an entry (s, ) exist for subject sIf and entry (s, ) exists for subject s then the system checks to see if the requested access is permitted or not.(i.e., )If the requested access is permitted then the request is executed else an appropriate exception is raised.Below is a sample implementation of Access Control List of an object o.;SubjectsAccess RightraviRead, Write, ExecuteranaReadjeffyWritealiceExecuteEasy revocation and Easy review of an access are the major feature of access control list." }, { "code": null, "e": 5537, "s": 5445, "text": "when a subject s request to access to the object o it is executed in the following manner." }, { "code": null, "e": 5636, "s": 5537, "text": "The system searches the access control list of o to find out if an entry (s, ) exist for subject s" }, { "code": null, "e": 5759, "s": 5636, "text": "If and entry (s, ) exists for subject s then the system checks to see if the requested access is permitted or not.(i.e., )" }, { "code": null, "e": 5866, "s": 5759, "text": "If the requested access is permitted then the request is executed else an appropriate exception is raised." }, { "code": null, "e": 5938, "s": 5866, "text": "Below is a sample implementation of Access Control List of an object o." }, { "code": null, "e": 5940, "s": 5938, "text": ";" }, { "code": null, "e": 6031, "s": 5940, "text": "Easy revocation and Easy review of an access are the major feature of access control list." }, { "code": null, "e": 6840, "s": 6031, "text": "Lock and key Method:The lock and key method is an hybrid of the access control list and capabilities method.In the lock and key method, every subject has a capability list that contains tuples of the form (o, key), indicating the subject can access object o using key key. Objects has an access control list that contains tuples of the form (lock, ), called a lock entry indicating lock lock can be accessed by modes in the set .When the subject makes the request to access object o in mode , the system executes in the following manner.The system locates the tuple (o, key) in the capability list of the subject. If no such tuple id found, the access is not permitted.Otherwise the access is permitted only if there exists a lock entry (lock, ) in the access control list of object o such that key=lock and " }, { "code": null, "e": 7162, "s": 6840, "text": "In the lock and key method, every subject has a capability list that contains tuples of the form (o, key), indicating the subject can access object o using key key. Objects has an access control list that contains tuples of the form (lock, ), called a lock entry indicating lock lock can be accessed by modes in the set ." }, { "code": null, "e": 7271, "s": 7162, "text": "When the subject makes the request to access object o in mode , the system executes in the following manner." }, { "code": null, "e": 7404, "s": 7271, "text": "The system locates the tuple (o, key) in the capability list of the subject. If no such tuple id found, the access is not permitted." }, { "code": null, "e": 7544, "s": 7404, "text": "Otherwise the access is permitted only if there exists a lock entry (lock, ) in the access control list of object o such that key=lock and " }, { "code": null, "e": 7768, "s": 7544, "text": "So this were the the implementations of the access matrix that are most commonly used . We have have Discussed the Processes in a brief and compact way. The usage, advantages and disadvantages can be covered in later posts." }, { "code": null, "e": 7787, "s": 7768, "text": "Distributed System" }, { "code": null, "e": 7805, "s": 7787, "text": "Operating Systems" }, { "code": null, "e": 7823, "s": 7805, "text": "Operating Systems" } ]
File mkdirs() method in Java with examples
28 Jan, 2019 The mkdirs() method is a part of File class. The mkdirs() function is used to create a new directory denoted by the abstract pathname and also all the non existent parent directories of the abstract pathname. If the mkdirs() function fails to create some directory it might have created some of its parent directories. The function returns true if directory is created else returns false. Function Signature: public boolean mkdirs() Syntax: file.mkdirs() Parameters: This method do not accepts any parameter. Return Value: The function returns boolean data type. The function returns true if directory is created else returns false. Exception: This method throws SecurityException if the method does not allow directory to be created Below programs will illustrate the use of mkdirs() function: Example 1: Try to create a new directory named program in “f:” drive. // Java program to demonstrate// the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program"); // check if the directory can be created // using the abstract path name if (f.mkdirs()) { // display that the directory is created // as the function returned true System.out.println("Directory is created"); } else { // display that the directory cannot be created // as the function returned false System.out.println("Directory cannot be created"); } }} Output: Directory is created Example 2: Try to create a new directory named program1 in “f:\program” directory, but program directory is not created. We will test whether the function mkdirs() can create the parent directories of the abstract pathname if the directories are not present. // Java program to demonstrate// the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File("F:\\program\\program1"); // check if the directory can be created // using the abstract path name if (f.mkdirs()) { // display that the directory is created // as the function returned true System.out.println("Directory is created"); } else { // display that the directory cannot be created // as the function returned false System.out.println("Directory cannot be created"); } }} Output: Directory is created The programs might not run in an online IDE. please use an offline IDE and set the path of the file Java-File Class Java-Functions Java-IO package Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 417, "s": 28, "text": "The mkdirs() method is a part of File class. The mkdirs() function is used to create a new directory denoted by the abstract pathname and also all the non existent parent directories of the abstract pathname. If the mkdirs() function fails to create some directory it might have created some of its parent directories. The function returns true if directory is created else returns false." }, { "code": null, "e": 437, "s": 417, "text": "Function Signature:" }, { "code": null, "e": 461, "s": 437, "text": "public boolean mkdirs()" }, { "code": null, "e": 469, "s": 461, "text": "Syntax:" }, { "code": null, "e": 483, "s": 469, "text": "file.mkdirs()" }, { "code": null, "e": 537, "s": 483, "text": "Parameters: This method do not accepts any parameter." }, { "code": null, "e": 661, "s": 537, "text": "Return Value: The function returns boolean data type. The function returns true if directory is created else returns false." }, { "code": null, "e": 762, "s": 661, "text": "Exception: This method throws SecurityException if the method does not allow directory to be created" }, { "code": null, "e": 823, "s": 762, "text": "Below programs will illustrate the use of mkdirs() function:" }, { "code": null, "e": 893, "s": 823, "text": "Example 1: Try to create a new directory named program in “f:” drive." }, { "code": "// Java program to demonstrate// the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File(\"F:\\\\program\"); // check if the directory can be created // using the abstract path name if (f.mkdirs()) { // display that the directory is created // as the function returned true System.out.println(\"Directory is created\"); } else { // display that the directory cannot be created // as the function returned false System.out.println(\"Directory cannot be created\"); } }}", "e": 1614, "s": 893, "text": null }, { "code": null, "e": 1622, "s": 1614, "text": "Output:" }, { "code": null, "e": 1643, "s": 1622, "text": "Directory is created" }, { "code": null, "e": 1902, "s": 1643, "text": "Example 2: Try to create a new directory named program1 in “f:\\program” directory, but program directory is not created. We will test whether the function mkdirs() can create the parent directories of the abstract pathname if the directories are not present." }, { "code": "// Java program to demonstrate// the use of File.mkdirs() method import java.io.*; public class GFG { public static void main(String args[]) { // create an abstract pathname (File object) File f = new File(\"F:\\\\program\\\\program1\"); // check if the directory can be created // using the abstract path name if (f.mkdirs()) { // display that the directory is created // as the function returned true System.out.println(\"Directory is created\"); } else { // display that the directory cannot be created // as the function returned false System.out.println(\"Directory cannot be created\"); } }}", "e": 2629, "s": 1902, "text": null }, { "code": null, "e": 2637, "s": 2629, "text": "Output:" }, { "code": null, "e": 2658, "s": 2637, "text": "Directory is created" }, { "code": null, "e": 2758, "s": 2658, "text": "The programs might not run in an online IDE. please use an offline IDE and set the path of the file" }, { "code": null, "e": 2774, "s": 2758, "text": "Java-File Class" }, { "code": null, "e": 2789, "s": 2774, "text": "Java-Functions" }, { "code": null, "e": 2805, "s": 2789, "text": "Java-IO package" }, { "code": null, "e": 2819, "s": 2805, "text": "Java Programs" } ]
Even numbers at even index and odd numbers at odd index
31 May, 2022 Given an array of size n containing equal number of odd and even numbers. The problem is to arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index. Required auxiliary space is O(1).Examples : Input : arr[] = {3, 6, 12, 1, 5, 8} Output : 6 3 12 1 8 5 Input : arr[] = {10, 9, 7, 18, 13, 19, 4, 20, 21, 14} Output : 10 9 18 7 20 19 4 13 14 21 Source: Amazon Interview Experience | Set 410. Approach : Start from the left and keep two index one for even position and other for odd positions. Traverse these index from left. At even position there should be even number and at odd positions, there should be odd number. Whenever there is mismatch , we swap the values at odd and even index. Below is the implementation of the above approach : CPP Java Python3 C# Javascript // C++ implementation to arrange// odd and even numbers#include <bits/stdc++.h>using namespace std; // function to arrange odd and even numbersvoid arrangeOddAndEven(int arr[], int n){ int oddInd = 1; int evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) swap (arr[evenInd], arr[oddInd]); else break; }} // function to print the arrayvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver program to test aboveint main(){ int arr[] = { 3, 6, 12, 1, 5, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original Array: "; printArray(arr, n); arrangeOddAndEven(arr, n); cout << "\nModified Array: "; printArray(arr, n); return 0;} // Java implementation to// arrange odd and even numbers import java.util.*;import java.lang.*; class GfG { // function to arrange// odd and even numberspublic static void arrangeOddAndEven(int arr[], int n){ int oddInd = 1; int evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) { int temp = arr[evenInd]; arr[evenInd] = arr[oddInd]; arr[oddInd] = temp; } else break; }} // function to print the arraypublic static void printArray(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Driver functionpublic static void main(String argc[]){ int arr[] = { 3, 6, 12, 1, 5, 8 }; int n = 6; System.out.print("Original Array: "); printArray(arr, n); arrangeOddAndEven(arr, n); System.out.print("\nModified Array: "); printArray(arr, n);}} // This code is contributed by Sagar Shukla # Python3 implementation to# arrange odd and even numbers def arrangeOddAndEven(arr, n): oddInd = 1 evenInd = 0 while (True): while (evenInd < n and arr[evenInd] % 2 == 0): evenInd += 2 while (oddInd < n and arr[oddInd] % 2 == 1): oddInd += 2 if (evenInd < n and oddInd < n): temp = arr[evenInd] arr[evenInd] = arr[oddInd] arr[oddInd] = temp; else: break # function to print the arraydef printArray(arr, n): for i in range(0,n): print(arr[i] , "",end="") # Driver functiondef main(): arr = [ 3, 6, 12, 1, 5, 8 ] n = 6 print("Original Array: ",end="") printArray(arr, n) arrangeOddAndEven(arr, n) print("\nModified Array: ",end="") printArray(arr, n) if __name__ == '__main__': main()# This code is contributed by 29AjayKumar // C# implementation to// arrange odd and even numbersusing System; class GFG { // function to arrange // odd and even numbers public static void arrangeOddAndEven(int[] arr, int n) { int oddInd = 1; int evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) { int temp = arr[evenInd]; arr[evenInd] = arr[oddInd]; arr[oddInd] = temp; } else break; } } // function to print the array public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver function public static void Main() { int[] arr = { 3, 6, 12, 1, 5, 8 }; int n = 6; Console.Write("Original Array: "); printArray(arr, n); arrangeOddAndEven(arr, n); Console.Write("\nModified Array: "); printArray(arr, n); }} // This code is contributed by Sam007 <script> // Javascript implementation to arrange// odd and even numbers // function to arrange odd and even numbersfunction arrangeOddAndEven(arr, n){ let oddInd = 1; let evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) { let temp; temp = arr[evenInd]; arr[evenInd] = arr[oddInd]; arr[oddInd] = temp; } else break; }} // function to print the arrayfunction printArray(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver program to test above let arr = [ 3, 6, 12, 1, 5, 8 ]; let n = arr.length; document.write("Original Array: "); printArray(arr, n); arrangeOddAndEven(arr, n); document.write("<br>" + "Modified Array: "); printArray(arr, n); // This code is contributed by Mayank Tyagi </script> Output : Original Array: 3 6 12 1 5 8 Modified Array: 6 3 12 1 8 5 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space. 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 review-team@geeksforgeeks.org. 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. 29AjayKumar surbhityagi15 mayanktyagi1709 rohitsingh57 array-rearrange Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 304, "s": 52, "text": "Given an array of size n containing equal number of odd and even numbers. The problem is to arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index. Required auxiliary space is O(1).Examples : " }, { "code": null, "e": 455, "s": 304, "text": "Input : arr[] = {3, 6, 12, 1, 5, 8}\nOutput : 6 3 12 1 8 5 \n\nInput : arr[] = {10, 9, 7, 18, 13, 19, 4, 20, 21, 14}\nOutput : 10 9 18 7 20 19 4 13 14 21 " }, { "code": null, "e": 503, "s": 455, "text": "Source: Amazon Interview Experience | Set 410. " }, { "code": null, "e": 516, "s": 503, "text": "Approach : " }, { "code": null, "e": 606, "s": 516, "text": "Start from the left and keep two index one for even position and other for odd positions." }, { "code": null, "e": 638, "s": 606, "text": "Traverse these index from left." }, { "code": null, "e": 733, "s": 638, "text": "At even position there should be even number and at odd positions, there should be odd number." }, { "code": null, "e": 804, "s": 733, "text": "Whenever there is mismatch , we swap the values at odd and even index." }, { "code": null, "e": 857, "s": 804, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 861, "s": 857, "text": "CPP" }, { "code": null, "e": 866, "s": 861, "text": "Java" }, { "code": null, "e": 874, "s": 866, "text": "Python3" }, { "code": null, "e": 877, "s": 874, "text": "C#" }, { "code": null, "e": 888, "s": 877, "text": "Javascript" }, { "code": "// C++ implementation to arrange// odd and even numbers#include <bits/stdc++.h>using namespace std; // function to arrange odd and even numbersvoid arrangeOddAndEven(int arr[], int n){ int oddInd = 1; int evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) swap (arr[evenInd], arr[oddInd]); else break; }} // function to print the arrayvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver program to test aboveint main(){ int arr[] = { 3, 6, 12, 1, 5, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Original Array: \"; printArray(arr, n); arrangeOddAndEven(arr, n); cout << \"\\nModified Array: \"; printArray(arr, n); return 0;}", "e": 1848, "s": 888, "text": null }, { "code": "// Java implementation to// arrange odd and even numbers import java.util.*;import java.lang.*; class GfG { // function to arrange// odd and even numberspublic static void arrangeOddAndEven(int arr[], int n){ int oddInd = 1; int evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) { int temp = arr[evenInd]; arr[evenInd] = arr[oddInd]; arr[oddInd] = temp; } else break; }} // function to print the arraypublic static void printArray(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");} // Driver functionpublic static void main(String argc[]){ int arr[] = { 3, 6, 12, 1, 5, 8 }; int n = 6; System.out.print(\"Original Array: \"); printArray(arr, n); arrangeOddAndEven(arr, n); System.out.print(\"\\nModified Array: \"); printArray(arr, n);}} // This code is contributed by Sagar Shukla", "e": 2998, "s": 1848, "text": null }, { "code": " # Python3 implementation to# arrange odd and even numbers def arrangeOddAndEven(arr, n): oddInd = 1 evenInd = 0 while (True): while (evenInd < n and arr[evenInd] % 2 == 0): evenInd += 2 while (oddInd < n and arr[oddInd] % 2 == 1): oddInd += 2 if (evenInd < n and oddInd < n): temp = arr[evenInd] arr[evenInd] = arr[oddInd] arr[oddInd] = temp; else: break # function to print the arraydef printArray(arr, n): for i in range(0,n): print(arr[i] , \"\",end=\"\") # Driver functiondef main(): arr = [ 3, 6, 12, 1, 5, 8 ] n = 6 print(\"Original Array: \",end=\"\") printArray(arr, n) arrangeOddAndEven(arr, n) print(\"\\nModified Array: \",end=\"\") printArray(arr, n) if __name__ == '__main__': main()# This code is contributed by 29AjayKumar", "e": 3952, "s": 2998, "text": null }, { "code": "// C# implementation to// arrange odd and even numbersusing System; class GFG { // function to arrange // odd and even numbers public static void arrangeOddAndEven(int[] arr, int n) { int oddInd = 1; int evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) { int temp = arr[evenInd]; arr[evenInd] = arr[oddInd]; arr[oddInd] = temp; } else break; } } // function to print the array public static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver function public static void Main() { int[] arr = { 3, 6, 12, 1, 5, 8 }; int n = 6; Console.Write(\"Original Array: \"); printArray(arr, n); arrangeOddAndEven(arr, n); Console.Write(\"\\nModified Array: \"); printArray(arr, n); }} // This code is contributed by Sam007", "e": 5135, "s": 3952, "text": null }, { "code": "<script> // Javascript implementation to arrange// odd and even numbers // function to arrange odd and even numbersfunction arrangeOddAndEven(arr, n){ let oddInd = 1; let evenInd = 0; while (true) { while (evenInd < n && arr[evenInd] % 2 == 0) evenInd += 2; while (oddInd < n && arr[oddInd] % 2 == 1) oddInd += 2; if (evenInd < n && oddInd < n) { let temp; temp = arr[evenInd]; arr[evenInd] = arr[oddInd]; arr[oddInd] = temp; } else break; }} // function to print the arrayfunction printArray(arr, n){ for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver program to test above let arr = [ 3, 6, 12, 1, 5, 8 ]; let n = arr.length; document.write(\"Original Array: \"); printArray(arr, n); arrangeOddAndEven(arr, n); document.write(\"<br>\" + \"Modified Array: \"); printArray(arr, n); // This code is contributed by Mayank Tyagi </script>", "e": 6180, "s": 5135, "text": null }, { "code": null, "e": 6190, "s": 6180, "text": "Output : " }, { "code": null, "e": 6250, "s": 6190, "text": "Original Array: 3 6 12 1 5 8 \nModified Array: 6 3 12 1 8 5 " }, { "code": null, "e": 6317, "s": 6250, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 6377, "s": 6317, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 6799, "s": 6377, "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 review-team@geeksforgeeks.org. 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": 6811, "s": 6799, "text": "29AjayKumar" }, { "code": null, "e": 6825, "s": 6811, "text": "surbhityagi15" }, { "code": null, "e": 6841, "s": 6825, "text": "mayanktyagi1709" }, { "code": null, "e": 6854, "s": 6841, "text": "rohitsingh57" }, { "code": null, "e": 6870, "s": 6854, "text": "array-rearrange" }, { "code": null, "e": 6877, "s": 6870, "text": "Arrays" }, { "code": null, "e": 6884, "s": 6877, "text": "Arrays" } ]
How to create admin login page using PHP?
30 May, 2022 In this article, we will see how we can create a login page for admin, connected with the database, or whose information to log in to the page is already stored in our database. Follow the steps to create an admin login page using PHP: Approach: Make sure you have XAMPP or WAMP installed on your windows machine. In case you’re using Linux OS then install the LAMP server. In this article, we will be using the XAMPP server. 1. Create Database: First, we will create a database named ‘geeksforgeeks‘ (you can give any name to your database). You can also use your existing database or create a new one. create database “geeksforgeeks” 2. Create Table: Create a table named ‘adminlogin’ with 3 columns to store the data. create table “adminlogin” 3. Create Table Structure: The table “adminlogin” contains three fields. id – primary key – auto increment username – varchar(100) password – varchar(100) The datatype for username and password is varchar. The size can be altered as per the requirement. However, 100 is sufficient, and the datatype for “id” is int and it is a primary key. A primary key also called a primary keyword is a key in a relational database that is unique for each record. It is a unique identifier, such as a driver’s license number, telephone number (including area code), or vehicle identification number (VIN). Your table structure should look like this. table structure Or copy and paste the following code into the SQL panel of your PHPMyAdmin. DROP TABLE IF EXISTS `adminlogin`; CREATE TABLE IF NOT EXISTS `adminlogin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; To do this from SQL Panel refer to the following screenshot. create a table from SQL panel 4. Insert admin login information: Here, we are inserting two records in our table. You can add as many as you want. inserting records Or copy and paste the following code to insert records into the SQL panel. INSERT INTO `adminlogin` (`id`, `username`, `password`) VALUES (NULL, 'admin', 'admin'), (NULL, 'admin2', 'admin2'); After inserting the values, the table will look like this. table records 5. Create a folder that includes the following files: The folder should be in “C:\xampp\htdocs\” (or where your XAMPP is installed). For the WAMP server, it should be in “C:\wamp64\www\” and on Linux “/opt/lampp/htdocs”. Filename: index.php HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="login.css"> <title>Login Page</title></head> <body> <form action="validate.php" method="post"> <div class="login-box"> <h1>Login</h1> <div class="textbox"> <i class="fa fa-user" aria-hidden="true"></i> <input type="text" placeholder="Username" name="username" value=""> </div> <div class="textbox"> <i class="fa fa-lock" aria-hidden="true"></i> <input type="password" placeholder="Password" name="password" value=""> </div> <input class="button" type="submit" name="login" value="Sign In"> </div> </form></body> </html> Filename: connection.php PHP <?php $conn = ""; try { $servername = "localhost:3306"; $dbname = "geeksforgeeks"; $username = "root"; $password = ""; $conn = new PDO( "mysql:host=$servername; dbname=geeksforgeeks", $username, $password ); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch(PDOException $e) { echo "Connection failed: " . $e->getMessage();} ?> Filename: login.css CSS body { margin: 0; padding: 0; font-family: sans-serif; background: url() no-repeat; background-size: cover;} .login-box { width: 280px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #191970;} .login-box h1 { float: left; font-size: 40px; border-bottom: 4px solid #191970; margin-bottom: 50px; padding: 13px;} .textbox { width: 100%; overflow: hidden; font-size: 20px; padding: 8px 0; margin: 8px 0; border-bottom: 1px solid #191970;} .fa { width: px; float: left; text-align: center;} .textbox input { border: none; outline: none; background: none; font-size: 18px; float: left; margin: 0 10px;} .button { width: 100%; padding: 8px; color: #ffffff; background: none #191970; border: none; border-radius: 6px; font-size: 18px; cursor: pointer; margin: 12px 0;} Filename: validate.php PHP <?php include_once('connection.php'); function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;} if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = test_input($_POST["username"]); $password = test_input($_POST["password"]); $stmt = $conn->prepare("SELECT * FROM adminlogin"); $stmt->execute(); $users = $stmt->fetchAll(); foreach($users as $user) { if(($user['username'] == $username) && ($user['password'] == $password)) { header("location: adminpage.php"); } else { echo "<script language='javascript'>"; echo "alert('WRONG INFORMATION')"; echo "</script>"; die(); } }} ?> Filename: adminpage.php Add anything that you want to display to the admin page. HTML <h2> Hello Admin </h2> 6. After completing all the above steps, now follow the steps: Run XAMPP server Start Apache and MySQL services from XAMPP Panel. Type http://localhost/loginPage/ in your browser. You will get the following login page screen. If you enter the correct credentials i.e. username and password, then you will be logged in to the “admin.php” page. else, you get an error pop-up alert. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. KarelV hardikkoriintern sanjyotpanure CSS-Misc HTML-Misc PHP-Misc CSS HTML PHP PHP Programs Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 May, 2022" }, { "code": null, "e": 233, "s": 54, "text": "In this article, we will see how we can create a login page for admin, connected with the database, or whose information to log in to the page is already stored in our database. " }, { "code": null, "e": 292, "s": 233, "text": "Follow the steps to create an admin login page using PHP: " }, { "code": null, "e": 483, "s": 292, "text": "Approach: Make sure you have XAMPP or WAMP installed on your windows machine. In case you’re using Linux OS then install the LAMP server. In this article, we will be using the XAMPP server. " }, { "code": null, "e": 662, "s": 483, "text": "1. Create Database: First, we will create a database named ‘geeksforgeeks‘ (you can give any name to your database). You can also use your existing database or create a new one. " }, { "code": null, "e": 694, "s": 662, "text": "create database “geeksforgeeks”" }, { "code": null, "e": 779, "s": 694, "text": "2. Create Table: Create a table named ‘adminlogin’ with 3 columns to store the data." }, { "code": null, "e": 805, "s": 779, "text": "create table “adminlogin”" }, { "code": null, "e": 879, "s": 805, "text": "3. Create Table Structure: The table “adminlogin” contains three fields. " }, { "code": null, "e": 913, "s": 879, "text": "id – primary key – auto increment" }, { "code": null, "e": 937, "s": 913, "text": "username – varchar(100)" }, { "code": null, "e": 961, "s": 937, "text": "password – varchar(100)" }, { "code": null, "e": 1442, "s": 961, "text": "The datatype for username and password is varchar. The size can be altered as per the requirement. However, 100 is sufficient, and the datatype for “id” is int and it is a primary key. A primary key also called a primary keyword is a key in a relational database that is unique for each record. It is a unique identifier, such as a driver’s license number, telephone number (including area code), or vehicle identification number (VIN). Your table structure should look like this." }, { "code": null, "e": 1458, "s": 1442, "text": "table structure" }, { "code": null, "e": 1534, "s": 1458, "text": "Or copy and paste the following code into the SQL panel of your PHPMyAdmin." }, { "code": null, "e": 1784, "s": 1534, "text": "DROP TABLE IF EXISTS `adminlogin`;\nCREATE TABLE IF NOT EXISTS `adminlogin` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `username` varchar(100) NOT NULL,\n `password` varchar(100) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;" }, { "code": null, "e": 1845, "s": 1784, "text": "To do this from SQL Panel refer to the following screenshot." }, { "code": null, "e": 1875, "s": 1845, "text": "create a table from SQL panel" }, { "code": null, "e": 1993, "s": 1875, "text": "4. Insert admin login information: Here, we are inserting two records in our table. You can add as many as you want. " }, { "code": null, "e": 2011, "s": 1993, "text": "inserting records" }, { "code": null, "e": 2086, "s": 2011, "text": "Or copy and paste the following code to insert records into the SQL panel." }, { "code": null, "e": 2203, "s": 2086, "text": "INSERT INTO `adminlogin` (`id`, `username`, `password`) VALUES (NULL, 'admin', 'admin'), (NULL, 'admin2', 'admin2');" }, { "code": null, "e": 2263, "s": 2203, "text": "After inserting the values, the table will look like this. " }, { "code": null, "e": 2277, "s": 2263, "text": "table records" }, { "code": null, "e": 2499, "s": 2277, "text": "5. Create a folder that includes the following files: The folder should be in “C:\\xampp\\htdocs\\” (or where your XAMPP is installed). For the WAMP server, it should be in “C:\\wamp64\\www\\” and on Linux “/opt/lampp/htdocs”. " }, { "code": null, "e": 2520, "s": 2499, "text": "Filename: index.php " }, { "code": null, "e": 2525, "s": 2520, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <link rel=\"stylesheet\" href=\"login.css\"> <title>Login Page</title></head> <body> <form action=\"validate.php\" method=\"post\"> <div class=\"login-box\"> <h1>Login</h1> <div class=\"textbox\"> <i class=\"fa fa-user\" aria-hidden=\"true\"></i> <input type=\"text\" placeholder=\"Username\" name=\"username\" value=\"\"> </div> <div class=\"textbox\"> <i class=\"fa fa-lock\" aria-hidden=\"true\"></i> <input type=\"password\" placeholder=\"Password\" name=\"password\" value=\"\"> </div> <input class=\"button\" type=\"submit\" name=\"login\" value=\"Sign In\"> </div> </form></body> </html>", "e": 3606, "s": 2525, "text": null }, { "code": null, "e": 3631, "s": 3606, "text": "Filename: connection.php" }, { "code": null, "e": 3635, "s": 3631, "text": "PHP" }, { "code": "<?php $conn = \"\"; try { $servername = \"localhost:3306\"; $dbname = \"geeksforgeeks\"; $username = \"root\"; $password = \"\"; $conn = new PDO( \"mysql:host=$servername; dbname=geeksforgeeks\", $username, $password ); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch(PDOException $e) { echo \"Connection failed: \" . $e->getMessage();} ?>", "e": 4047, "s": 3635, "text": null }, { "code": null, "e": 4068, "s": 4047, "text": "Filename: login.css " }, { "code": null, "e": 4072, "s": 4068, "text": "CSS" }, { "code": "body { margin: 0; padding: 0; font-family: sans-serif; background: url() no-repeat; background-size: cover;} .login-box { width: 280px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #191970;} .login-box h1 { float: left; font-size: 40px; border-bottom: 4px solid #191970; margin-bottom: 50px; padding: 13px;} .textbox { width: 100%; overflow: hidden; font-size: 20px; padding: 8px 0; margin: 8px 0; border-bottom: 1px solid #191970;} .fa { width: px; float: left; text-align: center;} .textbox input { border: none; outline: none; background: none; font-size: 18px; float: left; margin: 0 10px;} .button { width: 100%; padding: 8px; color: #ffffff; background: none #191970; border: none; border-radius: 6px; font-size: 18px; cursor: pointer; margin: 12px 0;}", "e": 4988, "s": 4072, "text": null }, { "code": null, "e": 5011, "s": 4988, "text": "Filename: validate.php" }, { "code": null, "e": 5015, "s": 5011, "text": "PHP" }, { "code": "<?php include_once('connection.php'); function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;} if ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") { $username = test_input($_POST[\"username\"]); $password = test_input($_POST[\"password\"]); $stmt = $conn->prepare(\"SELECT * FROM adminlogin\"); $stmt->execute(); $users = $stmt->fetchAll(); foreach($users as $user) { if(($user['username'] == $username) && ($user['password'] == $password)) { header(\"location: adminpage.php\"); } else { echo \"<script language='javascript'>\"; echo \"alert('WRONG INFORMATION')\"; echo \"</script>\"; die(); } }} ?>", "e": 5820, "s": 5015, "text": null }, { "code": null, "e": 5902, "s": 5820, "text": "Filename: adminpage.php Add anything that you want to display to the admin page. " }, { "code": null, "e": 5907, "s": 5902, "text": "HTML" }, { "code": "<h2> Hello Admin </h2>", "e": 5930, "s": 5907, "text": null }, { "code": null, "e": 5994, "s": 5930, "text": "6. After completing all the above steps, now follow the steps: " }, { "code": null, "e": 6011, "s": 5994, "text": "Run XAMPP server" }, { "code": null, "e": 6061, "s": 6011, "text": "Start Apache and MySQL services from XAMPP Panel." }, { "code": null, "e": 6111, "s": 6061, "text": "Type http://localhost/loginPage/ in your browser." }, { "code": null, "e": 6159, "s": 6111, "text": "You will get the following login page screen. " }, { "code": null, "e": 6278, "s": 6159, "text": "If you enter the correct credentials i.e. username and password, then you will be logged in to the “admin.php” page. " }, { "code": null, "e": 6317, "s": 6278, "text": "else, you get an error pop-up alert. " }, { "code": null, "e": 6488, "s": 6319, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 6495, "s": 6488, "text": "KarelV" }, { "code": null, "e": 6512, "s": 6495, "text": "hardikkoriintern" }, { "code": null, "e": 6526, "s": 6512, "text": "sanjyotpanure" }, { "code": null, "e": 6535, "s": 6526, "text": "CSS-Misc" }, { "code": null, "e": 6545, "s": 6535, "text": "HTML-Misc" }, { "code": null, "e": 6554, "s": 6545, "text": "PHP-Misc" }, { "code": null, "e": 6558, "s": 6554, "text": "CSS" }, { "code": null, "e": 6563, "s": 6558, "text": "HTML" }, { "code": null, "e": 6567, "s": 6563, "text": "PHP" }, { "code": null, "e": 6580, "s": 6567, "text": "PHP Programs" }, { "code": null, "e": 6597, "s": 6580, "text": "Web Technologies" }, { "code": null, "e": 6624, "s": 6597, "text": "Web technologies Questions" }, { "code": null, "e": 6629, "s": 6624, "text": "HTML" }, { "code": null, "e": 6633, "s": 6629, "text": "PHP" } ]
Handling TypeError Exception in Python
20 Aug, 2020 TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError. The general causes for TypeError being raised are: 1. Unsupported operation between two types: In the following example, the variable ‘geek’ is a string and the variable ‘num’ is an integer. The + (addition) operator cannot be used between these two types and hence TypeError is raised. Python3 geek = "Geeks"num = 4print(geek + num + geek) Output : TypeError: must be str, not int 2. Calling a non-callable identifier: In the below example code, the variable ‘geek’ is a string and is non-callable in this context. Since it is called in the print statement, TypeError is raised. Python3 geek = "GeeksforGeeks"print(geek()) Output : TypeError: 'str' object is not callable 3. Incorrect type of list index: In Python, list indices must always be an integer value. Since the index value used in the following code is a string, it raises TypeError. Python3 geeky_list = ["geek", "GeeksforGeeks", "geeky", "geekgod"]index = "1"print(geeky_list[index]) Output : TypeError: list indices must be integers or slices, not str 4. Iterating through a non-iterative identifier: In the following code, the value 1234.567890 is a floating-point number and hence it is non-iterative. Forcing Python to iterate on a non-iterative identifier will raise TypeError. Python3 for geek in 1234.567890: print(geek) Output : TypeError: 'float' object is not iterable TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block. In the following example, when one of the indices is found to be an incorrect type, an exception is raised and handled by the program. Python3 geeky_list = ["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"]indices = [0, 1, "2", 3]for i in range(len(indices)): try: print(geeky_list[indices[i]]) except TypeError: print("TypeError: Check list of indices") Output : Geeky GeeksforGeeks TypeError: Check list of indices Geek Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2020" }, { "code": null, "e": 287, "s": 28, "text": "TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError." }, { "code": null, "e": 338, "s": 287, "text": "The general causes for TypeError being raised are:" }, { "code": null, "e": 382, "s": 338, "text": "1. Unsupported operation between two types:" }, { "code": null, "e": 574, "s": 382, "text": "In the following example, the variable ‘geek’ is a string and the variable ‘num’ is an integer. The + (addition) operator cannot be used between these two types and hence TypeError is raised." }, { "code": null, "e": 582, "s": 574, "text": "Python3" }, { "code": "geek = \"Geeks\"num = 4print(geek + num + geek)", "e": 628, "s": 582, "text": null }, { "code": null, "e": 637, "s": 628, "text": "Output :" }, { "code": null, "e": 670, "s": 637, "text": "TypeError: must be str, not int\n" }, { "code": null, "e": 708, "s": 670, "text": "2. Calling a non-callable identifier:" }, { "code": null, "e": 868, "s": 708, "text": "In the below example code, the variable ‘geek’ is a string and is non-callable in this context. Since it is called in the print statement, TypeError is raised." }, { "code": null, "e": 876, "s": 868, "text": "Python3" }, { "code": "geek = \"GeeksforGeeks\"print(geek())", "e": 912, "s": 876, "text": null }, { "code": null, "e": 921, "s": 912, "text": "Output :" }, { "code": null, "e": 962, "s": 921, "text": "TypeError: 'str' object is not callable\n" }, { "code": null, "e": 995, "s": 962, "text": "3. Incorrect type of list index:" }, { "code": null, "e": 1135, "s": 995, "text": "In Python, list indices must always be an integer value. Since the index value used in the following code is a string, it raises TypeError." }, { "code": null, "e": 1143, "s": 1135, "text": "Python3" }, { "code": "geeky_list = [\"geek\", \"GeeksforGeeks\", \"geeky\", \"geekgod\"]index = \"1\"print(geeky_list[index])", "e": 1237, "s": 1143, "text": null }, { "code": null, "e": 1246, "s": 1237, "text": "Output :" }, { "code": null, "e": 1307, "s": 1246, "text": "TypeError: list indices must be integers or slices, not str\n" }, { "code": null, "e": 1356, "s": 1307, "text": "4. Iterating through a non-iterative identifier:" }, { "code": null, "e": 1537, "s": 1356, "text": "In the following code, the value 1234.567890 is a floating-point number and hence it is non-iterative. Forcing Python to iterate on a non-iterative identifier will raise TypeError." }, { "code": null, "e": 1545, "s": 1537, "text": "Python3" }, { "code": "for geek in 1234.567890: print(geek)", "e": 1585, "s": 1545, "text": null }, { "code": null, "e": 1594, "s": 1585, "text": "Output :" }, { "code": null, "e": 1637, "s": 1594, "text": "TypeError: 'float' object is not iterable\n" }, { "code": null, "e": 1983, "s": 1637, "text": "TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block. In the following example, when one of the indices is found to be an incorrect type, an exception is raised and handled by the program." }, { "code": null, "e": 1991, "s": 1983, "text": "Python3" }, { "code": "geeky_list = [\"Geeky\", \"GeeksforGeeks\", \"SuperGeek\", \"Geek\"]indices = [0, 1, \"2\", 3]for i in range(len(indices)): try: print(geeky_list[indices[i]]) except TypeError: print(\"TypeError: Check list of indices\")", "e": 2220, "s": 1991, "text": null }, { "code": null, "e": 2229, "s": 2220, "text": "Output :" }, { "code": null, "e": 2288, "s": 2229, "text": "Geeky\nGeeksforGeeks\nTypeError: Check list of indices\nGeek\n" }, { "code": null, "e": 2306, "s": 2288, "text": "Python-exceptions" }, { "code": null, "e": 2313, "s": 2306, "text": "Python" } ]
How to extract the host name from URL using JavaScript ?
15 Apr, 2020 To extract the hostname portion from a URL, we can use the location object that represents information about the current URL. It is the element of the window object and a client-side object. Syntax: window.location.propertyname Example 1: In this example, we will use the self URL, where the code will run to extract the hostname. Program:<!DOCTYPE html><html> <head> <title> Get domain from URL </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>URL is:</b> <script> document.write(window.location.href); </script> <br> <b>hostname is:</b> <script> document.write(window.location.hostname); </script></body> </html> <!DOCTYPE html><html> <head> <title> Get domain from URL </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>URL is:</b> <script> document.write(window.location.href); </script> <br> <b>hostname is:</b> <script> document.write(window.location.hostname); </script></body> </html> Output: Example 2: In this example, we will ask for the URL to the user and then will perform the extraction of hostname on that URL. Program:<!DOCTYPE html><html> <head> <title>Extracting URL</title></head> <body> <h1 style="color: green;">GeeksforGeeks</h1> <b>Extracting URL</b> <br><br> <form name="f1"> <input type="text" name="txt" placeholder="Paste URL"/> <input type="button" value="click" onclick="url2()" /> </form> <script> function url2() { var url3 = document.f1.txt.value; var j = url3.indexOf("://"); var host = ""; for (i = j + 3; i < url3.length; i++) { if (url3.charAt(i) != '/') { host = host + "" + url3.charAt(i); } else { break; } } document.write(host); } </script></body> </html> <!DOCTYPE html><html> <head> <title>Extracting URL</title></head> <body> <h1 style="color: green;">GeeksforGeeks</h1> <b>Extracting URL</b> <br><br> <form name="f1"> <input type="text" name="txt" placeholder="Paste URL"/> <input type="button" value="click" onclick="url2()" /> </form> <script> function url2() { var url3 = document.f1.txt.value; var j = url3.indexOf("://"); var host = ""; for (i = j + 3; i < url3.length; i++) { if (url3.charAt(i) != '/') { host = host + "" + url3.charAt(i); } else { break; } } document.write(host); } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2020" }, { "code": null, "e": 219, "s": 28, "text": "To extract the hostname portion from a URL, we can use the location object that represents information about the current URL. It is the element of the window object and a client-side object." }, { "code": null, "e": 227, "s": 219, "text": "Syntax:" }, { "code": null, "e": 256, "s": 227, "text": "window.location.propertyname" }, { "code": null, "e": 359, "s": 256, "text": "Example 1: In this example, we will use the self URL, where the code will run to extract the hostname." }, { "code": null, "e": 762, "s": 359, "text": "Program:<!DOCTYPE html><html> <head> <title> Get domain from URL </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>URL is:</b> <script> document.write(window.location.href); </script> <br> <b>hostname is:</b> <script> document.write(window.location.hostname); </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> Get domain from URL </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>URL is:</b> <script> document.write(window.location.href); </script> <br> <b>hostname is:</b> <script> document.write(window.location.hostname); </script></body> </html>", "e": 1157, "s": 762, "text": null }, { "code": null, "e": 1166, "s": 1157, "text": "Output: " }, { "code": null, "e": 1292, "s": 1166, "text": "Example 2: In this example, we will ask for the URL to the user and then will perform the extraction of hostname on that URL." }, { "code": null, "e": 2105, "s": 1292, "text": "Program:<!DOCTYPE html><html> <head> <title>Extracting URL</title></head> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Extracting URL</b> <br><br> <form name=\"f1\"> <input type=\"text\" name=\"txt\" placeholder=\"Paste URL\"/> <input type=\"button\" value=\"click\" onclick=\"url2()\" /> </form> <script> function url2() { var url3 = document.f1.txt.value; var j = url3.indexOf(\"://\"); var host = \"\"; for (i = j + 3; i < url3.length; i++) { if (url3.charAt(i) != '/') { host = host + \"\" + url3.charAt(i); } else { break; } } document.write(host); } </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title>Extracting URL</title></head> <body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Extracting URL</b> <br><br> <form name=\"f1\"> <input type=\"text\" name=\"txt\" placeholder=\"Paste URL\"/> <input type=\"button\" value=\"click\" onclick=\"url2()\" /> </form> <script> function url2() { var url3 = document.f1.txt.value; var j = url3.indexOf(\"://\"); var host = \"\"; for (i = j + 3; i < url3.length; i++) { if (url3.charAt(i) != '/') { host = host + \"\" + url3.charAt(i); } else { break; } } document.write(host); } </script></body> </html>", "e": 2910, "s": 2105, "text": null }, { "code": null, "e": 2918, "s": 2910, "text": "Output:" }, { "code": null, "e": 2927, "s": 2918, "text": "CSS-Misc" }, { "code": null, "e": 2937, "s": 2927, "text": "HTML-Misc" }, { "code": null, "e": 2953, "s": 2937, "text": "JavaScript-Misc" }, { "code": null, "e": 2960, "s": 2953, "text": "Picked" }, { "code": null, "e": 2964, "s": 2960, "text": "CSS" }, { "code": null, "e": 2969, "s": 2964, "text": "HTML" }, { "code": null, "e": 2980, "s": 2969, "text": "JavaScript" }, { "code": null, "e": 2997, "s": 2980, "text": "Web Technologies" }, { "code": null, "e": 3024, "s": 2997, "text": "Web technologies Questions" }, { "code": null, "e": 3029, "s": 3024, "text": "HTML" } ]
Python | Remove None values from list
03 Jan, 2019 Due to the upcoming of Machine Learning, the focus has now moved on handling the None values than ever before, the reason behind this is that it is the essential step of data preprocessing before it is fed into further techniques to perform. Hence, removal of None values in essential and knowledge of it is a must. Let’s discuss certain ways in which this is achieved. Method #1 : Naive MethodIn naive method, we iterate through the whole list and append all the filtered, non-None values into a new list, hence ready to be performed with subsequent operations. # Python3 code to demonstrate # removing None values in list# using naive method # initializing listtest_list = [1, None, 4, None, None, 5, 8, None] # printing original list print ("The original list is : " + str(test_list)) # using naive method # to remove None values in listres = []for val in test_list: if val != None : res.append(val) # printing resultprint ("List after removal of None values : " + str(res)) The original list is : [1, None, 4, None, None, 5, 8, None] List after removal of None values : [1, 4, 5, 8] Method #2 : Using list comprehensionThe longer task of using the naive method and increasing line of codes can be done in a compact way using this method. We just check for True values and construct the new filtered list. # Python3 code to demonstrate # removing None values in list# using list comprehension # initializing listtest_list = [1, None, 4, None, None, 5, 8, None] # printing original list print ("The original list is : " + str(test_list)) # using list comprehension# to remove None values in listres = [i for i in test_list if i] # printing resultprint ("List after removal of None values : " + str(res)) The original list is : [1, None, 4, None, None, 5, 8, None] List after removal of None values : [1, 4, 5, 8] Method #3 : Using filter()filter function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values. # Python3 code to demonstrate # removing None values in list# using filter() # initializing listtest_list = [1, None, 4, None, None, 5, 8, None] # printing original list print ("The original list is : " + str(test_list)) # using filter()# to remove None values in listres = list(filter(None, test_list)) # printing resultprint ("List after removal of None values : " + str(res)) The original list is : [1, None, 4, None, None, 5, 8, None] List after removal of None values : [1, 4, 5, 8] Python list-programs Python Python Programs 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 Read a file line by line in Python Python String | replace() Python program to convert a list to string Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2019" }, { "code": null, "e": 398, "s": 28, "text": "Due to the upcoming of Machine Learning, the focus has now moved on handling the None values than ever before, the reason behind this is that it is the essential step of data preprocessing before it is fed into further techniques to perform. Hence, removal of None values in essential and knowledge of it is a must. Let’s discuss certain ways in which this is achieved." }, { "code": null, "e": 591, "s": 398, "text": "Method #1 : Naive MethodIn naive method, we iterate through the whole list and append all the filtered, non-None values into a new list, hence ready to be performed with subsequent operations." }, { "code": "# Python3 code to demonstrate # removing None values in list# using naive method # initializing listtest_list = [1, None, 4, None, None, 5, 8, None] # printing original list print (\"The original list is : \" + str(test_list)) # using naive method # to remove None values in listres = []for val in test_list: if val != None : res.append(val) # printing resultprint (\"List after removal of None values : \" + str(res))", "e": 1022, "s": 591, "text": null }, { "code": null, "e": 1132, "s": 1022, "text": "The original list is : [1, None, 4, None, None, 5, 8, None]\nList after removal of None values : [1, 4, 5, 8]\n" }, { "code": null, "e": 1355, "s": 1132, "text": " Method #2 : Using list comprehensionThe longer task of using the naive method and increasing line of codes can be done in a compact way using this method. We just check for True values and construct the new filtered list." }, { "code": "# Python3 code to demonstrate # removing None values in list# using list comprehension # initializing listtest_list = [1, None, 4, None, None, 5, 8, None] # printing original list print (\"The original list is : \" + str(test_list)) # using list comprehension# to remove None values in listres = [i for i in test_list if i] # printing resultprint (\"List after removal of None values : \" + str(res))", "e": 1757, "s": 1355, "text": null }, { "code": null, "e": 1867, "s": 1757, "text": "The original list is : [1, None, 4, None, None, 5, 8, None]\nList after removal of None values : [1, 4, 5, 8]\n" }, { "code": null, "e": 2084, "s": 1867, "text": " Method #3 : Using filter()filter function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values." }, { "code": "# Python3 code to demonstrate # removing None values in list# using filter() # initializing listtest_list = [1, None, 4, None, None, 5, 8, None] # printing original list print (\"The original list is : \" + str(test_list)) # using filter()# to remove None values in listres = list(filter(None, test_list)) # printing resultprint (\"List after removal of None values : \" + str(res))", "e": 2468, "s": 2084, "text": null }, { "code": null, "e": 2578, "s": 2468, "text": "The original list is : [1, None, 4, None, None, 5, 8, None]\nList after removal of None values : [1, 4, 5, 8]\n" }, { "code": null, "e": 2599, "s": 2578, "text": "Python list-programs" }, { "code": null, "e": 2606, "s": 2599, "text": "Python" }, { "code": null, "e": 2622, "s": 2606, "text": "Python Programs" }, { "code": null, "e": 2720, "s": 2622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2738, "s": 2720, "text": "Python Dictionary" }, { "code": null, "e": 2780, "s": 2738, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2802, "s": 2780, "text": "Enumerate() in Python" }, { "code": null, "e": 2837, "s": 2802, "text": "Read a file line by line in Python" }, { "code": null, "e": 2863, "s": 2837, "text": "Python String | replace()" }, { "code": null, "e": 2906, "s": 2863, "text": "Python program to convert a list to string" }, { "code": null, "e": 2945, "s": 2906, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2983, "s": 2945, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3020, "s": 2983, "text": "Python Program for Fibonacci numbers" } ]
Program for FCFS CPU Scheduling | Set 2 (Processes with different arrival times)
14 Dec, 2021 We have already discussed FCFS Scheduling of processes with same arrival time. In this post, scenarios, when processes have different arrival times, are discussed. Given n processes with their burst times and arrival times, the task is to find average waiting time and an average turn around time using FCFS scheduling algorithm. FIFO simply queues processes in the order they arrive in the ready queue. Here, the process that comes first will be executed first and next process will start only after the previous gets fully executed. Completion Time: Time at which the process completes its execution.Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival TimeWaiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time. Completion Time: Time at which the process completes its execution. Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time Waiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time. Process Wait Time : Service Time - Arrival Time P0 0 - 0 = 0 P1 5 - 1 = 4 P2 8 - 2 = 6 P3 16 - 3 = 13 Average Wait Time: (0 + 4 + 6 + 13) / 4 = 5.75 Service Time: Service time means amount of time after which a process can start execution. It is summation of burst time of previous processes (Processes that came before) Changes in code as compare to code of FCFS with same arrival time: To find waiting time: Time taken by all processes before the current process to be started (i.e. burst time of all previous processes) – arrival time of current process wait_time[i] = (bt[0] + bt[1] +...... bt[i-1] ) – arrival_time[i] Implementation: 1- Input the processes along with their burst time(bt) and arrival time(at) 2- Find waiting time for all other processes i.e. for a given process i: wt[i] = (bt[0] + bt[1] +...... bt[i-1]) - at[i] 3- Now find turn around time = waiting_time + burst_time for all processes 4- Average waiting time = total_waiting_time / no_of_processes 5- Average turn around time = total_turn_around_time / no_of_processes C++ Java Python3 C# Javascript // C++ program for implementation of FCFS// scheduling with different arrival time#include<iostream>using namespace std; // Function to find the waiting time for all// processesvoid findWaitingTime(int processes[], int n, int bt[], int wt[], int at[]){ int service_time[n]; service_time[0] = at[0]; wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++) { // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 if (wt[i] < 0) wt[i] = 0; }} // Function to calculate turn around timevoid findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]){ // Calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.void findavgTime(int processes[], int n, int bt[], int at[]){ int wt[n], tat[n]; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details cout << "Processes " << " Burst Time " << " Arrival Time " << " Waiting Time " << " Turn-Around Time " << " Completion Time \n"; int total_wt = 0, total_tat = 0; for (int i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; int compl_time = tat[i] + at[i]; cout << " " << i+1 << "\t\t" << bt[i] << "\t\t" << at[i] << "\t\t" << wt[i] << "\t\t " << tat[i] << "\t\t " << compl_time << endl; } cout << "Average waiting time = " << (float)total_wt / (float)n; cout << "\nAverage turn around time = " << (float)total_tat / (float)n;} // Driver codeint main(){ // Process id's int processes[] = {1, 2, 3}; int n = sizeof processes / sizeof processes[0]; // Burst time of all processes int burst_time[] = {5, 9, 6}; // Arrival time of all processes int arrival_time[] = {0, 3, 6}; findavgTime(processes, n, burst_time, arrival_time); return 0;} // Java program for implementation of FCFS// scheduling with different arrival timepublic class GFG{ // Function to find the waiting time for all// processesstatic void findWaitingTime(int processes[], int n, int bt[], int wt[], int at[]){ int service_time[] = new int[n]; service_time[0] = at[0]; wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++) { //representing wasted time in queue int wasted=0; // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 // wasted time is basically time for process to wait after a process is over if (wt[i] < 0) { wasted = Math.abs(wt[i]); wt[i] = 0; } //Add wasted time service_time[i] = service_time[i] + wasted; }} // Function to calculate turn around timestatic void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]){ // Calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.static void findavgTime(int processes[], int n, int bt[], int at[]){ int wt[] = new int[n], tat[] = new int[n]; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details System.out.print("Processes " + " Burst Time " + " Arrival Time " + " Waiting Time " + " Turn-Around Time " + " Completion Time \n"); int total_wt = 0, total_tat = 0; for (int i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; int compl_time = tat[i] + at[i]; System.out.println(i+1 + "\t\t" + bt[i] + "\t\t" + at[i] + "\t\t" + wt[i] + "\t\t " + tat[i] + "\t\t " + compl_time); } System.out.print("Average waiting time = " + (float)total_wt / (float)n); System.out.print("\nAverage turn around time = " + (float)total_tat / (float)n);} // Driver code public static void main(String args[]) { // Process id's int processes[] = {1, 2, 3}; int n = processes.length; // Burst time of all processes int burst_time[] = {5, 9, 6}; // Arrival time of all processes int arrival_time[] = {0, 3, 6}; findavgTime(processes, n, burst_time, arrival_time); }} /*This code is contributed by PrinciRaj1992*/ # Python3 program for implementation of FCFS# scheduling with different arrival time # Function to find the waiting time# for all processesdef findWaitingTime(processes, n, bt, wt, at): service_time = [0] * n service_time[0] = 0 wt[0] = 0 # calculating waiting time for i in range(1, n): # Add burst time of previous processes service_time[i] = (service_time[i - 1] + bt[i - 1]) # Find waiting time for current # process = sum - at[i] wt[i] = service_time[i] - at[i] # If waiting time for a process is in # negative that means it is already # in the ready queue before CPU becomes # idle so its waiting time is 0 if (wt[i] < 0): wt[i] = 0 # Function to calculate turn around timedef findTurnAroundTime(processes, n, bt, wt, tat): # Calculating turnaround time by # adding bt[i] + wt[i] for i in range(n): tat[i] = bt[i] + wt[i] # Function to calculate average waiting# and turn-around times.def findavgTime(processes, n, bt, at): wt = [0] * n tat = [0] * n # Function to find waiting time # of all processes findWaitingTime(processes, n, bt, wt, at) # Function to find turn around time for # all processes findTurnAroundTime(processes, n, bt, wt, tat) # Display processes along with all details print("Processes Burst Time Arrival Time Waiting", "Time Turn-Around Time Completion Time \n") total_wt = 0 total_tat = 0 for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] compl_time = tat[i] + at[i] print(" ", i + 1, "\t\t", bt[i], "\t\t", at[i], "\t\t", wt[i], "\t\t ", tat[i], "\t\t ", compl_time) print("Average waiting time = %.5f "%(total_wt /n)) print("\nAverage turn around time = ", total_tat / n) # Driver codeif __name__ =="__main__": # Process id's processes = [1, 2, 3] n = 3 # Burst time of all processes burst_time = [5, 9, 6] # Arrival time of all processes arrival_time = [0, 3, 6] findavgTime(processes, n, burst_time, arrival_time) # This code is contributed# Shubham Singh(SHUBHAMSINGH10) // C# program for implementation of FCFS// scheduling with different arrival timeusing System; public class GFG{ // Function to find the waiting time for all// processesstatic void findWaitingTime(int []processes, int n, int []bt, int []wt, int []at){ int []service_time = new int[n]; service_time[0] = 0; wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++) { // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 if (wt[i] < 0) wt[i] = 0; }} // Function to calculate turn around timestatic void findTurnAroundTime(int []processes, int n, int[] bt, int []wt, int[] tat){ // Calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.static void findavgTime(int []processes, int n, int []bt, int []at){ int []wt = new int[n]; int []tat = new int[n]; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details Console.Write("Processes " + " Burst Time " + " Arrival Time " + " Waiting Time " + " Turn-Around Time " + " Completion Time \n"); int total_wt = 0, total_tat = 0; for (int i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; int compl_time = tat[i] + at[i]; Console.WriteLine(i+1 + "\t\t" + bt[i] + "\t\t" + at[i] + "\t\t" + wt[i] + "\t\t " + tat[i] + "\t\t " + compl_time); } Console.Write("Average waiting time = " + (float)total_wt / (float)n); Console.Write("\nAverage turn around time = " + (float)total_tat / (float)n);} // Driver code public static void Main(String []args) { // Process id's int []processes = {1, 2, 3}; int n = processes.Length; // Burst time of all processes int []burst_time = {5, 9, 6}; // Arrival time of all processes int []arrival_time = {0, 3, 6}; findavgTime(processes, n, burst_time, arrival_time); }}// This code is contributed by Princi Singh <script> // JavaScript program for implementation of FCFS// scheduling with different arrival time // Function to find the waiting time for all// processesfunction findWaitingTime(processes , n , bt , wt , at){ var service_time = Array.from({length: n}, (_, i) => 0); service_time[0] = at[0]; wt[0] = 0; // calculating waiting time for (var i = 1; i < n ; i++) { //representing wasted time in queue var wasted=0; // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 // wasted time is basically time for process to // wait after a process is over if (wt[i] < 0) { wasted = Math.abs(wt[i]); wt[i] = 0; } // Add wasted time service_time[i] = service_time[i] + wasted; }} // Function to calculate turn around timefunction findTurnAroundTime(processes , n , bt, wt , tat){ // Calculating turnaround time by adding bt[i] + wt[i] for (var i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.function findavgTime(processes , n , bt , at){ var wt = Array.from({length: n}, (_, i) => 0.0); var tat = Array.from({length: n}, (_, i) => 0.0); // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details document.write("Processes " + " Burst Time " + " Arrival Time " + " Waiting Time " + " Turn-Around Time " + " Completion Time <br>"); var total_wt = 0, total_tat = 0; for (var i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; var compl_time = tat[i] + at[i]; document.write(i+1 + " " + bt[i] + " " + at[i] + " " + wt[i] + " " + tat[i] + " " + compl_time+"<br>"); } document.write("<br>Average waiting time = " + total_wt/n +"<br>"); document.write("<br>Average turn around time = " + total_tat/n+"<br>");} // Driver code // Process id's var processes = [1, 2, 3]; var n = processes.length; // Burst time of all processesvar burst_time = [5, 9, 6]; // Arrival time of all processesvar arrival_time = [0, 3, 6]; findavgTime(processes, n, burst_time, arrival_time); // This code is contributed by 29AjayKumar </script> Output: Processes Burst Time Arrival Time Waiting Time Turn-Around Time Completion Time 1 5 0 0 5 5 2 9 3 2 11 14 3 6 6 8 14 20 Average waiting time = 3.33333 Average turn around time = 10.0 This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. princiraj1992 SHUBHAMSINGH10 soumya7 princi singh fakhruddinbadshah18 ritikkanswal 29AjayKumar arorakashish0911 cpu-scheduling Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Dec, 2021" }, { "code": null, "e": 588, "s": 52, "text": "We have already discussed FCFS Scheduling of processes with same arrival time. In this post, scenarios, when processes have different arrival times, are discussed. Given n processes with their burst times and arrival times, the task is to find average waiting time and an average turn around time using FCFS scheduling algorithm. FIFO simply queues processes in the order they arrive in the ready queue. Here, the process that comes first will be executed first and next process will start only after the previous gets fully executed. " }, { "code": null, "e": 902, "s": 588, "text": "Completion Time: Time at which the process completes its execution.Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival TimeWaiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time." }, { "code": null, "e": 970, "s": 902, "text": "Completion Time: Time at which the process completes its execution." }, { "code": null, "e": 1096, "s": 970, "text": "Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time" }, { "code": null, "e": 1218, "s": 1096, "text": "Waiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time." }, { "code": null, "e": 1483, "s": 1218, "text": "Process Wait Time : Service Time - Arrival Time\n P0 0 - 0 = 0\n P1 5 - 1 = 4\n P2 8 - 2 = 6\n P3 16 - 3 = 13\n\nAverage Wait Time: (0 + 4 + 6 + 13) / 4 = 5.75" }, { "code": null, "e": 1655, "s": 1483, "text": "Service Time: Service time means amount of time after which a process can start execution. It is summation of burst time of previous processes (Processes that came before)" }, { "code": null, "e": 1957, "s": 1655, "text": "Changes in code as compare to code of FCFS with same arrival time: To find waiting time: Time taken by all processes before the current process to be started (i.e. burst time of all previous processes) – arrival time of current process wait_time[i] = (bt[0] + bt[1] +...... bt[i-1] ) – arrival_time[i]" }, { "code": null, "e": 1974, "s": 1957, "text": "Implementation: " }, { "code": null, "e": 2445, "s": 1974, "text": "1- Input the processes along with their burst time(bt)\n and arrival time(at)\n2- Find waiting time for all other processes i.e. for\n a given process i:\n wt[i] = (bt[0] + bt[1] +...... bt[i-1]) - at[i] \n3- Now find turn around time \n = waiting_time + burst_time for all processes\n4- Average waiting time = \n total_waiting_time / no_of_processes\n5- Average turn around time = \n total_turn_around_time / no_of_processes" }, { "code": null, "e": 2449, "s": 2445, "text": "C++" }, { "code": null, "e": 2454, "s": 2449, "text": "Java" }, { "code": null, "e": 2462, "s": 2454, "text": "Python3" }, { "code": null, "e": 2465, "s": 2462, "text": "C#" }, { "code": null, "e": 2476, "s": 2465, "text": "Javascript" }, { "code": "// C++ program for implementation of FCFS// scheduling with different arrival time#include<iostream>using namespace std; // Function to find the waiting time for all// processesvoid findWaitingTime(int processes[], int n, int bt[], int wt[], int at[]){ int service_time[n]; service_time[0] = at[0]; wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++) { // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 if (wt[i] < 0) wt[i] = 0; }} // Function to calculate turn around timevoid findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]){ // Calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.void findavgTime(int processes[], int n, int bt[], int at[]){ int wt[n], tat[n]; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details cout << \"Processes \" << \" Burst Time \" << \" Arrival Time \" << \" Waiting Time \" << \" Turn-Around Time \" << \" Completion Time \\n\"; int total_wt = 0, total_tat = 0; for (int i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; int compl_time = tat[i] + at[i]; cout << \" \" << i+1 << \"\\t\\t\" << bt[i] << \"\\t\\t\" << at[i] << \"\\t\\t\" << wt[i] << \"\\t\\t \" << tat[i] << \"\\t\\t \" << compl_time << endl; } cout << \"Average waiting time = \" << (float)total_wt / (float)n; cout << \"\\nAverage turn around time = \" << (float)total_tat / (float)n;} // Driver codeint main(){ // Process id's int processes[] = {1, 2, 3}; int n = sizeof processes / sizeof processes[0]; // Burst time of all processes int burst_time[] = {5, 9, 6}; // Arrival time of all processes int arrival_time[] = {0, 3, 6}; findavgTime(processes, n, burst_time, arrival_time); return 0;}", "e": 5024, "s": 2476, "text": null }, { "code": "// Java program for implementation of FCFS// scheduling with different arrival timepublic class GFG{ // Function to find the waiting time for all// processesstatic void findWaitingTime(int processes[], int n, int bt[], int wt[], int at[]){ int service_time[] = new int[n]; service_time[0] = at[0]; wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++) { //representing wasted time in queue int wasted=0; // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 // wasted time is basically time for process to wait after a process is over if (wt[i] < 0) { wasted = Math.abs(wt[i]); wt[i] = 0; } //Add wasted time service_time[i] = service_time[i] + wasted; }} // Function to calculate turn around timestatic void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]){ // Calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.static void findavgTime(int processes[], int n, int bt[], int at[]){ int wt[] = new int[n], tat[] = new int[n]; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details System.out.print(\"Processes \" + \" Burst Time \" + \" Arrival Time \" + \" Waiting Time \" + \" Turn-Around Time \" + \" Completion Time \\n\"); int total_wt = 0, total_tat = 0; for (int i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; int compl_time = tat[i] + at[i]; System.out.println(i+1 + \"\\t\\t\" + bt[i] + \"\\t\\t\" + at[i] + \"\\t\\t\" + wt[i] + \"\\t\\t \" + tat[i] + \"\\t\\t \" + compl_time); } System.out.print(\"Average waiting time = \" + (float)total_wt / (float)n); System.out.print(\"\\nAverage turn around time = \" + (float)total_tat / (float)n);} // Driver code public static void main(String args[]) { // Process id's int processes[] = {1, 2, 3}; int n = processes.length; // Burst time of all processes int burst_time[] = {5, 9, 6}; // Arrival time of all processes int arrival_time[] = {0, 3, 6}; findavgTime(processes, n, burst_time, arrival_time); }} /*This code is contributed by PrinciRaj1992*/", "e": 7902, "s": 5024, "text": null }, { "code": "# Python3 program for implementation of FCFS# scheduling with different arrival time # Function to find the waiting time# for all processesdef findWaitingTime(processes, n, bt, wt, at): service_time = [0] * n service_time[0] = 0 wt[0] = 0 # calculating waiting time for i in range(1, n): # Add burst time of previous processes service_time[i] = (service_time[i - 1] + bt[i - 1]) # Find waiting time for current # process = sum - at[i] wt[i] = service_time[i] - at[i] # If waiting time for a process is in # negative that means it is already # in the ready queue before CPU becomes # idle so its waiting time is 0 if (wt[i] < 0): wt[i] = 0 # Function to calculate turn around timedef findTurnAroundTime(processes, n, bt, wt, tat): # Calculating turnaround time by # adding bt[i] + wt[i] for i in range(n): tat[i] = bt[i] + wt[i] # Function to calculate average waiting# and turn-around times.def findavgTime(processes, n, bt, at): wt = [0] * n tat = [0] * n # Function to find waiting time # of all processes findWaitingTime(processes, n, bt, wt, at) # Function to find turn around time for # all processes findTurnAroundTime(processes, n, bt, wt, tat) # Display processes along with all details print(\"Processes Burst Time Arrival Time Waiting\", \"Time Turn-Around Time Completion Time \\n\") total_wt = 0 total_tat = 0 for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] compl_time = tat[i] + at[i] print(\" \", i + 1, \"\\t\\t\", bt[i], \"\\t\\t\", at[i], \"\\t\\t\", wt[i], \"\\t\\t \", tat[i], \"\\t\\t \", compl_time) print(\"Average waiting time = %.5f \"%(total_wt /n)) print(\"\\nAverage turn around time = \", total_tat / n) # Driver codeif __name__ ==\"__main__\": # Process id's processes = [1, 2, 3] n = 3 # Burst time of all processes burst_time = [5, 9, 6] # Arrival time of all processes arrival_time = [0, 3, 6] findavgTime(processes, n, burst_time, arrival_time) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)", "e": 10174, "s": 7902, "text": null }, { "code": "// C# program for implementation of FCFS// scheduling with different arrival timeusing System; public class GFG{ // Function to find the waiting time for all// processesstatic void findWaitingTime(int []processes, int n, int []bt, int []wt, int []at){ int []service_time = new int[n]; service_time[0] = 0; wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++) { // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 if (wt[i] < 0) wt[i] = 0; }} // Function to calculate turn around timestatic void findTurnAroundTime(int []processes, int n, int[] bt, int []wt, int[] tat){ // Calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.static void findavgTime(int []processes, int n, int []bt, int []at){ int []wt = new int[n]; int []tat = new int[n]; // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details Console.Write(\"Processes \" + \" Burst Time \" + \" Arrival Time \" + \" Waiting Time \" + \" Turn-Around Time \" + \" Completion Time \\n\"); int total_wt = 0, total_tat = 0; for (int i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; int compl_time = tat[i] + at[i]; Console.WriteLine(i+1 + \"\\t\\t\" + bt[i] + \"\\t\\t\" + at[i] + \"\\t\\t\" + wt[i] + \"\\t\\t \" + tat[i] + \"\\t\\t \" + compl_time); } Console.Write(\"Average waiting time = \" + (float)total_wt / (float)n); Console.Write(\"\\nAverage turn around time = \" + (float)total_tat / (float)n);} // Driver code public static void Main(String []args) { // Process id's int []processes = {1, 2, 3}; int n = processes.Length; // Burst time of all processes int []burst_time = {5, 9, 6}; // Arrival time of all processes int []arrival_time = {0, 3, 6}; findavgTime(processes, n, burst_time, arrival_time); }}// This code is contributed by Princi Singh", "e": 12800, "s": 10174, "text": null }, { "code": "<script> // JavaScript program for implementation of FCFS// scheduling with different arrival time // Function to find the waiting time for all// processesfunction findWaitingTime(processes , n , bt , wt , at){ var service_time = Array.from({length: n}, (_, i) => 0); service_time[0] = at[0]; wt[0] = 0; // calculating waiting time for (var i = 1; i < n ; i++) { //representing wasted time in queue var wasted=0; // Add burst time of previous processes service_time[i] = service_time[i-1] + bt[i-1]; // Find waiting time for current process = // sum - at[i] wt[i] = service_time[i] - at[i]; // If waiting time for a process is in negative // that means it is already in the ready queue // before CPU becomes idle so its waiting time is 0 // wasted time is basically time for process to // wait after a process is over if (wt[i] < 0) { wasted = Math.abs(wt[i]); wt[i] = 0; } // Add wasted time service_time[i] = service_time[i] + wasted; }} // Function to calculate turn around timefunction findTurnAroundTime(processes , n , bt, wt , tat){ // Calculating turnaround time by adding bt[i] + wt[i] for (var i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} // Function to calculate average waiting and turn-around// times.function findavgTime(processes , n , bt , at){ var wt = Array.from({length: n}, (_, i) => 0.0); var tat = Array.from({length: n}, (_, i) => 0.0); // Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt, at); // Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details document.write(\"Processes \" + \" Burst Time \" + \" Arrival Time \" + \" Waiting Time \" + \" Turn-Around Time \" + \" Completion Time <br>\"); var total_wt = 0, total_tat = 0; for (var i = 0 ; i < n ; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; var compl_time = tat[i] + at[i]; document.write(i+1 + \" \" + bt[i] + \" \" + at[i] + \" \" + wt[i] + \" \" + tat[i] + \" \" + compl_time+\"<br>\"); } document.write(\"<br>Average waiting time = \" + total_wt/n +\"<br>\"); document.write(\"<br>Average turn around time = \" + total_tat/n+\"<br>\");} // Driver code // Process id's var processes = [1, 2, 3]; var n = processes.length; // Burst time of all processesvar burst_time = [5, 9, 6]; // Arrival time of all processesvar arrival_time = [0, 3, 6]; findavgTime(processes, n, burst_time, arrival_time); // This code is contributed by 29AjayKumar </script>", "e": 15593, "s": 12800, "text": null }, { "code": null, "e": 15602, "s": 15593, "text": "Output: " }, { "code": null, "e": 15905, "s": 15602, "text": "Processes Burst Time Arrival Time Waiting Time Turn-Around Time Completion Time \n 1 5 0 0 5 5\n 2 9 3 2 11 14\n 3 6 6 8 14 20\nAverage waiting time = 3.33333\nAverage turn around time = 10.0" }, { "code": null, "e": 16333, "s": 15905, "text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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": 16347, "s": 16333, "text": "princiraj1992" }, { "code": null, "e": 16362, "s": 16347, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 16370, "s": 16362, "text": "soumya7" }, { "code": null, "e": 16383, "s": 16370, "text": "princi singh" }, { "code": null, "e": 16403, "s": 16383, "text": "fakhruddinbadshah18" }, { "code": null, "e": 16416, "s": 16403, "text": "ritikkanswal" }, { "code": null, "e": 16428, "s": 16416, "text": "29AjayKumar" }, { "code": null, "e": 16445, "s": 16428, "text": "arorakashish0911" }, { "code": null, "e": 16460, "s": 16445, "text": "cpu-scheduling" }, { "code": null, "e": 16478, "s": 16460, "text": "Operating Systems" }, { "code": null, "e": 16496, "s": 16478, "text": "Operating Systems" } ]
Read, Write and Parse JSON using Python
18 Aug, 2021 JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Example: s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}' The syntax of JSON is considered as a subset of the syntax of JavaScript including the following: Name/Value pairs: Represents Data, name is followed by ‘:'(colon) and the Name/Value pairs separated by, (comma). Curly braces: Holds objects. Square brackets: Hold arrays with values separated by, (comma). Keys/Name must be strings with double quotes and values must be data types amongst the following: String Number Object (JSON object) array Boolean Null Example: { "employee": [ { "id": "01", "name": "Amit", "department": "Sales" }, { "id": "04", "name": "sunil", "department": "HR" } ] } json.loads() method can parse a json string and the result will be a Python dictionary.Syntax: json.loads(json_string) Example: Python3 # Python program to convert JSON to Python import json # JSON stringemployee ='{"id":"09", "name": "Nitin", "department":"Finance"}' # Convert string to Python dictemployee_dict = json.loads(employee)print(employee_dict) print(employee_dict['name']) Output: {'id': '09', 'department': 'Finance', 'name': 'Nitin'} Nitin json.load() method can read a file which contains a JSON object. Consider a file named employee.json which contains a JSON object.Syntax: json.load(file_object) Example: Let’s suppose the JSON looks like this. We want to read the content of this file. Below is the implementation. Python3 # Python program to read# json file import json # Opening JSON filef = open('data.json',) # returns JSON object as # a dictionarydata = json.load(f) # Iterating through the json# listfor i in data['emp_details']: print(i) # Closing filef.close() Output: Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data. json.dumps() method can convert a Python object into a JSON string. Syntax: json.dumps(dict, indent) It takes two parameters: dictionary – name of dictionary which should be converted to JSON object. indent – defines the number of units for indentation Example: Python3 # Python program to convert# Python to JSON import json # Data to be writtendictionary ={ "id": "04", "name": "sunil", "department": "HR"} # Serializing json json_object = json.dumps(dictionary, indent = 4)print(json_object) { "id": "04", "name": "sunil", "department": "HR" } Output: { "depatment": "HR", "id": "04", "name": "sunil" } The following types of Python objects can be converted into JSON strings: dict list tuple string int float True False None Python objects and their equivalent conversion to JSON: json.dump() method can be used for writing to JSON file.Syntax: json.dump(dict, file_pointer) It takes 2 parameters: dictionary – name of dictionary which should be converted to JSON object. file pointer – pointer of the file opened in write or append mode. Python3 # Python program to write JSON# to a file import json # Data to be writtendictionary ={ "name" : "sathiyajith", "rollno" : 56, "cgpa" : 8.6, "phonenumber" : "9976770500"} with open("sample.json", "w") as outfile: json.dump(dictionary, outfile) Output: The above program opens a file named sample.json in writing mode using ‘w’. The file will be created if it does not exist. Json.dump() will transform dictionary to a JSON string and it will be saved in the file sample.json. gulshankumarar231 Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2021" }, { "code": null, "e": 315, "s": 52, "text": "JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. " }, { "code": null, "e": 388, "s": 315, "text": "Example:\ns = '{\"id\":01, \"name\": \"Emily\", \"language\": [\"C++\", \"Python\"]}'" }, { "code": null, "e": 486, "s": 388, "text": "The syntax of JSON is considered as a subset of the syntax of JavaScript including the following:" }, { "code": null, "e": 600, "s": 486, "text": "Name/Value pairs: Represents Data, name is followed by ‘:'(colon) and the Name/Value pairs separated by, (comma)." }, { "code": null, "e": 629, "s": 600, "text": "Curly braces: Holds objects." }, { "code": null, "e": 693, "s": 629, "text": "Square brackets: Hold arrays with values separated by, (comma)." }, { "code": null, "e": 793, "s": 693, "text": "Keys/Name must be strings with double quotes and values must be data types amongst the following: " }, { "code": null, "e": 800, "s": 793, "text": "String" }, { "code": null, "e": 807, "s": 800, "text": "Number" }, { "code": null, "e": 828, "s": 807, "text": "Object (JSON object)" }, { "code": null, "e": 834, "s": 828, "text": "array" }, { "code": null, "e": 842, "s": 834, "text": "Boolean" }, { "code": null, "e": 847, "s": 842, "text": "Null" }, { "code": null, "e": 1070, "s": 847, "text": "Example:\n {\n \"employee\": [\n\n {\n \"id\": \"01\",\n \"name\": \"Amit\",\n \"department\": \"Sales\"\n },\n\n {\n \"id\": \"04\",\n \"name\": \"sunil\",\n \"department\": \"HR\"\n }\n ]\n}" }, { "code": null, "e": 1165, "s": 1070, "text": "json.loads() method can parse a json string and the result will be a Python dictionary.Syntax:" }, { "code": null, "e": 1189, "s": 1165, "text": "json.loads(json_string)" }, { "code": null, "e": 1198, "s": 1189, "text": "Example:" }, { "code": null, "e": 1206, "s": 1198, "text": "Python3" }, { "code": "# Python program to convert JSON to Python import json # JSON stringemployee ='{\"id\":\"09\", \"name\": \"Nitin\", \"department\":\"Finance\"}' # Convert string to Python dictemployee_dict = json.loads(employee)print(employee_dict) print(employee_dict['name'])", "e": 1462, "s": 1206, "text": null }, { "code": null, "e": 1471, "s": 1462, "text": "Output: " }, { "code": null, "e": 1532, "s": 1471, "text": "{'id': '09', 'department': 'Finance', 'name': 'Nitin'}\nNitin" }, { "code": null, "e": 1670, "s": 1532, "text": "json.load() method can read a file which contains a JSON object. Consider a file named employee.json which contains a JSON object.Syntax:" }, { "code": null, "e": 1693, "s": 1670, "text": "json.load(file_object)" }, { "code": null, "e": 1742, "s": 1693, "text": "Example: Let’s suppose the JSON looks like this." }, { "code": null, "e": 1813, "s": 1742, "text": "We want to read the content of this file. Below is the implementation." }, { "code": null, "e": 1821, "s": 1813, "text": "Python3" }, { "code": "# Python program to read# json file import json # Opening JSON filef = open('data.json',) # returns JSON object as # a dictionarydata = json.load(f) # Iterating through the json# listfor i in data['emp_details']: print(i) # Closing filef.close()", "e": 2083, "s": 1821, "text": null }, { "code": null, "e": 2091, "s": 2083, "text": "Output:" }, { "code": null, "e": 2243, "s": 2091, "text": "Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data." }, { "code": null, "e": 2319, "s": 2243, "text": "json.dumps() method can convert a Python object into a JSON string. Syntax:" }, { "code": null, "e": 2344, "s": 2319, "text": "json.dumps(dict, indent)" }, { "code": null, "e": 2369, "s": 2344, "text": "It takes two parameters:" }, { "code": null, "e": 2443, "s": 2369, "text": "dictionary – name of dictionary which should be converted to JSON object." }, { "code": null, "e": 2496, "s": 2443, "text": "indent – defines the number of units for indentation" }, { "code": null, "e": 2506, "s": 2496, "text": "Example: " }, { "code": null, "e": 2514, "s": 2506, "text": "Python3" }, { "code": "# Python program to convert# Python to JSON import json # Data to be writtendictionary ={ \"id\": \"04\", \"name\": \"sunil\", \"department\": \"HR\"} # Serializing json json_object = json.dumps(dictionary, indent = 4)print(json_object)", "e": 2751, "s": 2514, "text": null }, { "code": null, "e": 2816, "s": 2751, "text": "{\n \"id\": \"04\",\n \"name\": \"sunil\",\n \"department\": \"HR\"\n}\n" }, { "code": null, "e": 2825, "s": 2816, "text": "Output: " }, { "code": null, "e": 2888, "s": 2825, "text": "{\n \"depatment\": \"HR\",\n \"id\": \"04\",\n \"name\": \"sunil\"\n}" }, { "code": null, "e": 2964, "s": 2888, "text": "The following types of Python objects can be converted into JSON strings: " }, { "code": null, "e": 2969, "s": 2964, "text": "dict" }, { "code": null, "e": 2974, "s": 2969, "text": "list" }, { "code": null, "e": 2980, "s": 2974, "text": "tuple" }, { "code": null, "e": 2987, "s": 2980, "text": "string" }, { "code": null, "e": 2991, "s": 2987, "text": "int" }, { "code": null, "e": 2997, "s": 2991, "text": "float" }, { "code": null, "e": 3002, "s": 2997, "text": "True" }, { "code": null, "e": 3008, "s": 3002, "text": "False" }, { "code": null, "e": 3013, "s": 3008, "text": "None" }, { "code": null, "e": 3069, "s": 3013, "text": "Python objects and their equivalent conversion to JSON:" }, { "code": null, "e": 3133, "s": 3069, "text": "json.dump() method can be used for writing to JSON file.Syntax:" }, { "code": null, "e": 3163, "s": 3133, "text": "json.dump(dict, file_pointer)" }, { "code": null, "e": 3186, "s": 3163, "text": "It takes 2 parameters:" }, { "code": null, "e": 3260, "s": 3186, "text": "dictionary – name of dictionary which should be converted to JSON object." }, { "code": null, "e": 3327, "s": 3260, "text": "file pointer – pointer of the file opened in write or append mode." }, { "code": null, "e": 3335, "s": 3327, "text": "Python3" }, { "code": "# Python program to write JSON# to a file import json # Data to be writtendictionary ={ \"name\" : \"sathiyajith\", \"rollno\" : 56, \"cgpa\" : 8.6, \"phonenumber\" : \"9976770500\"} with open(\"sample.json\", \"w\") as outfile: json.dump(dictionary, outfile)", "e": 3603, "s": 3335, "text": null }, { "code": null, "e": 3611, "s": 3603, "text": "Output:" }, { "code": null, "e": 3835, "s": 3611, "text": "The above program opens a file named sample.json in writing mode using ‘w’. The file will be created if it does not exist. Json.dump() will transform dictionary to a JSON string and it will be saved in the file sample.json." }, { "code": null, "e": 3853, "s": 3835, "text": "gulshankumarar231" }, { "code": null, "e": 3865, "s": 3853, "text": "Python-json" }, { "code": null, "e": 3872, "s": 3865, "text": "Python" } ]
Find Kth largest element from right of every element in the array - GeeksforGeeks
16 Mar, 2022 Given an array arr[] of size N and an integer K. The task is to find the Kth largest element from the right of every element in the array. If there are not enough elements to the right then print the same element. Examples: Input: N = 6, K = 3, arr[] = {4, 5, 3, 6, 7, 2}Output: 5 3 2 6 7 2Explanation: The elements right to 4 are {5, 3, 6, 7, 2}. So 3rd largest element to the right of 4 is 5. Similarly, repeat the process for the rest of the elements.And 7 and 2 does not have sufficient element to the right.So, they are kept as it is. Input: N = 5, K = 2, arr[] = {-4, 7, 5, 3, 0}Output: 5 3 0 3 0 Naive Approach: The naive approach is to sort every subarray to the right of every element and check whether the Kth largest element exists or not. If it exists, print the Kth largest element, else print the same element. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the Kth// largest element to the right// of every elementint getKLargest(int* arr, int r, int l, int& K){ // Elements to the right // of current element vector<int> v(arr, arr + l + 1); // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector sort(v.begin() + r + 1, v.end()); return v[l - K + 1]; } else return v[r];} // Driver Codeint main(){ int arr[] = { -4, 7, 5, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; for (int i = 0; i < N; i++) cout << getKLargest(arr, i, N - 1, K) << " "; return 0;} // Java code for the above approachimport java.util.*; class GFG{ // Function to sort the elements of the array // from index a to index b static void sort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index // range int l = Math.min(a, b); int r = Math.max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Arrays.sort(temp); // Modifying original array with temporary array // elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } } // Function to find the Kth // largest element to the right // of every element static int getKLargest(int[] arr, int r, int l, int K) { // Elements to the right // of current element int n = arr.length; int[] v = new int[l + 1]; for (int i = 0; i < l + 1; i++) { v[i] = arr[i]; } // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector sort(v, n, r + 1, n - 1); return v[l - K + 1]; } else return v[r]; } // Driver Code public static void main(String[] args) { int arr[] = { -4, 7, 5, 3, 0 }; int N = arr.length; int K = 2; for (int i = 0; i < N; i++) System.out.print(getKLargest(arr, i, N - 1, K) + " "); }} // This code is contributed by code_hunt. # Python code for the above approach # Function to find the Kth# largest element to the right# of every elementdef getKLargest(arr, r, l, K): # Elements to the right # of current element v = arr[0: l + 1] # There are greater than K elements # to the right if (l - r >= K): # Sort the vector temp1 = v[0: r + 1] temp = v[r + 1:] temp.sort() v = temp1 + temp return v[l - K + 1] else: return v[r] # Driver Codearr = [-4, 7, 5, 3, 0]N = len(arr)K = 2 for i in range(N): print(getKLargest(arr, i, N - 1, K), end=" ") # This code is contributed by Saurabh Jaiswal // C# program for the above approachusing System;class GFG{ // Function to sort the elements of the array // from index a to index b static void sort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index // range int l = Math.Min(a, b); int r = Math.Max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Array.Sort(temp); // Modifying original array with temporary array // elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } } // Function to find the Kth // largest element to the right // of every element static int getKLargest(int[] arr, int r, int l, int K) { // Elements to the right // of current element int n = arr.Length; int[] v = new int[l + 1]; for (int i = 0; i < l + 1; i++) { v[i] = arr[i]; } // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector sort(v, n, r + 1, n - 1); return v[l - K + 1]; } else return v[r]; } // Driver Code public static void Main() { int[] arr = { -4, 7, 5, 3, 0 }; int N = arr.Length; int K = 2; for (int i = 0; i < N; i++) Console.Write(getKLargest(arr, i, N - 1, K) + " "); }}// This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to find the Kth // largest element to the right // of every element function getKLargest(arr, r, l, K) { // Elements to the right // of current element let v = arr.slice(0, l + 1); // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector let temp1 = v.slice(0, r + 1); let temp = v.slice(r + 1); temp.sort(function (a, b) { return a - b }) v = temp1.concat(temp) return v[l - K + 1]; } else return v[r]; } // Driver Code let arr = [-4, 7, 5, 3, 0]; let N = arr.length; let K = 2; for (let i = 0; i < N; i++) document.write(getKLargest(arr, i, N - 1, K) + " ") // This code is contributed by Potta Lokesh </script> 5 3 0 3 0 Time Complexity: O(N2 * logN)Auxiliary Space: O(N) Approach based on Sets: Another approach is to use sets. Though both the approaches have same the time complexity, sets have an inbuilt sorting feature, it doesn’t require explicit sorting. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the kth largest// element to the rightint getKLargest(vector<int>& arr, int r, int l, int& k){ set<int> s(arr.begin() + r + 1, arr.end()); if (l - r >= k) { set<int>::iterator it = s.end(); advance(it, -k); return *it; } else return arr[r];} // Driver codeint main(){ int arr[] = { -4, 7, 5, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); int i, K = 2; vector<int> a(arr, arr + N); for (i = 0; i < N; i++) cout << getKLargest(a, i, N - 1, K) << " "; return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the kth largest// element to the rightstatic int getKLargest(List<Integer> arr, int r, int l, int k){ HashSet<Integer> s = new HashSet<>(arr.subList(r+1,arr.size())); List<Integer> a = new ArrayList<>(s); if (l - r >= k) { return a.get(a.size()-k); } else return arr.get(r);} // Driver codepublic static void main(String[] args){ Integer arr[] = { -4, 7, 5, 3, 0 }; int N = arr.length; int i=0; int K = 2; List<Integer> a = Arrays.asList(arr); for (i = 0; i < N; i++) System.out.print(getKLargest(a, i, N - 1, K) + " ");}} // This code is contributed by shikhasingrajput # Python3 program for the above approach # def to find the kth largest# element to the rightdef getKLargest( arr , r , l , k): s = set() for i in range(r+1,len(arr)): s.add(arr[i]) a = [] for p in s: a.append(p) if(l - r >= k): return a[len(a)- k] else: return arr[r] # Driver code arr = [ -4, 7, 5, 3, 0 ]N = len(arr)i = 0K = 2 a = arr for i in range(N): print(getKLargest(a, i, N - 1, K) ,end=" ") # This code is contributed by shinjanpatra // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the kth largest // element to the right static int getKLargest(List<int> arr, int r, int l, int k) { HashSet<int> s = new HashSet<int>(arr.GetRange(r+1,arr.Count-(r+1))); List<int> a = new List<int>(s); a.Reverse(); if (l - r >= k) { return a[a.Count-k]; } else return arr[r]; } // Driver code public static void Main(String[] args) { int []arr = { -4, 7, 5, 3, 0 }; int N = arr.Length; int i=0; int K = 2; List<int> a = new List<int>(arr); for (i = 0; i < N; i++) Console.Write(getKLargest(a, i, N - 1, K) + " "); }} // This code is contributed by 29AjayKumar <script>// javascript program for the above approach // Function to find the kth largest // element to the right function getKLargest( arr , r , l , k) { var s = new Set(); for(let i = r+1;i<arr.length;i++) s.add(arr[i]); // <>(arr.subList(r + 1, arr.size())); var a = []; for(let p of s) a.push(p); a.reverse(); if (l - r >= k) { return a[a.length - k]; } else return arr[r]; } // Driver code var arr = [ -4, 7, 5, 3, 0 ]; var N = arr.length; var i = 0; var K = 2; var a = (arr); for (var i = 0; i < N; i++) document.write(getKLargest(a, i, N - 1, K) + " "); // This code contributed by Rajput-Ji</script> 5 3 0 3 0 Time Complexity: O(N2 * logN)Auxiliary Space: O(N) lokeshpotta20 _saurabh_jaiswal samim2000 code_hunt shikhasingrajput 29AjayKumar Rajput-Ji shinjanpatra Algo-Geek 2021 Algo Geek Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if an edge is a part of any Minimum Spanning Tree Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Check if the given string is valid English word or not Divide given number into two even parts Sort strings on the basis of their numeric part Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 27657, "s": 27629, "text": "\n16 Mar, 2022" }, { "code": null, "e": 27871, "s": 27657, "text": "Given an array arr[] of size N and an integer K. The task is to find the Kth largest element from the right of every element in the array. If there are not enough elements to the right then print the same element." }, { "code": null, "e": 27881, "s": 27871, "text": "Examples:" }, { "code": null, "e": 28197, "s": 27881, "text": "Input: N = 6, K = 3, arr[] = {4, 5, 3, 6, 7, 2}Output: 5 3 2 6 7 2Explanation: The elements right to 4 are {5, 3, 6, 7, 2}. So 3rd largest element to the right of 4 is 5. Similarly, repeat the process for the rest of the elements.And 7 and 2 does not have sufficient element to the right.So, they are kept as it is." }, { "code": null, "e": 28260, "s": 28197, "text": "Input: N = 5, K = 2, arr[] = {-4, 7, 5, 3, 0}Output: 5 3 0 3 0" }, { "code": null, "e": 28482, "s": 28260, "text": "Naive Approach: The naive approach is to sort every subarray to the right of every element and check whether the Kth largest element exists or not. If it exists, print the Kth largest element, else print the same element." }, { "code": null, "e": 28533, "s": 28482, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28539, "s": 28533, "text": "C++14" }, { "code": null, "e": 28544, "s": 28539, "text": "Java" }, { "code": null, "e": 28552, "s": 28544, "text": "Python3" }, { "code": null, "e": 28555, "s": 28552, "text": "C#" }, { "code": null, "e": 28566, "s": 28555, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the Kth// largest element to the right// of every elementint getKLargest(int* arr, int r, int l, int& K){ // Elements to the right // of current element vector<int> v(arr, arr + l + 1); // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector sort(v.begin() + r + 1, v.end()); return v[l - K + 1]; } else return v[r];} // Driver Codeint main(){ int arr[] = { -4, 7, 5, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; for (int i = 0; i < N; i++) cout << getKLargest(arr, i, N - 1, K) << \" \"; return 0;}", "e": 29317, "s": 28566, "text": null }, { "code": "// Java code for the above approachimport java.util.*; class GFG{ // Function to sort the elements of the array // from index a to index b static void sort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index // range int l = Math.min(a, b); int r = Math.max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Arrays.sort(temp); // Modifying original array with temporary array // elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } } // Function to find the Kth // largest element to the right // of every element static int getKLargest(int[] arr, int r, int l, int K) { // Elements to the right // of current element int n = arr.length; int[] v = new int[l + 1]; for (int i = 0; i < l + 1; i++) { v[i] = arr[i]; } // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector sort(v, n, r + 1, n - 1); return v[l - K + 1]; } else return v[r]; } // Driver Code public static void main(String[] args) { int arr[] = { -4, 7, 5, 3, 0 }; int N = arr.length; int K = 2; for (int i = 0; i < N; i++) System.out.print(getKLargest(arr, i, N - 1, K) + \" \"); }} // This code is contributed by code_hunt.", "e": 30781, "s": 29317, "text": null }, { "code": "# Python code for the above approach # Function to find the Kth# largest element to the right# of every elementdef getKLargest(arr, r, l, K): # Elements to the right # of current element v = arr[0: l + 1] # There are greater than K elements # to the right if (l - r >= K): # Sort the vector temp1 = v[0: r + 1] temp = v[r + 1:] temp.sort() v = temp1 + temp return v[l - K + 1] else: return v[r] # Driver Codearr = [-4, 7, 5, 3, 0]N = len(arr)K = 2 for i in range(N): print(getKLargest(arr, i, N - 1, K), end=\" \") # This code is contributed by Saurabh Jaiswal", "e": 31417, "s": 30781, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to sort the elements of the array // from index a to index b static void sort(int[] arr, int N, int a, int b) { // Variables to store start and end of the index // range int l = Math.Min(a, b); int r = Math.Max(a, b); // Temporary array int[] temp = new int[r - l + 1]; int j = 0; for (int i = l; i <= r; i++) { temp[j] = arr[i]; j++; } // Sort the temporary array Array.Sort(temp); // Modifying original array with temporary array // elements j = 0; for (int i = l; i <= r; i++) { arr[i] = temp[j]; j++; } } // Function to find the Kth // largest element to the right // of every element static int getKLargest(int[] arr, int r, int l, int K) { // Elements to the right // of current element int n = arr.Length; int[] v = new int[l + 1]; for (int i = 0; i < l + 1; i++) { v[i] = arr[i]; } // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector sort(v, n, r + 1, n - 1); return v[l - K + 1]; } else return v[r]; } // Driver Code public static void Main() { int[] arr = { -4, 7, 5, 3, 0 }; int N = arr.Length; int K = 2; for (int i = 0; i < N; i++) Console.Write(getKLargest(arr, i, N - 1, K) + \" \"); }}// This code is contributed by Samim Hossain Mondal.", "e": 32865, "s": 31417, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the Kth // largest element to the right // of every element function getKLargest(arr, r, l, K) { // Elements to the right // of current element let v = arr.slice(0, l + 1); // There are greater than K elements // to the right if (l - r >= K) { // Sort the vector let temp1 = v.slice(0, r + 1); let temp = v.slice(r + 1); temp.sort(function (a, b) { return a - b }) v = temp1.concat(temp) return v[l - K + 1]; } else return v[r]; } // Driver Code let arr = [-4, 7, 5, 3, 0]; let N = arr.length; let K = 2; for (let i = 0; i < N; i++) document.write(getKLargest(arr, i, N - 1, K) + \" \") // This code is contributed by Potta Lokesh </script>", "e": 33901, "s": 32865, "text": null }, { "code": null, "e": 33915, "s": 33904, "text": "5 3 0 3 0 " }, { "code": null, "e": 33968, "s": 33917, "text": "Time Complexity: O(N2 * logN)Auxiliary Space: O(N)" }, { "code": null, "e": 34160, "s": 33970, "text": "Approach based on Sets: Another approach is to use sets. Though both the approaches have same the time complexity, sets have an inbuilt sorting feature, it doesn’t require explicit sorting." }, { "code": null, "e": 34213, "s": 34162, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34221, "s": 34215, "text": "C++14" }, { "code": null, "e": 34226, "s": 34221, "text": "Java" }, { "code": null, "e": 34234, "s": 34226, "text": "Python3" }, { "code": null, "e": 34237, "s": 34234, "text": "C#" }, { "code": null, "e": 34248, "s": 34237, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the kth largest// element to the rightint getKLargest(vector<int>& arr, int r, int l, int& k){ set<int> s(arr.begin() + r + 1, arr.end()); if (l - r >= k) { set<int>::iterator it = s.end(); advance(it, -k); return *it; } else return arr[r];} // Driver codeint main(){ int arr[] = { -4, 7, 5, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); int i, K = 2; vector<int> a(arr, arr + N); for (i = 0; i < N; i++) cout << getKLargest(a, i, N - 1, K) << \" \"; return 0;}", "e": 34919, "s": 34248, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the kth largest// element to the rightstatic int getKLargest(List<Integer> arr, int r, int l, int k){ HashSet<Integer> s = new HashSet<>(arr.subList(r+1,arr.size())); List<Integer> a = new ArrayList<>(s); if (l - r >= k) { return a.get(a.size()-k); } else return arr.get(r);} // Driver codepublic static void main(String[] args){ Integer arr[] = { -4, 7, 5, 3, 0 }; int N = arr.length; int i=0; int K = 2; List<Integer> a = Arrays.asList(arr); for (i = 0; i < N; i++) System.out.print(getKLargest(a, i, N - 1, K) + \" \");}} // This code is contributed by shikhasingrajput", "e": 35661, "s": 34919, "text": null }, { "code": "# Python3 program for the above approach # def to find the kth largest# element to the rightdef getKLargest( arr , r , l , k): s = set() for i in range(r+1,len(arr)): s.add(arr[i]) a = [] for p in s: a.append(p) if(l - r >= k): return a[len(a)- k] else: return arr[r] # Driver code arr = [ -4, 7, 5, 3, 0 ]N = len(arr)i = 0K = 2 a = arr for i in range(N): print(getKLargest(a, i, N - 1, K) ,end=\" \") # This code is contributed by shinjanpatra", "e": 36151, "s": 35661, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the kth largest // element to the right static int getKLargest(List<int> arr, int r, int l, int k) { HashSet<int> s = new HashSet<int>(arr.GetRange(r+1,arr.Count-(r+1))); List<int> a = new List<int>(s); a.Reverse(); if (l - r >= k) { return a[a.Count-k]; } else return arr[r]; } // Driver code public static void Main(String[] args) { int []arr = { -4, 7, 5, 3, 0 }; int N = arr.Length; int i=0; int K = 2; List<int> a = new List<int>(arr); for (i = 0; i < N; i++) Console.Write(getKLargest(a, i, N - 1, K) + \" \"); }} // This code is contributed by 29AjayKumar", "e": 36941, "s": 36151, "text": null }, { "code": "<script>// javascript program for the above approach // Function to find the kth largest // element to the right function getKLargest( arr , r , l , k) { var s = new Set(); for(let i = r+1;i<arr.length;i++) s.add(arr[i]); // <>(arr.subList(r + 1, arr.size())); var a = []; for(let p of s) a.push(p); a.reverse(); if (l - r >= k) { return a[a.length - k]; } else return arr[r]; } // Driver code var arr = [ -4, 7, 5, 3, 0 ]; var N = arr.length; var i = 0; var K = 2; var a = (arr); for (var i = 0; i < N; i++) document.write(getKLargest(a, i, N - 1, K) + \" \"); // This code contributed by Rajput-Ji</script>", "e": 37717, "s": 36941, "text": null }, { "code": null, "e": 37731, "s": 37720, "text": "5 3 0 3 0 " }, { "code": null, "e": 37784, "s": 37733, "text": "Time Complexity: O(N2 * logN)Auxiliary Space: O(N)" }, { "code": null, "e": 37800, "s": 37786, "text": "lokeshpotta20" }, { "code": null, "e": 37817, "s": 37800, "text": "_saurabh_jaiswal" }, { "code": null, "e": 37827, "s": 37817, "text": "samim2000" }, { "code": null, "e": 37837, "s": 37827, "text": "code_hunt" }, { "code": null, "e": 37854, "s": 37837, "text": "shikhasingrajput" }, { "code": null, "e": 37866, "s": 37854, "text": "29AjayKumar" }, { "code": null, "e": 37876, "s": 37866, "text": "Rajput-Ji" }, { "code": null, "e": 37889, "s": 37876, "text": "shinjanpatra" }, { "code": null, "e": 37904, "s": 37889, "text": "Algo-Geek 2021" }, { "code": null, "e": 37914, "s": 37904, "text": "Algo Geek" }, { "code": null, "e": 37921, "s": 37914, "text": "Arrays" }, { "code": null, "e": 37929, "s": 37921, "text": "Sorting" }, { "code": null, "e": 37936, "s": 37929, "text": "Arrays" }, { "code": null, "e": 37944, "s": 37936, "text": "Sorting" }, { "code": null, "e": 38042, "s": 37944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38098, "s": 38042, "text": "Check if an edge is a part of any Minimum Spanning Tree" }, { "code": null, "e": 38178, "s": 38098, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 38233, "s": 38178, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 38273, "s": 38233, "text": "Divide given number into two even parts" }, { "code": null, "e": 38321, "s": 38273, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 38336, "s": 38321, "text": "Arrays in Java" }, { "code": null, "e": 38352, "s": 38336, "text": "Arrays in C/C++" }, { "code": null, "e": 38420, "s": 38352, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38466, "s": 38420, "text": "Write a program to reverse an array or string" } ]
Header Guard in C++ - GeeksforGeeks
02 Nov, 2020 Header Guards in C++ are conditional compilation directives that help to avoid errors that arise when the same function or variable is defined more than once by the mistake of a programmer. According to C++, when a function or a variable is defined more than once, it yields an error. Below is the program to illustrate the same: Program 1: C++ // C++ program to illustrate error// caused due to defining same// function more than once#include <iostream>using namespace std; // Function 1void fool(){ cout << "hello";} // Function 2void fool(){ cout << "hello maddy";} // Driver Codeint main(){ // Function Call fool(); return 0;} Output: Explanation:In the above program, a function fool() has been defined twice which is causing a fatal error. Program 2: C++ // C++ program to illustrate error// caused due to defining same// variable more than once#include <iostream>using namespace std; // Driver Codeint main(){ // error: note: 'double x' previously double x{}; // declared here int x{ 2 }; return 0;} Output: Explanation:In the above program, the variable x has been defined twice which is causing a fatal error. These are the most commonly occurring errors and can be fixed with a very basic knowledge of programming. But if a situation arises where a Header file is included in a program and inadvertently a forward declaration of a function is done which has been a part of the already included header file. In that case, the content of the header file is not remembered, no matter whether it’s user-defined or predefined. So further, a fatal error is encountered which sometimes becomes unresolvable. For this, C++is armed with some preprocessor directives that avoid this error. Let there is a header file named pentagon.h as below: C++ // Function to get the side of// the pentagonint getting_pentagon_side(){ // Return the side return 5;} Let there be another header file named “mathematics.h” that includes the header file “pentagon.h”. C++ // Including another header file// "pentagon.h" in the current program#include "pentagon.h" Now, a C++ program is created with the name “pentagon.cpp” as shown below: Program 3: C++ // C++ program to illustrate the error// discussed above#include <iostream> // Include header files created#include "mathematics.h"#include "pentagon.h"using namespace std; // Driver Codeint main(){ return 0;} Output: To solve the error caused above, the idea is to use the concept of “Header Guard” to avoid errors that occur when the same function variable is defined more than once by the mistake of the programmer. A header guard can avoid such errors by using Conditional Compilation directives. It is a combination of Conditional Compilation directives that protect your header from being included in a program multiple numbers of times. Syntax: #ifndef HEADER_H_NAME #define HEADER_H_NAME /*... ...*/ #endif Now, Let’s come to the previous example and see how the error conflict can be resolved: First, the “pentagon.h” header file is modified as: #ifndef PENTAGON_H #define PENTAGON_H int getting_pentagon_side() { return 5; } #endif Now the “mathematics.h” header file that includes “pentagon.h” is modified as: #ifndef MATHEMATICS_H #define MATHEMATICS_H #include "pentagon.h" #endif Below is the program after the above changes to avoid the errors: C++ // C++ program to illustrate how to// avoid errors using Header Guard#include <iostream> // Include header guards in both// the header files#include "mathematics.h" // Now, the error will not occur#include "pentagon.h" using namespace std; // Driver Codeint main(){ // Function Call to find the // sides of the pentagon int i{ getting pentagon side() }; // Print the sides cout << "sides in a pentagon is: " << i; return 0;} Output: CPP-Basics cpp-macros C++ C++ Programs Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 25369, "s": 25341, "text": "\n02 Nov, 2020" }, { "code": null, "e": 25699, "s": 25369, "text": "Header Guards in C++ are conditional compilation directives that help to avoid errors that arise when the same function or variable is defined more than once by the mistake of a programmer. According to C++, when a function or a variable is defined more than once, it yields an error. Below is the program to illustrate the same:" }, { "code": null, "e": 25710, "s": 25699, "text": "Program 1:" }, { "code": null, "e": 25714, "s": 25710, "text": "C++" }, { "code": "// C++ program to illustrate error// caused due to defining same// function more than once#include <iostream>using namespace std; // Function 1void fool(){ cout << \"hello\";} // Function 2void fool(){ cout << \"hello maddy\";} // Driver Codeint main(){ // Function Call fool(); return 0;}", "e": 26020, "s": 25714, "text": null }, { "code": null, "e": 26028, "s": 26020, "text": "Output:" }, { "code": null, "e": 26135, "s": 26028, "text": "Explanation:In the above program, a function fool() has been defined twice which is causing a fatal error." }, { "code": null, "e": 26146, "s": 26135, "text": "Program 2:" }, { "code": null, "e": 26150, "s": 26146, "text": "C++" }, { "code": "// C++ program to illustrate error// caused due to defining same// variable more than once#include <iostream>using namespace std; // Driver Codeint main(){ // error: note: 'double x' previously double x{}; // declared here int x{ 2 }; return 0;}", "e": 26416, "s": 26150, "text": null }, { "code": null, "e": 26424, "s": 26416, "text": "Output:" }, { "code": null, "e": 26528, "s": 26424, "text": "Explanation:In the above program, the variable x has been defined twice which is causing a fatal error." }, { "code": null, "e": 26942, "s": 26528, "text": "These are the most commonly occurring errors and can be fixed with a very basic knowledge of programming. But if a situation arises where a Header file is included in a program and inadvertently a forward declaration of a function is done which has been a part of the already included header file. In that case, the content of the header file is not remembered, no matter whether it’s user-defined or predefined. " }, { "code": null, "e": 27100, "s": 26942, "text": "So further, a fatal error is encountered which sometimes becomes unresolvable. For this, C++is armed with some preprocessor directives that avoid this error." }, { "code": null, "e": 27154, "s": 27100, "text": "Let there is a header file named pentagon.h as below:" }, { "code": null, "e": 27158, "s": 27154, "text": "C++" }, { "code": "// Function to get the side of// the pentagonint getting_pentagon_side(){ // Return the side return 5;}", "e": 27268, "s": 27158, "text": null }, { "code": null, "e": 27367, "s": 27268, "text": "Let there be another header file named “mathematics.h” that includes the header file “pentagon.h”." }, { "code": null, "e": 27371, "s": 27367, "text": "C++" }, { "code": "// Including another header file// \"pentagon.h\" in the current program#include \"pentagon.h\"", "e": 27463, "s": 27371, "text": null }, { "code": null, "e": 27538, "s": 27463, "text": "Now, a C++ program is created with the name “pentagon.cpp” as shown below:" }, { "code": null, "e": 27549, "s": 27538, "text": "Program 3:" }, { "code": null, "e": 27553, "s": 27549, "text": "C++" }, { "code": "// C++ program to illustrate the error// discussed above#include <iostream> // Include header files created#include \"mathematics.h\"#include \"pentagon.h\"using namespace std; // Driver Codeint main(){ return 0;}", "e": 27770, "s": 27553, "text": null }, { "code": null, "e": 27778, "s": 27770, "text": "Output:" }, { "code": null, "e": 27979, "s": 27778, "text": "To solve the error caused above, the idea is to use the concept of “Header Guard” to avoid errors that occur when the same function variable is defined more than once by the mistake of the programmer." }, { "code": null, "e": 28204, "s": 27979, "text": "A header guard can avoid such errors by using Conditional Compilation directives. It is a combination of Conditional Compilation directives that protect your header from being included in a program multiple numbers of times." }, { "code": null, "e": 28212, "s": 28204, "text": "Syntax:" }, { "code": null, "e": 28276, "s": 28212, "text": "#ifndef HEADER_H_NAME\n#define HEADER_H_NAME\n/*...\n...*/\n#endif\n" }, { "code": null, "e": 28364, "s": 28276, "text": "Now, Let’s come to the previous example and see how the error conflict can be resolved:" }, { "code": null, "e": 28416, "s": 28364, "text": "First, the “pentagon.h” header file is modified as:" }, { "code": null, "e": 28507, "s": 28416, "text": "#ifndef PENTAGON_H\n#define PENTAGON_H\n\nint getting_pentagon_side()\n{ \nreturn 5;\n}\n#endif\n\n" }, { "code": null, "e": 28586, "s": 28507, "text": "Now the “mathematics.h” header file that includes “pentagon.h” is modified as:" }, { "code": null, "e": 28661, "s": 28586, "text": "#ifndef MATHEMATICS_H\n#define MATHEMATICS_H\n#include \"pentagon.h\"\n#endif\n\n" }, { "code": null, "e": 28727, "s": 28661, "text": "Below is the program after the above changes to avoid the errors:" }, { "code": null, "e": 28731, "s": 28727, "text": "C++" }, { "code": "// C++ program to illustrate how to// avoid errors using Header Guard#include <iostream> // Include header guards in both// the header files#include \"mathematics.h\" // Now, the error will not occur#include \"pentagon.h\" using namespace std; // Driver Codeint main(){ // Function Call to find the // sides of the pentagon int i{ getting pentagon side() }; // Print the sides cout << \"sides in a pentagon is: \" << i; return 0;}", "e": 29190, "s": 28731, "text": null }, { "code": null, "e": 29198, "s": 29190, "text": "Output:" }, { "code": null, "e": 29209, "s": 29198, "text": "CPP-Basics" }, { "code": null, "e": 29220, "s": 29209, "text": "cpp-macros" }, { "code": null, "e": 29224, "s": 29220, "text": "C++" }, { "code": null, "e": 29237, "s": 29224, "text": "C++ Programs" }, { "code": null, "e": 29258, "s": 29237, "text": "Programming Language" }, { "code": null, "e": 29262, "s": 29258, "text": "CPP" }, { "code": null, "e": 29360, "s": 29262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29388, "s": 29360, "text": "Operator Overloading in C++" }, { "code": null, "e": 29408, "s": 29388, "text": "Polymorphism in C++" }, { "code": null, "e": 29441, "s": 29408, "text": "Friend class and function in C++" }, { "code": null, "e": 29465, "s": 29441, "text": "Sorting a vector in C++" }, { "code": null, "e": 29490, "s": 29465, "text": "std::string class in C++" }, { "code": null, "e": 29525, "s": 29490, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 29569, "s": 29525, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 29595, "s": 29569, "text": "C++ Program for QuickSort" }, { "code": null, "e": 29654, "s": 29595, "text": "How to return multiple values from a function in C or C++?" } ]
Deep Learning with PyTorch | An Introduction - GeeksforGeeks
07 Feb, 2019 PyTorch in a lot of ways behaves like the arrays we love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation) and another module specifically for building neural networks. All together, PyTorch ends up being more flexible with Python and the Numpy stack compared to TensorFlow and other frameworks. Neural Networks:Deep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply “neurons.” Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit’s output.Below is an example of a simple neural net. Tensors:It turns out neural network computations are just a bunch of linear algebra operations on tensors, which are a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor. The fundamental data structure for neural networks are tensors and PyTorch is built around tensors. It’s time to explore how we can use PyTorch to build a simple neural network. # First, import PyTorchimport torch Define an activation function(sigmoid) to compute the linear output def activation(x): """ Sigmoid activation function Arguments --------- x: torch.Tensor """ return 1/(1 + torch.exp(-x)) # Generate some data # Features are 3 random normal variablesfeatures = torch.randn((1, 5)) # True weights for our data, random normal variables againweights = torch.randn_like(features) # and a true bias termbias = torch.randn((1, 1)) features = torch.randn((1, 5)) creates a tensor with shape (1, 5), one row and five columns, that contains values randomly distributed according to the normal distribution with a mean of zero and standard deviation of one. weights = torch.randn_like(features) creates another tensor with the same shape as features, again containing values from a normal distribution. Finally, bias = torch.randn((1, 1)) creates a single value from a normal distribution. Now we calculate the output of the network using matrix multiplication. y = activation(torch.mm(features, weights.view(5, 1)) + bias) That’s how we can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix. We define the structure of neural network and initialize the weights and biases. # Features are 3 random normal variablesfeatures = torch.randn((1, 3)) # Define the size of each layer in our network # Number of input units, must match number of input featuresn_input = features.shape[1] n_hidden = 2 # Number of hidden units n_output = 1 # Number of output units # Weights for inputs to hidden layerW1 = torch.randn(n_input, n_hidden) # Weights for hidden layer to output layerW2 = torch.randn(n_hidden, n_output) # and bias terms for hidden and output layersB1 = torch.randn((1, n_hidden))B2 = torch.randn((1, n_output)) Now we can calculate the output for this multi-layer network using the weights W1 & W2, and the biases, B1 & B2. h = activation(torch.mm(features, W1) + B1)output = activation(torch.mm(h, W2) + B2)print(output) Python-PyTorch Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Decision Tree Introduction with example Activation functions in Neural Networks Python | Decision tree implementation Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25543, "s": 25515, "text": "\n07 Feb, 2019" }, { "code": null, "e": 26071, "s": 25543, "text": "PyTorch in a lot of ways behaves like the arrays we love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation) and another module specifically for building neural networks. All together, PyTorch ends up being more flexible with Python and the Numpy stack compared to TensorFlow and other frameworks." }, { "code": null, "e": 26533, "s": 26071, "text": "Neural Networks:Deep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply “neurons.” Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit’s output.Below is an example of a simple neural net." }, { "code": null, "e": 26907, "s": 26533, "text": "Tensors:It turns out neural network computations are just a bunch of linear algebra operations on tensors, which are a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor. The fundamental data structure for neural networks are tensors and PyTorch is built around tensors." }, { "code": null, "e": 26985, "s": 26907, "text": "It’s time to explore how we can use PyTorch to build a simple neural network." }, { "code": "# First, import PyTorchimport torch", "e": 27021, "s": 26985, "text": null }, { "code": null, "e": 27089, "s": 27021, "text": "Define an activation function(sigmoid) to compute the linear output" }, { "code": "def activation(x): \"\"\" Sigmoid activation function Arguments --------- x: torch.Tensor \"\"\" return 1/(1 + torch.exp(-x))", "e": 27246, "s": 27089, "text": null }, { "code": "# Generate some data # Features are 3 random normal variablesfeatures = torch.randn((1, 5)) # True weights for our data, random normal variables againweights = torch.randn_like(features) # and a true bias termbias = torch.randn((1, 1))", "e": 27484, "s": 27246, "text": null }, { "code": null, "e": 27707, "s": 27484, "text": "features = torch.randn((1, 5)) creates a tensor with shape (1, 5), one row and five columns, that contains values randomly distributed according to the normal distribution with a mean of zero and standard deviation of one." }, { "code": null, "e": 27852, "s": 27707, "text": "weights = torch.randn_like(features) creates another tensor with the same shape as features, again containing values from a normal distribution." }, { "code": null, "e": 27939, "s": 27852, "text": "Finally, bias = torch.randn((1, 1)) creates a single value from a normal distribution." }, { "code": null, "e": 28011, "s": 27939, "text": "Now we calculate the output of the network using matrix multiplication." }, { "code": "y = activation(torch.mm(features, weights.view(5, 1)) + bias)", "e": 28073, "s": 28011, "text": null }, { "code": null, "e": 28447, "s": 28073, "text": "That’s how we can calculate the output for a single neuron. The real power of this algorithm happens when you start stacking these individual units into layers and stacks of layers, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix." }, { "code": null, "e": 28528, "s": 28447, "text": "We define the structure of neural network and initialize the weights and biases." }, { "code": "# Features are 3 random normal variablesfeatures = torch.randn((1, 3)) # Define the size of each layer in our network # Number of input units, must match number of input featuresn_input = features.shape[1] n_hidden = 2 # Number of hidden units n_output = 1 # Number of output units # Weights for inputs to hidden layerW1 = torch.randn(n_input, n_hidden) # Weights for hidden layer to output layerW2 = torch.randn(n_hidden, n_output) # and bias terms for hidden and output layersB1 = torch.randn((1, n_hidden))B2 = torch.randn((1, n_output))", "e": 29108, "s": 28528, "text": null }, { "code": null, "e": 29221, "s": 29108, "text": "Now we can calculate the output for this multi-layer network using the weights W1 & W2, and the biases, B1 & B2." }, { "code": "h = activation(torch.mm(features, W1) + B1)output = activation(torch.mm(h, W2) + B2)print(output)", "e": 29319, "s": 29221, "text": null }, { "code": null, "e": 29334, "s": 29319, "text": "Python-PyTorch" }, { "code": null, "e": 29351, "s": 29334, "text": "Machine Learning" }, { "code": null, "e": 29358, "s": 29351, "text": "Python" }, { "code": null, "e": 29375, "s": 29358, "text": "Machine Learning" }, { "code": null, "e": 29473, "s": 29375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29487, "s": 29473, "text": "Decision Tree" }, { "code": null, "e": 29527, "s": 29487, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 29567, "s": 29527, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 29605, "s": 29567, "text": "Python | Decision tree implementation" }, { "code": null, "e": 29638, "s": 29605, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29666, "s": 29638, "text": "Read JSON file using Python" }, { "code": null, "e": 29716, "s": 29666, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29738, "s": 29716, "text": "Python map() function" } ]
How to retrieve the contents of a ResultSet from last to first in JDBC?
Certain SQL queries (especially SELECT) returns tabular data, In JDBC the object of the java.sql.ResultSet interface holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general). The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row. There are two types of result sets namely, forward only and, bidirectional. By default the ResultSet we get by the executeQuery() method is of the type forward only. Using this you can traverse/move the cursor only forward direction. A bi-directional ResultSet object is the one whose cursor moves in both forward and backward directions. The createStatement() method of the Connection interface has a variant which accepts two integer values representing the result set type and the concurrency type. Statement createStatement(int resultSetType, int resultSetConcurrency) To create a bi-directional result set you need to pass the type as ResultSet.TYPE_SCROLL_SENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE, along with the concurrency, to this method as − //Creating a Statement object Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); Then, if you invoke executeQuery() method using this statement it returns a ResultSet object which is bi-directional. The previous() method of the ResultSet interface moves the pointer of this ResultSet object to the previous row, from the current position. This method returns a boolean value specifying whether the ResultSet object contains more rows. If there are no rows previous to its current position this method returns false, else it returns true. The Getter methods of the ResultSet interface (getInt(), getString() etc..) accepts the column index and returns the value of the specified column in the current row. Using these methods, you can retrieve the contents of a ResultSet object from first to last. while(rs.previous()) { System.out.print("Brand: "+rs.getString("Mobile_Brand")+", "); System.out.print("Sale: "+rs.getString("Unit_Sale")); System.out.println(""); } Let us create a table with name mobile_sales in MySQL database using CREATE statement as shown below − CREATE TABLE mobile_sales ( mobile_brand VARCHAR(255), unit_sale INT ); Now, we will insert 11 records in mobile_sales table using INSERT statements − insert into mobile_sales values('Iphone', 3000); insert into mobile_sales values('Samsung', 4000); insert into mobile_sales values('Nokia', 5000); insert into mobile_sales values('Vivo', 1500); insert into mobile_sales values('Oppo', 900); insert into mobile_sales values('MI', 6400); insert into mobile_sales values('MotoG', 4360); insert into mobile_sales values('Lenovo', 4100); insert into mobile_sales values('RedMI', 4000); insert into mobile_sales values('MotoG', 4360); insert into mobile_sales values('OnePlus', 6334); Following example establishes connection with the database and retrieves the contents of the table mobile_sales from last to first. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class BidirectionalResultSet { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/TestDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from mobile_sales"); //Moving the cursor to the end of the ResultSet rs.afterLast(); System.out.println("Contents of the table"); while(rs.previous()) { System.out.print("Brand: "+rs.getString("Mobile_Brand")+", "); System.out.print("Sale: "+rs.getString("Unit_Sale")); System.out.println(""); } } } Connection established...... Contents of the table Brand: Vivo, Sale: 1500 Brand: Nokia, Sale: 5000 Brand: Samsung, Sale: 4000 Brand: IPhone, Sale: 3000
[ { "code": null, "e": 1343, "s": 1062, "text": "Certain SQL queries (especially SELECT) returns tabular data, In JDBC the object of the java.sql.ResultSet interface holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general)." }, { "code": null, "e": 1472, "s": 1343, "text": "The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row." }, { "code": null, "e": 1706, "s": 1472, "text": "There are two types of result sets namely, forward only and, bidirectional. By default the ResultSet we get by the executeQuery() method is of the type forward only. Using this you can traverse/move the cursor only forward direction." }, { "code": null, "e": 1974, "s": 1706, "text": "A bi-directional ResultSet object is the one whose cursor moves in both forward and backward directions. The createStatement() method of the Connection interface has a variant which accepts two integer values representing the result set type and the concurrency type." }, { "code": null, "e": 2045, "s": 1974, "text": "Statement createStatement(int resultSetType, int resultSetConcurrency)" }, { "code": null, "e": 2230, "s": 2045, "text": "To create a bi-directional result set you need to pass the type as ResultSet.TYPE_SCROLL_SENSITIVE or ResultSet.TYPE_SCROLL_INSENSITIVE, along with the concurrency, to this method as −" }, { "code": null, "e": 2359, "s": 2230, "text": "//Creating a Statement object\nStatement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);" }, { "code": null, "e": 2477, "s": 2359, "text": "Then, if you invoke executeQuery() method using this statement it returns a ResultSet object which is bi-directional." }, { "code": null, "e": 2617, "s": 2477, "text": "The previous() method of the ResultSet interface moves the pointer of this ResultSet object to the previous row, from the current position." }, { "code": null, "e": 2713, "s": 2617, "text": "This method returns a boolean value specifying whether the ResultSet object contains more rows." }, { "code": null, "e": 2816, "s": 2713, "text": "If there are no rows previous to its current position this method returns false, else it returns true." }, { "code": null, "e": 2983, "s": 2816, "text": "The Getter methods of the ResultSet interface (getInt(), getString() etc..) accepts the column index and returns the value of the specified column in the current row." }, { "code": null, "e": 3076, "s": 2983, "text": "Using these methods, you can retrieve the contents of a ResultSet object from first to last." }, { "code": null, "e": 3251, "s": 3076, "text": "while(rs.previous()) {\n System.out.print(\"Brand: \"+rs.getString(\"Mobile_Brand\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Unit_Sale\"));\n System.out.println(\"\");\n}" }, { "code": null, "e": 3354, "s": 3251, "text": "Let us create a table with name mobile_sales in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 3432, "s": 3354, "text": "CREATE TABLE mobile_sales (\n mobile_brand VARCHAR(255),\n unit_sale INT\n);" }, { "code": null, "e": 3511, "s": 3432, "text": "Now, we will insert 11 records in mobile_sales table using INSERT statements −" }, { "code": null, "e": 4039, "s": 3511, "text": "insert into mobile_sales values('Iphone', 3000);\ninsert into mobile_sales values('Samsung', 4000);\ninsert into mobile_sales values('Nokia', 5000);\ninsert into mobile_sales values('Vivo', 1500);\ninsert into mobile_sales values('Oppo', 900);\ninsert into mobile_sales values('MI', 6400);\ninsert into mobile_sales values('MotoG', 4360);\ninsert into mobile_sales values('Lenovo', 4100);\ninsert into mobile_sales values('RedMI', 4000);\ninsert into mobile_sales values('MotoG', 4360);\ninsert into mobile_sales values('OnePlus', 6334);" }, { "code": null, "e": 4171, "s": 4039, "text": "Following example establishes connection with the database and retrieves the contents of the table mobile_sales from last to first." }, { "code": null, "e": 5285, "s": 4171, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class BidirectionalResultSet {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/TestDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from mobile_sales\");\n //Moving the cursor to the end of the ResultSet\n rs.afterLast();\n System.out.println(\"Contents of the table\");\n while(rs.previous()) {\n System.out.print(\"Brand: \"+rs.getString(\"Mobile_Brand\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Unit_Sale\"));\n System.out.println(\"\");\n }\n }\n}" }, { "code": null, "e": 5438, "s": 5285, "text": "Connection established......\nContents of the table\nBrand: Vivo, Sale: 1500\nBrand: Nokia, Sale: 5000\nBrand: Samsung, Sale: 4000\nBrand: IPhone, Sale: 3000" } ]
Android Annotation Processing - GeeksforGeeks
23 Jul, 2021 You’ve undoubtedly seen a lot of annotations as an Android developer: They’re those strange code components that begin with @ and sometimes have parameters connected to them. Annotations link metadata to other code components, allowing you to include extra information in your code. Annotations may be used to produce new source files based on that information using annotation processing. Image 1. An android annotation. In the example image shown above the “@” followed by the word, Override is actually what is known as an Android Annotation. In this article, we will know about the same in detail. Annotation processing is used by several well-known libraries in Android development, including Picasso, Glide, PlaceHolderView, and others. Annotation processing has evolved into one of the most critical language features in current Java programming. Java has supported annotation processing since the introduction of Java 5, although its full potential has only recently been realized. In layman’s terms, annotation processing is used to produce files during compilation. But before you get too much into the annotation, here’s a note: GeekTip: Annotation processing may only be used to create new files and cannot be used to change existing ones. Annotation processing is used for many types of files, not just.java files. Many compilation cycles are spent on annotation processing. During each cycle, the compiler reads a java source file and looks for annotations that have been registered for processing before calling the relevant annotation processor. This cycle continues until a file is produced or it ends if no file is generated in that cycle. Without further ado, let’s go on and create a simple annotation ourselves! It may sound overwhelming but is actually easy. Step #1: Creating a new Module The first step is to build a new module that will house your annotations. Go to Android Studio and then click on File -> New ->New Module then choose Kotlin and after that, you need to add a name to the module like you usually do with your android projects. Image 2. Selecting the Module AdapterModel is now a regular Kotlin class, but converting it to an annotation class is straightforward. Simply place the annotation keyword in front of the class. As an example: Step #2: Configuring the Module Name the module gfg-annotations.Set the package to com.geeksforgeeks.gfg_annotations.Set the class name to AdapterModule.Set the language as kt or Kotlin. Name the module gfg-annotations. Set the package to com.geeksforgeeks.gfg_annotations. Set the class name to AdapterModule. Set the language as kt or Kotlin. Image 3. Configuring the Module. Press ‘Finish’ after that to create your new annotation module! Note: AdapterModule is now a regular Kotlin class, but converting it to an annotation class is straightforward. Simply place the annotation keyword in front of the class. Like: annotation class AdapterModule Image 4. Making the standard module as an annotation. Step #3: Adding Functionality to the Annotation Even if you’re creating a basic annotation, you can’t help but use additional annotations on it! Two common annotations will be used to annotate your annotation classes. The very first one is creating a value data object like the one mentioned below: Kotlin annotation class AdapterModule(val layoutId: Int) Step #4: Adding Another Annotation Only one annotation is not enough to make the module worth using, as a fact all the modern days’ libraries which are mentioned in the former part of this article have used around 100s of different annotations to achieve the functionality. Although the issue of annotation usage and consumption is vast and complex, it all comes down to achieving more with less. That is, less code (annotations) magically transforms into greater functionality, and annotation processing catalyzes this computational alchemy. Image 5. Adding another Annotation to the Module. Don’t worry about all the red lines of the codes, they are just persistent as a warning because the module isn’t published with proper documentation, and adding the documentation to them will remove them, as in the Android Project on GitHub all the red lines are removed. The final version of this project may be downloaded by clicking here. Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters Kotlin when expression
[ { "code": null, "e": 26491, "s": 26463, "text": "\n23 Jul, 2021" }, { "code": null, "e": 26881, "s": 26491, "text": "You’ve undoubtedly seen a lot of annotations as an Android developer: They’re those strange code components that begin with @ and sometimes have parameters connected to them. Annotations link metadata to other code components, allowing you to include extra information in your code. Annotations may be used to produce new source files based on that information using annotation processing." }, { "code": null, "e": 26913, "s": 26881, "text": "Image 1. An android annotation." }, { "code": null, "e": 27094, "s": 26913, "text": "In the example image shown above the “@” followed by the word, Override is actually what is known as an Android Annotation. In this article, we will know about the same in detail. " }, { "code": null, "e": 27632, "s": 27094, "text": "Annotation processing is used by several well-known libraries in Android development, including Picasso, Glide, PlaceHolderView, and others. Annotation processing has evolved into one of the most critical language features in current Java programming. Java has supported annotation processing since the introduction of Java 5, although its full potential has only recently been realized. In layman’s terms, annotation processing is used to produce files during compilation. But before you get too much into the annotation, here’s a note:" }, { "code": null, "e": 27820, "s": 27632, "text": "GeekTip: Annotation processing may only be used to create new files and cannot be used to change existing ones. Annotation processing is used for many types of files, not just.java files." }, { "code": null, "e": 28273, "s": 27820, "text": "Many compilation cycles are spent on annotation processing. During each cycle, the compiler reads a java source file and looks for annotations that have been registered for processing before calling the relevant annotation processor. This cycle continues until a file is produced or it ends if no file is generated in that cycle. Without further ado, let’s go on and create a simple annotation ourselves! It may sound overwhelming but is actually easy." }, { "code": null, "e": 28304, "s": 28273, "text": "Step #1: Creating a new Module" }, { "code": null, "e": 28562, "s": 28304, "text": "The first step is to build a new module that will house your annotations. Go to Android Studio and then click on File -> New ->New Module then choose Kotlin and after that, you need to add a name to the module like you usually do with your android projects." }, { "code": null, "e": 28592, "s": 28562, "text": "Image 2. Selecting the Module" }, { "code": null, "e": 28771, "s": 28592, "text": "AdapterModel is now a regular Kotlin class, but converting it to an annotation class is straightforward. Simply place the annotation keyword in front of the class. As an example:" }, { "code": null, "e": 28803, "s": 28771, "text": "Step #2: Configuring the Module" }, { "code": null, "e": 28958, "s": 28803, "text": "Name the module gfg-annotations.Set the package to com.geeksforgeeks.gfg_annotations.Set the class name to AdapterModule.Set the language as kt or Kotlin." }, { "code": null, "e": 28991, "s": 28958, "text": "Name the module gfg-annotations." }, { "code": null, "e": 29045, "s": 28991, "text": "Set the package to com.geeksforgeeks.gfg_annotations." }, { "code": null, "e": 29082, "s": 29045, "text": "Set the class name to AdapterModule." }, { "code": null, "e": 29116, "s": 29082, "text": "Set the language as kt or Kotlin." }, { "code": null, "e": 29149, "s": 29116, "text": "Image 3. Configuring the Module." }, { "code": null, "e": 29213, "s": 29149, "text": "Press ‘Finish’ after that to create your new annotation module!" }, { "code": null, "e": 29390, "s": 29213, "text": "Note: AdapterModule is now a regular Kotlin class, but converting it to an annotation class is straightforward. Simply place the annotation keyword in front of the class. Like:" }, { "code": null, "e": 29421, "s": 29390, "text": "annotation class AdapterModule" }, { "code": null, "e": 29475, "s": 29421, "text": "Image 4. Making the standard module as an annotation." }, { "code": null, "e": 29523, "s": 29475, "text": "Step #3: Adding Functionality to the Annotation" }, { "code": null, "e": 29774, "s": 29523, "text": "Even if you’re creating a basic annotation, you can’t help but use additional annotations on it! Two common annotations will be used to annotate your annotation classes. The very first one is creating a value data object like the one mentioned below:" }, { "code": null, "e": 29781, "s": 29774, "text": "Kotlin" }, { "code": "annotation class AdapterModule(val layoutId: Int)", "e": 29831, "s": 29781, "text": null }, { "code": null, "e": 29866, "s": 29831, "text": "Step #4: Adding Another Annotation" }, { "code": null, "e": 30374, "s": 29866, "text": "Only one annotation is not enough to make the module worth using, as a fact all the modern days’ libraries which are mentioned in the former part of this article have used around 100s of different annotations to achieve the functionality. Although the issue of annotation usage and consumption is vast and complex, it all comes down to achieving more with less. That is, less code (annotations) magically transforms into greater functionality, and annotation processing catalyzes this computational alchemy." }, { "code": null, "e": 30424, "s": 30374, "text": "Image 5. Adding another Annotation to the Module." }, { "code": null, "e": 30696, "s": 30424, "text": "Don’t worry about all the red lines of the codes, they are just persistent as a warning because the module isn’t published with proper documentation, and adding the documentation to them will remove them, as in the Android Project on GitHub all the red lines are removed." }, { "code": null, "e": 30766, "s": 30696, "text": "The final version of this project may be downloaded by clicking here." }, { "code": null, "e": 30773, "s": 30766, "text": "Picked" }, { "code": null, "e": 30781, "s": 30773, "text": "Android" }, { "code": null, "e": 30788, "s": 30781, "text": "Kotlin" }, { "code": null, "e": 30796, "s": 30788, "text": "Android" }, { "code": null, "e": 30894, "s": 30796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30932, "s": 30894, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30971, "s": 30932, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31021, "s": 30971, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 31047, "s": 31021, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 31098, "s": 31047, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 31117, "s": 31098, "text": "Android UI Layouts" }, { "code": null, "e": 31130, "s": 31117, "text": "Kotlin Array" }, { "code": null, "e": 31172, "s": 31130, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31199, "s": 31172, "text": "Kotlin Setters and Getters" } ]
How to append HTML code to a div using JavaScript ? - GeeksforGeeks
20 Jul, 2021 There are two ways to append HTML code to a div through JavaScript Using the innerHTML attribute Using the insertAdjacentHTML() method Using the innerHTML attribute:To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML. Syntax: element.innerHTML += "additional HTML code" or element.innerHTML = element.innerHTML + "additional HTML code" Example: <!DOCTYPE html><html> <head> <title>How to Append HTML Code to a Div using Javascript</title> <style> body { text-align: center; padding: 5%; } h1{ color:green; } </style></head> <body> <div id="add_to_me"> <h1>GeeksforGeeks</h1> <p>This is the text which has already been typed into the div</p> </div> <button onclick="addCode()">Add Stuff</button> <script> function addCode() { document.getElementById("add_to_me").innerHTML += "<h3>This is the text which has been inserted by JS</h3>"; } </script></body> </html> Before Clicking the Button: After Clicking the Button:Note: This method basically destroys all the content of the div and recreates it. So, if you have any listeners attached to the child nodes of that div, they will be lost.Using the insertAdjacentHTML() methodHTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters:The position (in the document) where you want to insert the code (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’)The HTML code you want to insert enclosed in quotesSyntax:elementInsideDiv.insertAdjacentHTML('afterend', 'additional HTML code'); Example:<!DOCTYPE html><html> <head> <title>How to Append HTML Code to a Div using Javascript</title> <style> body { text-align: center; padding: 5%; } h1{ color: green } </style></head> <body> <div id="add_to_me"> <h1>GeeksforGeeks</h1> <p id="add_after_me"> This is the text which has already been typed into the div</p> </div> <button onclick="addCode()">Add Stuff</button> <script> function addCode() { document.getElementById("add_after_me").insertAdjacentHTML("afterend", "<h3>This is the text which has been inserted by JS</h3>"); } </script></body> </html>Output:Before Clicking the Button:After Clicking the Button:Note:You should never insert the HTML code in this way if you are taking it as an input from the user. It opens your website to cross-site scripting vulnerabilities.JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.Attention 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 Note: This method basically destroys all the content of the div and recreates it. So, if you have any listeners attached to the child nodes of that div, they will be lost. Using the insertAdjacentHTML() method HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’)The HTML code you want to insert enclosed in quotes The position (in the document) where you want to insert the code (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’) The HTML code you want to insert enclosed in quotes Syntax: elementInsideDiv.insertAdjacentHTML('afterend', 'additional HTML code'); Example: <!DOCTYPE html><html> <head> <title>How to Append HTML Code to a Div using Javascript</title> <style> body { text-align: center; padding: 5%; } h1{ color: green } </style></head> <body> <div id="add_to_me"> <h1>GeeksforGeeks</h1> <p id="add_after_me"> This is the text which has already been typed into the div</p> </div> <button onclick="addCode()">Add Stuff</button> <script> function addCode() { document.getElementById("add_after_me").insertAdjacentHTML("afterend", "<h3>This is the text which has been inserted by JS</h3>"); } </script></body> </html> Before Clicking the Button: After Clicking the Button:Note:You should never insert the HTML code in this way if you are taking it as an input from the user. It opens your website to cross-site scripting vulnerabilities.JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.Attention 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 Note:You should never insert the HTML code in this way if you are taking it as an input from the user. It opens your website to cross-site scripting vulnerabilities. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. JacobAntony1 HTML-Attributes Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples How to read a local text file using JavaScript? Node.js | fs.writeFileSync() Method How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 26440, "s": 26412, "text": "\n20 Jul, 2021" }, { "code": null, "e": 26507, "s": 26440, "text": "There are two ways to append HTML code to a div through JavaScript" }, { "code": null, "e": 26537, "s": 26507, "text": "Using the innerHTML attribute" }, { "code": null, "e": 26575, "s": 26537, "text": "Using the insertAdjacentHTML() method" }, { "code": null, "e": 26787, "s": 26575, "text": "Using the innerHTML attribute:To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML." }, { "code": null, "e": 26795, "s": 26787, "text": "Syntax:" }, { "code": null, "e": 26840, "s": 26795, "text": "element.innerHTML += \"additional HTML code\"\n" }, { "code": null, "e": 26843, "s": 26840, "text": "or" }, { "code": null, "e": 26907, "s": 26843, "text": "element.innerHTML = element.innerHTML + \"additional HTML code\"\n" }, { "code": null, "e": 26916, "s": 26907, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to Append HTML Code to a Div using Javascript</title> <style> body { text-align: center; padding: 5%; } h1{ color:green; } </style></head> <body> <div id=\"add_to_me\"> <h1>GeeksforGeeks</h1> <p>This is the text which has already been typed into the div</p> </div> <button onclick=\"addCode()\">Add Stuff</button> <script> function addCode() { document.getElementById(\"add_to_me\").innerHTML += \"<h3>This is the text which has been inserted by JS</h3>\"; } </script></body> </html>", "e": 27589, "s": 26916, "text": null }, { "code": null, "e": 27617, "s": 27589, "text": "Before Clicking the Button:" }, { "code": null, "e": 29607, "s": 27617, "text": "After Clicking the Button:Note: This method basically destroys all the content of the div and recreates it. So, if you have any listeners attached to the child nodes of that div, they will be lost.Using the insertAdjacentHTML() methodHTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters:The position (in the document) where you want to insert the code (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’)The HTML code you want to insert enclosed in quotesSyntax:elementInsideDiv.insertAdjacentHTML('afterend', 'additional HTML code');\nExample:<!DOCTYPE html><html> <head> <title>How to Append HTML Code to a Div using Javascript</title> <style> body { text-align: center; padding: 5%; } h1{ color: green } </style></head> <body> <div id=\"add_to_me\"> <h1>GeeksforGeeks</h1> <p id=\"add_after_me\"> This is the text which has already been typed into the div</p> </div> <button onclick=\"addCode()\">Add Stuff</button> <script> function addCode() { document.getElementById(\"add_after_me\").insertAdjacentHTML(\"afterend\", \"<h3>This is the text which has been inserted by JS</h3>\"); } </script></body> </html>Output:Before Clicking the Button:After Clicking the Button:Note:You should never insert the HTML code in this way if you are taking it as an input from the user. It opens your website to cross-site scripting vulnerabilities.JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.Attention 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": 29779, "s": 29607, "text": "Note: This method basically destroys all the content of the div and recreates it. So, if you have any listeners attached to the child nodes of that div, they will be lost." }, { "code": null, "e": 29817, "s": 29779, "text": "Using the insertAdjacentHTML() method" }, { "code": null, "e": 29996, "s": 29817, "text": "HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters:" }, { "code": null, "e": 30167, "s": 29996, "text": "The position (in the document) where you want to insert the code (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’)The HTML code you want to insert enclosed in quotes" }, { "code": null, "e": 30287, "s": 30167, "text": "The position (in the document) where you want to insert the code (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’)" }, { "code": null, "e": 30339, "s": 30287, "text": "The HTML code you want to insert enclosed in quotes" }, { "code": null, "e": 30347, "s": 30339, "text": "Syntax:" }, { "code": null, "e": 30421, "s": 30347, "text": "elementInsideDiv.insertAdjacentHTML('afterend', 'additional HTML code');\n" }, { "code": null, "e": 30430, "s": 30421, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to Append HTML Code to a Div using Javascript</title> <style> body { text-align: center; padding: 5%; } h1{ color: green } </style></head> <body> <div id=\"add_to_me\"> <h1>GeeksforGeeks</h1> <p id=\"add_after_me\"> This is the text which has already been typed into the div</p> </div> <button onclick=\"addCode()\">Add Stuff</button> <script> function addCode() { document.getElementById(\"add_after_me\").insertAdjacentHTML(\"afterend\", \"<h3>This is the text which has been inserted by JS</h3>\"); } </script></body> </html>", "e": 31136, "s": 30430, "text": null }, { "code": null, "e": 31164, "s": 31136, "text": "Before Clicking the Button:" }, { "code": null, "e": 31745, "s": 31164, "text": "After Clicking the Button:Note:You should never insert the HTML code in this way if you are taking it as an input from the user. It opens your website to cross-site scripting vulnerabilities.JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.Attention 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": 31911, "s": 31745, "text": "Note:You should never insert the HTML code in this way if you are taking it as an input from the user. It opens your website to cross-site scripting vulnerabilities." }, { "code": null, "e": 32130, "s": 31911, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 32267, "s": 32130, "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": 32280, "s": 32267, "text": "JacobAntony1" }, { "code": null, "e": 32296, "s": 32280, "text": "HTML-Attributes" }, { "code": null, "e": 32303, "s": 32296, "text": "Picked" }, { "code": null, "e": 32314, "s": 32303, "text": "JavaScript" }, { "code": null, "e": 32412, "s": 32314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32452, "s": 32412, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32497, "s": 32452, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32558, "s": 32497, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32630, "s": 32558, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32676, "s": 32630, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 32717, "s": 32676, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 32758, "s": 32717, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 32806, "s": 32758, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 32842, "s": 32806, "text": "Node.js | fs.writeFileSync() Method" } ]
How can I encode a URL in Android?
This example demonstrates how do I can encode a URL in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"/> <Button android:id="@+id/btnEncode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Load URL" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class MainActivity extends AppCompatActivity { Button button; private WebView webView; String strURL; private String query; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.webView); button = findViewById(R.id.btnEncode); strURL = "http://stackoverflow.com/search?q="; try { query = URLEncoder.encode("android drawables", "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } strURL += query; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { } @Override public void onPageFinished(WebView view, String url) { Toast.makeText(getApplicationContext(), "Page Loaded.", Toast.LENGTH_SHORT).show(); } }); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(strURL); } }); } } Step 4 − Add the following code to androidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1126, "s": 1062, "text": "This example demonstrates how do I can encode a URL in android." }, { "code": null, "e": 1255, "s": 1126, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1320, "s": 1255, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2023, "s": 1320, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"/>\n <Button\n android:id=\"@+id/btnEncode\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Load URL\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentEnd=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2080, "s": 2023, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3696, "s": 2080, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Bitmap;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n private WebView webView;\n String strURL;\n private String query;\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n webView = findViewById(R.id.webView);\n button = findViewById(R.id.btnEncode);\n strURL = \"http://stackoverflow.com/search?q=\";\n try {\n query = URLEncoder.encode(\"android drawables\", \"UTF-8\");\n }\n catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n strURL += query;\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n webView.setWebViewClient(new WebViewClient() {\n @Override\n public void onPageStarted(WebView view, String url, Bitmap favicon) {\n }\n @Override\n public void onPageFinished(WebView view, String url) {\n Toast.makeText(getApplicationContext(), \"Page Loaded.\", Toast.LENGTH_SHORT).show();\n }\n });\n webView.getSettings().setJavaScriptEnabled(true);\n webView.loadUrl(strURL);\n }\n });\n }\n}" }, { "code": null, "e": 3751, "s": 3696, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4466, "s": 3751, "text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4817, "s": 4466, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4858, "s": 4817, "text": "Click here to download the project code." } ]
numpy.iscomplex() in Python - GeeksforGeeks
28 Mar, 2022 The numpy.iscomplex() function tests element-wise whether it is a complex number or not(not infinity or not Not a Number) and returns the result as a boolean array. Syntax : numpy.iscomplex(array) Parameters : array : [array_like] Input array whose element we want to test Return : boolean array containing the result Code 1 : Python # Python Program illustrating# numpy.iscomplex() method import numpy as geek print("Is Complex : ", geek.iscomplex([1+1j, 1+0j]), "\n") print("Is Complex : ", geek.iscomplex([0+1j, 0]), "\n") Output : Is Complex : [ True False] Is Complex : [ True False] Code 2 : Python # Python Program illustrating# numpy.iscomplex() method import numpy as geek # Returns True/False value for each elementa = geek.arange(20).reshape(5, 4)print("Is complex : \n", geek.iscomplex(a)) # Returns True/False value as ans# because we have mentioned dtpe in the beginningb = geek.arange(20).reshape(5, 4).dtype = complex print("\n",b)print("\nIs complex : ", geek.iscomplex(b)) b = [[1j], [3]]print("\nIs complex : \n", geek.iscomplex(b)) Output : Is complex : [[False False False False] [False False False False] [False False False False] [False False False False] [False False False False]] Is complex : False Is complex : [[ True] [False]] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isfinite.html Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. Akanksha_Rai vinayedula Python numpy-Logic Functions Python-numpy 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 | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25840, "s": 25665, "text": "The numpy.iscomplex() function tests element-wise whether it is a complex number or not(not infinity or not Not a Number) and returns the result as a boolean array. Syntax : " }, { "code": null, "e": 25863, "s": 25840, "text": "numpy.iscomplex(array)" }, { "code": null, "e": 25877, "s": 25863, "text": "Parameters : " }, { "code": null, "e": 25940, "s": 25877, "text": "array : [array_like] Input array whose element we want to test" }, { "code": null, "e": 25950, "s": 25940, "text": "Return : " }, { "code": null, "e": 25986, "s": 25950, "text": "boolean array containing the result" }, { "code": null, "e": 25996, "s": 25986, "text": "Code 1 : " }, { "code": null, "e": 26003, "s": 25996, "text": "Python" }, { "code": "# Python Program illustrating# numpy.iscomplex() method import numpy as geek print(\"Is Complex : \", geek.iscomplex([1+1j, 1+0j]), \"\\n\") print(\"Is Complex : \", geek.iscomplex([0+1j, 0]), \"\\n\")", "e": 26196, "s": 26003, "text": null }, { "code": null, "e": 26206, "s": 26196, "text": "Output : " }, { "code": null, "e": 26265, "s": 26206, "text": "Is Complex : [ True False] \n\nIs Complex : [ True False] " }, { "code": null, "e": 26275, "s": 26265, "text": "Code 2 : " }, { "code": null, "e": 26282, "s": 26275, "text": "Python" }, { "code": "# Python Program illustrating# numpy.iscomplex() method import numpy as geek # Returns True/False value for each elementa = geek.arange(20).reshape(5, 4)print(\"Is complex : \\n\", geek.iscomplex(a)) # Returns True/False value as ans# because we have mentioned dtpe in the beginningb = geek.arange(20).reshape(5, 4).dtype = complex print(\"\\n\",b)print(\"\\nIs complex : \", geek.iscomplex(b)) b = [[1j], [3]]print(\"\\nIs complex : \\n\", geek.iscomplex(b))", "e": 26753, "s": 26282, "text": null }, { "code": null, "e": 26763, "s": 26753, "text": "Output : " }, { "code": null, "e": 26970, "s": 26763, "text": "Is complex : \n [[False False False False]\n [False False False False]\n [False False False False]\n [False False False False]\n [False False False False]]\n\nIs complex : False\n\nIs complex : \n [[ True]\n [False]]" }, { "code": null, "e": 27061, "s": 26970, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isfinite.html " }, { "code": null, "e": 27168, "s": 27061, "text": "Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. " }, { "code": null, "e": 27593, "s": 27168, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 27606, "s": 27593, "text": "Akanksha_Rai" }, { "code": null, "e": 27617, "s": 27606, "text": "vinayedula" }, { "code": null, "e": 27646, "s": 27617, "text": "Python numpy-Logic Functions" }, { "code": null, "e": 27659, "s": 27646, "text": "Python-numpy" }, { "code": null, "e": 27666, "s": 27659, "text": "Python" }, { "code": null, "e": 27764, "s": 27666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27796, "s": 27764, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27838, "s": 27796, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27880, "s": 27838, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27936, "s": 27880, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27963, "s": 27936, "text": "Python Classes and Objects" }, { "code": null, "e": 27994, "s": 27963, "text": "Python | os.path.join() method" }, { "code": null, "e": 28023, "s": 27994, "text": "Create a directory in Python" }, { "code": null, "e": 28045, "s": 28023, "text": "Defaultdict in Python" }, { "code": null, "e": 28084, "s": 28045, "text": "Python | Get unique values from a list" } ]
JavaScript Array reduceRight() Method - GeeksforGeeks
04 Oct, 2021 Below is the example of Array reduceRight() method. Example: HTML <!DOCTYPE html><html> <head> <title> JavaScript Array reduceRight() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from the left side </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Subtract: <span id="GFG"></span> <!-- Script to use reduceRight method --> <script> var arr = [175, 50, 25]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduceRight(subofArray); } </script></body> </html> Output: The arr.reduceRight() method in JavaScript is used to convert elements of the given array from right to left to a single value. Syntax: array.reduceRight( function(total, currentValue, currentIndex, arr), initialValue ) Parameter: This method accepts five parameters as mentioned above and described below: function(total, currentValue, index, arr): It is the required parameter and used to run for each element of array. It contains four parameter which are listed below: total: It is required parameter and used to specify the initialValue, or the previously returned value of the function.currentValue: It is required parameter and used to specify the value of the current element.currentIndex: It is optional parameter and used to specify the array index of the current element.arr: It is optional parameter and used to specify the array object the current element belongs to. total: It is required parameter and used to specify the initialValue, or the previously returned value of the function. currentValue: It is required parameter and used to specify the value of the current element. currentIndex: It is optional parameter and used to specify the array index of the current element. arr: It is optional parameter and used to specify the array object the current element belongs to. initialValue: It is optional parameter and used to specify the value to be passed to the function as the initial value. Example 1: This example use reduceRight() method to return the subtract of all array elements from right. HTML <!DOCTYPE html><html> <head> <title> JavaScript Array reduceRight() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from right </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Subtract: <span id="GFG"></span> <!-- Script to use reduceRight method --> <script> var arr = [10, 20, 30, 40, 50, 60]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduceRight(subofArray); } </script></body> </html> Output: Example 2: This example use reduceRight() method to return the round sum of all array elements. The code performing sum that does not affect by the reduceRight() method. HTML <!DOCTYPE html><html> <head> <title> JavaScript Array reduceRight() Method </title></head> <body style="text-align:center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p> Click here to get the sum of array elements </p> <button onclick="myGeeks()"> Click Here! </button> <br><br> Sum: <span id="GFG"></span> <!-- Script to use reduceRight method --> <script> var arr = [1.5, 20.3, 11.1, 40.7]; function sumofArray(sum, num) { return sum + Math.round(num); } function myGeeks(item) { document.getElementById("GFG").innerHTML = arr.reduceRight(sumofArray, 0); } </script></body> </html> Output: Supported Browsers: The browsers supported by JavaScript Array reduceRight() method are listed below: Google Chrome 3 Microsoft Edge 12 Mozilla Firefox 3.0 Safari 5 Opera 10.5 Internet Explorer 9 arorakashish0911 ysachin2314 javascript-array JavaScript-Methods 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 Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26141, "s": 26113, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26194, "s": 26141, "text": "Below is the example of Array reduceRight() method. " }, { "code": null, "e": 26204, "s": 26194, "text": "Example: " }, { "code": null, "e": 26209, "s": 26204, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Array reduceRight() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from the left side </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Subtract: <span id=\"GFG\"></span> <!-- Script to use reduceRight method --> <script> var arr = [175, 50, 25]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduceRight(subofArray); } </script></body> </html> ", "e": 27004, "s": 26209, "text": null }, { "code": null, "e": 27014, "s": 27004, "text": "Output: " }, { "code": null, "e": 27142, "s": 27014, "text": "The arr.reduceRight() method in JavaScript is used to convert elements of the given array from right to left to a single value." }, { "code": null, "e": 27151, "s": 27142, "text": "Syntax: " }, { "code": null, "e": 27236, "s": 27151, "text": "array.reduceRight( function(total, currentValue, currentIndex, arr), \ninitialValue )" }, { "code": null, "e": 27324, "s": 27236, "text": "Parameter: This method accepts five parameters as mentioned above and described below: " }, { "code": null, "e": 27898, "s": 27324, "text": "function(total, currentValue, index, arr): It is the required parameter and used to run for each element of array. It contains four parameter which are listed below: total: It is required parameter and used to specify the initialValue, or the previously returned value of the function.currentValue: It is required parameter and used to specify the value of the current element.currentIndex: It is optional parameter and used to specify the array index of the current element.arr: It is optional parameter and used to specify the array object the current element belongs to." }, { "code": null, "e": 28018, "s": 27898, "text": "total: It is required parameter and used to specify the initialValue, or the previously returned value of the function." }, { "code": null, "e": 28111, "s": 28018, "text": "currentValue: It is required parameter and used to specify the value of the current element." }, { "code": null, "e": 28210, "s": 28111, "text": "currentIndex: It is optional parameter and used to specify the array index of the current element." }, { "code": null, "e": 28309, "s": 28210, "text": "arr: It is optional parameter and used to specify the array object the current element belongs to." }, { "code": null, "e": 28429, "s": 28309, "text": "initialValue: It is optional parameter and used to specify the value to be passed to the function as the initial value." }, { "code": null, "e": 28537, "s": 28429, "text": "Example 1: This example use reduceRight() method to return the subtract of all array elements from right. " }, { "code": null, "e": 28542, "s": 28537, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Array reduceRight() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the Subtract of array elements from right </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Subtract: <span id=\"GFG\"></span> <!-- Script to use reduceRight method --> <script> var arr = [10, 20, 30, 40, 50, 60]; function subofArray(total, num) { return total - num; } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduceRight(subofArray); } </script></body> </html> ", "e": 29350, "s": 28542, "text": null }, { "code": null, "e": 29360, "s": 29350, "text": "Output: " }, { "code": null, "e": 29531, "s": 29360, "text": "Example 2: This example use reduceRight() method to return the round sum of all array elements. The code performing sum that does not affect by the reduceRight() method. " }, { "code": null, "e": 29536, "s": 29531, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript Array reduceRight() Method </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p> Click here to get the sum of array elements </p> <button onclick=\"myGeeks()\"> Click Here! </button> <br><br> Sum: <span id=\"GFG\"></span> <!-- Script to use reduceRight method --> <script> var arr = [1.5, 20.3, 11.1, 40.7]; function sumofArray(sum, num) { return sum + Math.round(num); } function myGeeks(item) { document.getElementById(\"GFG\").innerHTML = arr.reduceRight(sumofArray, 0); } </script></body> </html> ", "e": 30334, "s": 29536, "text": null }, { "code": null, "e": 30344, "s": 30334, "text": "Output: " }, { "code": null, "e": 30447, "s": 30344, "text": "Supported Browsers: The browsers supported by JavaScript Array reduceRight() method are listed below: " }, { "code": null, "e": 30463, "s": 30447, "text": "Google Chrome 3" }, { "code": null, "e": 30481, "s": 30463, "text": "Microsoft Edge 12" }, { "code": null, "e": 30501, "s": 30481, "text": "Mozilla Firefox 3.0" }, { "code": null, "e": 30510, "s": 30501, "text": "Safari 5" }, { "code": null, "e": 30521, "s": 30510, "text": "Opera 10.5" }, { "code": null, "e": 30541, "s": 30521, "text": "Internet Explorer 9" }, { "code": null, "e": 30558, "s": 30541, "text": "arorakashish0911" }, { "code": null, "e": 30570, "s": 30558, "text": "ysachin2314" }, { "code": null, "e": 30587, "s": 30570, "text": "javascript-array" }, { "code": null, "e": 30606, "s": 30587, "text": "JavaScript-Methods" }, { "code": null, "e": 30617, "s": 30606, "text": "JavaScript" }, { "code": null, "e": 30634, "s": 30617, "text": "Web Technologies" }, { "code": null, "e": 30732, "s": 30634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30772, "s": 30732, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30817, "s": 30772, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30878, "s": 30817, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30950, "s": 30878, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31002, "s": 30950, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31042, "s": 31002, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31075, "s": 31042, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31120, "s": 31075, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31163, "s": 31120, "text": "How to fetch data from an API in ReactJS ?" } ]
DecimalField - Django Models - GeeksforGeeks
12 Feb, 2020 DecimalField is a field which stores a fixed-precision decimal number, represented in Python by a Decimal instance. It validates the input using DecimalValidator. Syntax field_name = models.DecimalField(max_digits=None, decimal_places=None, **options) DecimalField.max_digitsThe maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. DecimalField.decimal_placesThe number of decimal places to store with the number. The number of decimal places to store with the number. For example, to store numbers up to 999 with a resolution of 2 decimal places, you’d use: models.DecimalField(..., max_digits=5, decimal_places=2) And to store numbers up to approximately one billion with a resolution of 10 decimal places: models.DecimalField(..., max_digits=19, decimal_places=10) Illustration of DecimalField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DecimalField( max_digits = 5, decimal_places = 2) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DecimalField( max_digits = 5, decimal_places = 2 )), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field DecimalField is created when you run migrations on the project. It is a field to store datetime.date python object. DecimalField is used for storing python datetime.date instance in the database. One can store any type of decimal number in the database. Let’s try storing a decimal number in the model created above. # importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport decimal # creating an instance of # datetime.dated = decimal.Decimal(9.53) # creating an instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DecimalField will enable it to store empty values for that table in relational database.Here are the field options and attributes that a DecimalField can use. NaveenArora Django-models Python Django 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 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 *args and **kwargs in Python
[ { "code": null, "e": 24322, "s": 24294, "text": "\n12 Feb, 2020" }, { "code": null, "e": 24485, "s": 24322, "text": "DecimalField is a field which stores a fixed-precision decimal number, represented in Python by a Decimal instance. It validates the input using DecimalValidator." }, { "code": null, "e": 24492, "s": 24485, "text": "Syntax" }, { "code": null, "e": 24574, "s": 24492, "text": "field_name = models.DecimalField(max_digits=None, decimal_places=None, **options)" }, { "code": null, "e": 24720, "s": 24574, "text": "DecimalField.max_digitsThe maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places." }, { "code": null, "e": 24843, "s": 24720, "text": "The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places." }, { "code": null, "e": 24925, "s": 24843, "text": "DecimalField.decimal_placesThe number of decimal places to store with the number." }, { "code": null, "e": 24980, "s": 24925, "text": "The number of decimal places to store with the number." }, { "code": null, "e": 25070, "s": 24980, "text": "For example, to store numbers up to 999 with a resolution of 2 decimal places, you’d use:" }, { "code": null, "e": 25127, "s": 25070, "text": "models.DecimalField(..., max_digits=5, decimal_places=2)" }, { "code": null, "e": 25220, "s": 25127, "text": "And to store numbers up to approximately one billion with a resolution of 10 decimal places:" }, { "code": null, "e": 25279, "s": 25220, "text": "models.DecimalField(..., max_digits=19, decimal_places=10)" }, { "code": null, "e": 25392, "s": 25279, "text": "Illustration of DecimalField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25479, "s": 25392, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 25530, "s": 25479, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25563, "s": 25530, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25622, "s": 25563, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DecimalField( max_digits = 5, decimal_places = 2)", "e": 25859, "s": 25622, "text": null }, { "code": null, "e": 25895, "s": 25859, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 26133, "s": 25895, "text": null }, { "code": null, "e": 26191, "s": 26133, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 26223, "s": 26191, "text": "Python manage.py makemigrations" }, { "code": null, "e": 26323, "s": 26223, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DecimalField( max_digits = 5, decimal_places = 2 )), ], ), ]", "e": 27041, "s": 26323, "text": null }, { "code": null, "e": 27050, "s": 27041, "text": "Now run," }, { "code": null, "e": 27075, "s": 27050, "text": "Python manage.py migrate" }, { "code": null, "e": 27212, "s": 27075, "text": "Thus, an geeks_field DecimalField is created when you run migrations on the project. It is a field to store datetime.date python object." }, { "code": null, "e": 27413, "s": 27212, "text": "DecimalField is used for storing python datetime.date instance in the database. One can store any type of decimal number in the database. Let’s try storing a decimal number in the model created above." }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport decimal # creating an instance of # datetime.dated = decimal.Decimal(9.53) # creating an instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()", "e": 27711, "s": 27413, "text": null }, { "code": null, "e": 27790, "s": 27711, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 28141, "s": 27790, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DecimalField will enable it to store empty values for that table in relational database.Here are the field options and attributes that a DecimalField can use." }, { "code": null, "e": 28153, "s": 28141, "text": "NaveenArora" }, { "code": null, "e": 28167, "s": 28153, "text": "Django-models" }, { "code": null, "e": 28181, "s": 28167, "text": "Python Django" }, { "code": null, "e": 28188, "s": 28181, "text": "Python" }, { "code": null, "e": 28286, "s": 28188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28295, "s": 28286, "text": "Comments" }, { "code": null, "e": 28308, "s": 28295, "text": "Old Comments" }, { "code": null, "e": 28326, "s": 28308, "text": "Python Dictionary" }, { "code": null, "e": 28361, "s": 28326, "text": "Read a file line by line in Python" }, { "code": null, "e": 28393, "s": 28361, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28423, "s": 28393, "text": "Iterate over a list in Python" }, { "code": null, "e": 28465, "s": 28423, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28491, "s": 28465, "text": "Python String | replace()" }, { "code": null, "e": 28534, "s": 28491, "text": "Python program to convert a list to string" }, { "code": null, "e": 28578, "s": 28534, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28615, "s": 28578, "text": "Create a Pandas DataFrame from Lists" } ]
Data Definition Commands in DBMS
Data definition commands are used to create, modify and remove database objects such as schemas, tables, views, indexes etc. Common Data Definition commands − The main use of create command is to create a new table in database. It has a predefined syntax in which we specify the columns and their respective data types. CREATE TABLE <TABLE NAME> ( <COLUMN NAME> <DATA TYPE>, <COLUMN NAME> <DATA TYPE>, <COLUMN NAME> <DATA TYPE>, <COLUMN NAME> <DATA TYPE> ); Create a student table with columns student name and roll number. CREATE TABLE STUDENT (STUDENT_NAME VARCHAR(30), ROLL_NUMBER INT ); An existing database object can be modified using the alter command. Alter command can do following changes to any table- Add new columns. Add new columns. Add new integrity constraints. Add new integrity constraints. Modify existing columns. Modify existing columns. Drop integrity constraints. Drop integrity constraints. General Syntax of the ALTER command is mentioned below − For adding a new column ALTER TABLE <table_name> ADD <column_name> For renaming a table ALTER TABLE <table_name> RENAME To <new_table_name > For modifying a column ALTER TABLE <table_name> MODIFY <column_name > <data type > For deleting a column ALTER TABLE <table_name> DROP COLUMN <column_name> This command can delete an index, table or view. Basically, any component from a relational database management system can be removed using the Drop command. Once the object is dropped, it cannot be reused.The general syntax of drop command is as follows − DROP TABLE <table_name>; DROP DATABASE <database_name>; DROP TABLE <index_name>; Using the truncate command, all the records in a database are deleted, but the database structure is maintained. TRUNCATE TABLE <table name> This command is used to add comments to the data dictionary. Single line comments: use ‘ --‘ before any text. Multiline comments: /* comments in between */ The rename command renames an object Rename <old name> to <new name>
[ { "code": null, "e": 1187, "s": 1062, "text": "Data definition commands are used to create, modify and remove database objects such as schemas, tables, views, indexes etc." }, { "code": null, "e": 1221, "s": 1187, "text": "Common Data Definition commands −" }, { "code": null, "e": 1382, "s": 1221, "text": "The main use of create command is to create a new table in database. It has a predefined syntax in which we specify the columns and their respective data types." }, { "code": null, "e": 1524, "s": 1382, "text": "CREATE TABLE <TABLE NAME>\n( <COLUMN NAME> <DATA TYPE>,\n<COLUMN NAME> <DATA TYPE>,\n<COLUMN NAME> <DATA TYPE>,\n<COLUMN NAME> <DATA TYPE>\n);" }, { "code": null, "e": 1590, "s": 1524, "text": "Create a student table with columns student name and roll number." }, { "code": null, "e": 1657, "s": 1590, "text": "CREATE TABLE STUDENT\n(STUDENT_NAME VARCHAR(30),\nROLL_NUMBER INT\n);" }, { "code": null, "e": 1779, "s": 1657, "text": "An existing database object can be modified using the alter command. Alter command can do following changes to any table-" }, { "code": null, "e": 1796, "s": 1779, "text": "Add new columns." }, { "code": null, "e": 1813, "s": 1796, "text": "Add new columns." }, { "code": null, "e": 1844, "s": 1813, "text": "Add new integrity constraints." }, { "code": null, "e": 1875, "s": 1844, "text": "Add new integrity constraints." }, { "code": null, "e": 1901, "s": 1875, "text": "Modify existing columns. " }, { "code": null, "e": 1927, "s": 1901, "text": "Modify existing columns. " }, { "code": null, "e": 1955, "s": 1927, "text": "Drop integrity constraints." }, { "code": null, "e": 1983, "s": 1955, "text": "Drop integrity constraints." }, { "code": null, "e": 2040, "s": 1983, "text": "General Syntax of the ALTER command is mentioned below −" }, { "code": null, "e": 2064, "s": 2040, "text": "For adding a new column" }, { "code": null, "e": 2109, "s": 2064, "text": "ALTER TABLE <table_name> ADD <column_name>" }, { "code": null, "e": 2131, "s": 2109, "text": " For renaming a table" }, { "code": null, "e": 2185, "s": 2131, "text": "ALTER TABLE <table_name> RENAME To <new_table_name >" }, { "code": null, "e": 2208, "s": 2185, "text": "For modifying a column" }, { "code": null, "e": 2268, "s": 2208, "text": "ALTER TABLE <table_name> MODIFY <column_name > <data type >" }, { "code": null, "e": 2290, "s": 2268, "text": "For deleting a column" }, { "code": null, "e": 2341, "s": 2290, "text": "ALTER TABLE <table_name> DROP COLUMN <column_name>" }, { "code": null, "e": 2599, "s": 2341, "text": "This command can delete an index, table or view. Basically, any component from a relational database management system can be removed using the Drop command. Once the object is dropped, it cannot be reused.The general syntax of drop command is as follows −" }, { "code": null, "e": 2680, "s": 2599, "text": "DROP TABLE <table_name>;\nDROP DATABASE <database_name>;\nDROP TABLE <index_name>;" }, { "code": null, "e": 2793, "s": 2680, "text": "Using the truncate command, all the records in a database are deleted, but the database structure is maintained." }, { "code": null, "e": 2821, "s": 2793, "text": "TRUNCATE TABLE <table name>" }, { "code": null, "e": 2882, "s": 2821, "text": "This command is used to add comments to the data dictionary." }, { "code": null, "e": 2933, "s": 2882, "text": "Single line comments: use ‘ --‘ before any text. " }, { "code": null, "e": 2982, "s": 2933, "text": "Multiline comments: /* comments in between */" }, { "code": null, "e": 3019, "s": 2982, "text": "The rename command renames an object" }, { "code": null, "e": 3051, "s": 3019, "text": "Rename <old name> to <new name>" } ]
Express.js req.param() Function - GeeksforGeeks
27 Apr, 2021 The req.param() function basically returns the value of param name when present. When parameters are passed, then it can be accessed using this function.Syntax: req.param(name [, defaultValue]) Parameter: The name parameter is the name of the parameter.Return Value: String.Installation of express module: You can visit the link to Install express module. You can install this package by using this command. You can visit the link to Install express module. You can install this package by using this command. npm install express After installing the express module, you can check your express version in command prompt using the command. After installing the express module, you can check your express version in command prompt using the command. npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Example 1: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; app.get('/', function (req, res) { //reading single parameter console.log(req.param('title')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this: The project structure will look like this: Make sure you have installed express module using the following command: Make sure you have installed express module using the following command: npm install express Run index.js file using below command: Run index.js file using below command: node index.js Output: Output: Server listening on PORT 3000 Now make a GET request to http://localhost:3000?title=GeeksforGeeks, then you will see the following output on your console: Now make a GET request to http://localhost:3000?title=GeeksforGeeks, then you will see the following output on your console: Server listening on PORT 3000 GeeksforGeeks Example 2: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; app.get('/', function (req, res) { // Reading multiple parameter console.log("Title:", req.param('title')); console.log("Domain:", req.param('domain')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now make a GET request to http://localhost:3000?title=GeeksforGeeks&domain=CS, then you will see the following output on your console: Server listening on PORT 3000 Title: GeeksforGeeks Domain: CS Reference: https://expressjs.com/en/4x/api.html#req.param simmytarika5 Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js path.resolve() Method Node.js crypto.createCipheriv() Method Node.js CRUD Operations Using Mongoose and MongoDB Atlas Node.js First Application How to Integrate Stripe Payment Gateway in Node.js ? Express.js express.Router() Function Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24295, "s": 24267, "text": "\n27 Apr, 2021" }, { "code": null, "e": 24458, "s": 24295, "text": "The req.param() function basically returns the value of param name when present. When parameters are passed, then it can be accessed using this function.Syntax: " }, { "code": null, "e": 24491, "s": 24458, "text": "req.param(name [, defaultValue])" }, { "code": null, "e": 24605, "s": 24491, "text": "Parameter: The name parameter is the name of the parameter.Return Value: String.Installation of express module: " }, { "code": null, "e": 24709, "s": 24605, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 24813, "s": 24709, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 24833, "s": 24813, "text": "npm install express" }, { "code": null, "e": 24944, "s": 24833, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 25055, "s": 24944, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 25075, "s": 25055, "text": "npm version express" }, { "code": null, "e": 25212, "s": 25075, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 25349, "s": 25212, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 25363, "s": 25349, "text": "node index.js" }, { "code": null, "e": 25395, "s": 25363, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 25406, "s": 25395, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.get('/', function (req, res) { //reading single parameter console.log(req.param('title')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 25711, "s": 25406, "text": null }, { "code": null, "e": 25739, "s": 25711, "text": "Steps to run the program: " }, { "code": null, "e": 25784, "s": 25739, "text": "The project structure will look like this: " }, { "code": null, "e": 25829, "s": 25784, "text": "The project structure will look like this: " }, { "code": null, "e": 25904, "s": 25829, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 25979, "s": 25904, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 25999, "s": 25979, "text": "npm install express" }, { "code": null, "e": 26040, "s": 25999, "text": "Run index.js file using below command: " }, { "code": null, "e": 26081, "s": 26040, "text": "Run index.js file using below command: " }, { "code": null, "e": 26095, "s": 26081, "text": "node index.js" }, { "code": null, "e": 26105, "s": 26095, "text": "Output: " }, { "code": null, "e": 26115, "s": 26105, "text": "Output: " }, { "code": null, "e": 26145, "s": 26115, "text": "Server listening on PORT 3000" }, { "code": null, "e": 26273, "s": 26145, "text": " Now make a GET request to http://localhost:3000?title=GeeksforGeeks, then you will see the following output on your console: " }, { "code": null, "e": 26402, "s": 26275, "text": "Now make a GET request to http://localhost:3000?title=GeeksforGeeks, then you will see the following output on your console: " }, { "code": null, "e": 26446, "s": 26402, "text": "Server listening on PORT 3000\nGeeksforGeeks" }, { "code": null, "e": 26482, "s": 26450, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 26493, "s": 26482, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.get('/', function (req, res) { // Reading multiple parameter console.log(\"Title:\", req.param('title')); console.log(\"Domain:\", req.param('domain')); res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 26865, "s": 26493, "text": null }, { "code": null, "e": 26906, "s": 26865, "text": "Run index.js file using below command: " }, { "code": null, "e": 26920, "s": 26906, "text": "node index.js" }, { "code": null, "e": 27057, "s": 26920, "text": "Now make a GET request to http://localhost:3000?title=GeeksforGeeks&domain=CS, then you will see the following output on your console: " }, { "code": null, "e": 27119, "s": 27057, "text": "Server listening on PORT 3000\nTitle: GeeksforGeeks\nDomain: CS" }, { "code": null, "e": 27178, "s": 27119, "text": "Reference: https://expressjs.com/en/4x/api.html#req.param " }, { "code": null, "e": 27191, "s": 27178, "text": "simmytarika5" }, { "code": null, "e": 27202, "s": 27191, "text": "Express.js" }, { "code": null, "e": 27210, "s": 27202, "text": "Node.js" }, { "code": null, "e": 27227, "s": 27210, "text": "Web Technologies" }, { "code": null, "e": 27325, "s": 27227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27334, "s": 27325, "text": "Comments" }, { "code": null, "e": 27347, "s": 27334, "text": "Old Comments" }, { "code": null, "e": 27377, "s": 27347, "text": "Node.js path.resolve() Method" }, { "code": null, "e": 27416, "s": 27377, "text": "Node.js crypto.createCipheriv() Method" }, { "code": null, "e": 27473, "s": 27416, "text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas" }, { "code": null, "e": 27499, "s": 27473, "text": "Node.js First Application" }, { "code": null, "e": 27552, "s": 27499, "text": "How to Integrate Stripe Payment Gateway in Node.js ?" }, { "code": null, "e": 27589, "s": 27552, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27634, "s": 27589, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27694, "s": 27634, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27755, "s": 27694, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
When to use @JsonManagedReference and @JsonBackReference annotations using Jackson in Java?
The @JsonManagedReference and @JsonBackReference annotations can be used to create a JSON structure in a bidirectional way. The @JsonManagedReference annotation is a forward reference that includes during the serialization process whereas @JsonBackReference annotation is a backreference that omits during the serialization process. In the below example, we can implement @JsonManagedReference and @JsonBackReference annotations. import java.util.*; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException; public class ManagedReferenceBackReferenceTest { public static void main(String args[]) throws JsonProcessingException { BackReferenceBeanTest testBean = new BackReferenceBeanTest(110, "Sai Chaitanya"); ManagedReferenceBeanTest bean = new ManagedReferenceBeanTest(135, "Adithya Ram", testBean); testBean.addEmployees(bean); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean); System.out.println(jsonString); } } class ManagedReferenceBeanTest { public int empId = 115; public String empName = "Raja Ramesh"; @JsonManagedReference public BackReferenceBeanTest manager; public ManagedReferenceBeanTest(int empId, String empName, BackReferenceBeanTest manager) { this.empId = empId; this.empName = empName; this.manager = manager; } } class BackReferenceBeanTest { public int empId = 125; public String empName = "Jai Dev"; @JsonBackReference public List<ManagedReferenceBeanTest> list; public BackReferenceBeanTest(int empId, String empName) { this.empId = empId; this.empName = empName; list = new ArrayList<ManagedReferenceBeanTest>(); } public void addEmployees(ManagedReferenceBeanTest managedReferenceBeanTest) { list.add(managedReferenceBeanTest); } } { "empId" : 135, "empName" : "Adithya Ram", "manager" : { "empId" : 110, "empName" : "Sai Chaitanya" } }
[ { "code": null, "e": 1395, "s": 1062, "text": "The @JsonManagedReference and @JsonBackReference annotations can be used to create a JSON structure in a bidirectional way. The @JsonManagedReference annotation is a forward reference that includes during the serialization process whereas @JsonBackReference annotation is a backreference that omits during the serialization process." }, { "code": null, "e": 1492, "s": 1395, "text": "In the below example, we can implement @JsonManagedReference and @JsonBackReference annotations." }, { "code": null, "e": 3102, "s": 1492, "text": "import java.util.*;\nimport com.fasterxml.jackson.annotation.JsonManagedReference;\nimport com.fasterxml.jackson.annotation.JsonBackReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.core.JsonProcessingException;\npublic class ManagedReferenceBackReferenceTest {\n public static void main(String args[]) throws JsonProcessingException {\n BackReferenceBeanTest testBean = new BackReferenceBeanTest(110, \"Sai Chaitanya\");\n ManagedReferenceBeanTest bean = new ManagedReferenceBeanTest(135, \"Adithya Ram\", testBean);\n testBean.addEmployees(bean);\n ObjectMapper mapper = new ObjectMapper();\n String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);\n System.out.println(jsonString);\n }\n}\nclass ManagedReferenceBeanTest {\n public int empId = 115;\n public String empName = \"Raja Ramesh\";\n @JsonManagedReference\n public BackReferenceBeanTest manager;\n public ManagedReferenceBeanTest(int empId, String empName, BackReferenceBeanTest manager) {\n this.empId = empId;\n this.empName = empName;\n this.manager = manager;\n }\n}\nclass BackReferenceBeanTest {\n public int empId = 125;\n public String empName = \"Jai Dev\";\n @JsonBackReference\n public List<ManagedReferenceBeanTest> list;\n public BackReferenceBeanTest(int empId, String empName) {\n this.empId = empId;\n this.empName = empName;\n list = new ArrayList<ManagedReferenceBeanTest>();\n }\n public void addEmployees(ManagedReferenceBeanTest managedReferenceBeanTest) {\n list.add(managedReferenceBeanTest);\n }\n}" }, { "code": null, "e": 3231, "s": 3102, "text": "{\n \"empId\" : 135,\n \"empName\" : \"Adithya Ram\",\n \"manager\" : {\n \"empId\" : 110,\n \"empName\" : \"Sai Chaitanya\"\n }\n}" } ]
JavaScript Function.prototype.call() Method - GeeksforGeeks
24 Jan, 2022 The call() method allows function calls belonging to one object to be assigned and it is called for a different object. It provides a new value of this to the function. The call() method allows you to write a method once and allows it for inheritance in another object, without rewriting the method for the new object. Syntax: myFunc.call([thisArg[, arg1, arg2, ...argN]]) Parameters: thisArg: The values to use as this when calling myFunc function. arg1, arg2, ..., argN: These are the arguments for the above mentioned function. Note: In certain cases, thisArg may not be the actual value. If the method is in non-strict mode, primitive values will be converted to objects and null,undefined will be replaced with the global object. Return value: It returns the specified this value and arguments as a result of calling of the function. Example 1: The following example demonstrates the use of calling to chain constructors for an object. html <script>function Product(name, price) { this.name = name; this.price = price; } function Vehicle(name, price) { Product.call(this, name, price); this.category = 'vehicle'; } function Restaurant(name, price) { Product.call(this, name, price); this.category = 'restaurant'; } const car = new Vehicle('Suzuki', 100000); const restau = new Restaurant('KFC', 1000); console.log(car); console.log(restaurant);</script> Output: Example 2: The following example demonstrates the use of call() method to invoke an anonymous function. html <script>const Birds = [ { species: 'Pigeon', name: 'King' }, { species: 'Crow', name: 'Fail' } ]; let i=0; while(i<Birds.length){ (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(Birds[i], i); ++i; }</script> Output: #0 Pigeon: King #1 Crow: Fail Example 3: The following example demonstrates the use of call method to invoke a function and specifying the context for ‘this’. html <script>function greet() { const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' '); console.log(reply); } const obj = { animal: 'Rats', sleepDuration: '2 and 5 hours' }; greet.call(obj);</script> Output: Rats typically sleep between 2 and 5 hours Example 4: The following example demonstrates the use of call() method to invoke a function without specifying the first argument. html <script>var str = 'Brad'; function display() { console.log('string value is %s ', this.str);} display.call();</script> Output: string value is Brad Note: In strict mode, the value of this will be undefined. html <script>'use strict'; var str = 'Brad'; function display() { console.log('str value is %s ', this.str);}display.call();</script> Output: Cannot read property 'str' of undefined surinderdawra388 JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to filter object array based on attributes? How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 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": 25220, "s": 25192, "text": "\n24 Jan, 2022" }, { "code": null, "e": 25539, "s": 25220, "text": "The call() method allows function calls belonging to one object to be assigned and it is called for a different object. It provides a new value of this to the function. The call() method allows you to write a method once and allows it for inheritance in another object, without rewriting the method for the new object." }, { "code": null, "e": 25549, "s": 25539, "text": "Syntax: " }, { "code": null, "e": 25595, "s": 25549, "text": "myFunc.call([thisArg[, arg1, arg2, ...argN]])" }, { "code": null, "e": 25609, "s": 25595, "text": "Parameters: " }, { "code": null, "e": 25674, "s": 25609, "text": "thisArg: The values to use as this when calling myFunc function." }, { "code": null, "e": 25755, "s": 25674, "text": "arg1, arg2, ..., argN: These are the arguments for the above mentioned function." }, { "code": null, "e": 25961, "s": 25757, "text": "Note: In certain cases, thisArg may not be the actual value. If the method is in non-strict mode, primitive values will be converted to objects and null,undefined will be replaced with the global object." }, { "code": null, "e": 26068, "s": 25963, "text": "Return value: It returns the specified this value and arguments as a result of calling of the function. " }, { "code": null, "e": 26170, "s": 26068, "text": "Example 1: The following example demonstrates the use of calling to chain constructors for an object." }, { "code": null, "e": 26177, "s": 26172, "text": "html" }, { "code": "<script>function Product(name, price) { this.name = name; this.price = price; } function Vehicle(name, price) { Product.call(this, name, price); this.category = 'vehicle'; } function Restaurant(name, price) { Product.call(this, name, price); this.category = 'restaurant'; } const car = new Vehicle('Suzuki', 100000); const restau = new Restaurant('KFC', 1000); console.log(car); console.log(restaurant);</script>", "e": 26683, "s": 26177, "text": null }, { "code": null, "e": 26691, "s": 26683, "text": "Output:" }, { "code": null, "e": 26795, "s": 26691, "text": "Example 2: The following example demonstrates the use of call() method to invoke an anonymous function." }, { "code": null, "e": 26800, "s": 26795, "text": "html" }, { "code": "<script>const Birds = [ { species: 'Pigeon', name: 'King' }, { species: 'Crow', name: 'Fail' } ]; let i=0; while(i<Birds.length){ (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(Birds[i], i); ++i; }</script>", "e": 27145, "s": 26800, "text": null }, { "code": null, "e": 27153, "s": 27145, "text": "Output:" }, { "code": null, "e": 27183, "s": 27153, "text": "#0 Pigeon: King\n#1 Crow: Fail" }, { "code": null, "e": 27312, "s": 27183, "text": "Example 3: The following example demonstrates the use of call method to invoke a function and specifying the context for ‘this’." }, { "code": null, "e": 27317, "s": 27312, "text": "html" }, { "code": "<script>function greet() { const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' '); console.log(reply); } const obj = { animal: 'Rats', sleepDuration: '2 and 5 hours' }; greet.call(obj);</script>", "e": 27572, "s": 27317, "text": null }, { "code": null, "e": 27582, "s": 27572, "text": "Output: " }, { "code": null, "e": 27626, "s": 27582, "text": " Rats typically sleep between 2 and 5 hours" }, { "code": null, "e": 27757, "s": 27626, "text": "Example 4: The following example demonstrates the use of call() method to invoke a function without specifying the first argument." }, { "code": null, "e": 27762, "s": 27757, "text": "html" }, { "code": "<script>var str = 'Brad'; function display() { console.log('string value is %s ', this.str);} display.call();</script>", "e": 27886, "s": 27762, "text": null }, { "code": null, "e": 27894, "s": 27886, "text": "Output:" }, { "code": null, "e": 27916, "s": 27894, "text": " string value is Brad" }, { "code": null, "e": 27975, "s": 27916, "text": "Note: In strict mode, the value of this will be undefined." }, { "code": null, "e": 27980, "s": 27975, "text": "html" }, { "code": "<script>'use strict'; var str = 'Brad'; function display() { console.log('str value is %s ', this.str);}display.call();</script>", "e": 28112, "s": 27980, "text": null }, { "code": null, "e": 28120, "s": 28112, "text": "Output:" }, { "code": null, "e": 28160, "s": 28120, "text": "Cannot read property 'str' of undefined" }, { "code": null, "e": 28177, "s": 28160, "text": "surinderdawra388" }, { "code": null, "e": 28188, "s": 28177, "text": "JavaScript" }, { "code": null, "e": 28205, "s": 28188, "text": "Web Technologies" }, { "code": null, "e": 28303, "s": 28205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28312, "s": 28303, "text": "Comments" }, { "code": null, "e": 28325, "s": 28312, "text": "Old Comments" }, { "code": null, "e": 28386, "s": 28325, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28427, "s": 28386, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28475, "s": 28427, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28537, "s": 28475, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 28594, "s": 28537, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 28627, "s": 28594, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28669, "s": 28627, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28712, "s": 28669, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28774, "s": 28712, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Introduction to Multilayer Neural Networks with TensorFlow’s Keras API | by Lorraine Li | Towards Data Science
Learn how to build and train a multilayer perceptron using TensorFlow’s high-level API Keras! The development of Keras started in early 2015. As of today, it has evolved into one of the most popular and widely used libraries built on top of Theano and TensorFlow. One of its prominent features is that it has a very intuitive and user-friendly API, which allows us to implement neural networks in only a few lines of code. Keras is also integrated into TensorFlow from version 1.1.0. It is part of the contrib module (which contains packages developed by contributors to TensorFlow and is considered experimental code). In this tutorial we will look at this high-level TensorFlow API by walking through: The basics of feedforward neural networks Loading and preparing the popular MNIST dataset Building an image classifier Train a neural network and evaluate its accuracy Let’s get started! This tutorial is adapted from Part 4 of Next Tech’s Python Machine Learning series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free here! Multilayer feedforward neural networks are a special type of fully connected network with multiple single neurons. They are also called Multilayer Perceptrons (MLP). The following figure illustrates the concept of an MLP consisting of three layers: The MLP depicted in the preceding figure has one input layer, one hidden layer, and one output layer. The units in the hidden layer are fully connected to the input layer, and the output layer is fully connected to the hidden layer. If such a network has more than one hidden layer, we also call it a deep artificial neural network. We can add an arbitrary number of hidden layers to the MLP to create deeper network architectures. Practically, we can think of the number of layers and units in a neural network as additional hyperparameters that we want to optimize for a given problem task. As shown in the preceding figure, we denote the ith activation unit in the ith layer as a_i^(l). To make the math and code implementations a bit more intuitive, we will use the in superscript for the input layer, the h superscript for the hidden layer, and the o superscript for the output layer. For instance, a_i^(in)​ refers to the ith value in the input layer, a_i^(h)​ refers to the ith unit in the hidden layer, and a_i^(out)​ refers to the ith unit in the output layer. Here, the activation units a_0^(in) and a_0^(out)​ are the bias units, which we set equal to 1. The activation of the units in the input layer is just its input plus the bias unit: Each unit in layer l is connected to all units in layer l + 1 via a weight coefficient. For example, the connection between the kth unit in layer l to the jth unit in layer l + 1 will be written as w_{k, j}^(l)​. Referring back to the previous figure, we denote the weight matrix that connects the input to the hidden layer as W^(h)​, and we write the matrix that connects the hidden layer to the output layer as W^(out)​. We summarize the weights that connect the input and hidden layers by a matrix: where d is the number of hidden units and m is the number of input units including the bias unit. Since it is important to internalize this notation to follow the concepts later in this tutorial, let’s summarize what we have just learned in a descriptive illustration of a simplified 3–4–3 multilayer perceptron: To see what neural network training via the tensorflow.keras (tf.keras) high-level API looks like, let's implement a multilayer perceptron to classify the handwritten digits from the popular Mixed National Institute of Standards and Technology (MNIST) dataset that serves as a popular benchmark dataset for machine learning algorithm. To follow along with the code snippets in this tutorial, you can use this Next Tech sandbox, which has the MNIST dataset and all necessary packages installed. Otherwise, you can use your local environment and download the dataset here. The MNIST dataset in four parts, as listed here: Training set images: train-images-idx3-ubyte.gz — 60,000 samples Training set labels: train-labels-idx1-ubyte.gz — 60,000 labels Test set images: t10k-images-idx3-ubyte.gz — 10,000 samples Test set labels: t10k-labels-idx1-ubyte.gz — 10,000 labels The training set consists of handwritten digits from 250 different people (50% high school students, 50% employees from the Census Bureau). The test set contains handwritten digits from different people. Note that TensorFlow also provides the same dataset as follows: However, we will work with the MNIST dataset as an external dataset to learn all the steps of data preprocessing separately. This way, you learn what you need to do with your own dataset. The first step is to unzip the four parts of the MNIST dataset by running the following commands in your Terminal: The load_mnist function returns two arrays, the first being an n x m dimensional NumPy array (images), where n is the number of samples and m is the number of features (here, pixels). The images in the MNIST dataset consist of 28 x 28 pixels, and each pixel is represented by a gray scale intensity value. Here, we unroll the 28 x 28 pixels into one-dimensional row vectors, which represent the rows in our images array (784 per row or image). The second array (labels) returned by the load_mnist function contains the corresponding target variable, the class labels (integers 0-9) of the handwritten digits. Then, the dataset is loaded and prepared as follows: [Out:] Rows: 60000, Columns: 784 Rows: 10000, Columns: 784 (60000, 784) (60000,) (10000, 784) (10000,) To get an idea of how those images in MNIST look, let’s visualize examples of the digits 0–9 via Matplotlib’s imshowfunction: We should now see a plot of the 2 x 5 subfigures showing a representative image of each unique digit: Now let’s start building our model! First, let’s set the random seed for NumPy and TensorFlow so that we get consistent results: To continue with the preparation of the training data, we need to convert the class labels (integers 0–9) into the one-hot format. Fortunately, Keras provides a convenient tool for this: First 3 labels: [5 0 4]First 3 labels (one-hot): [[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]] Now, let’s implement our neural network! Briefly, we will have three layers, where the first two layers (the input and hidden layers) each have 50 units with the tanh activation function and the last layer (the output layer) has 10 layers for the 10 class labels and uses softmax to give the probability of each class. Keras makes these tasks very simple: First, we initialize a new model using the Sequential class to implement a feedforward neural network. Then, we can add as many layers to it as we like. However, since the first layer that we add is the input layer, we have to make sure that the input_dim attribute matches the number of features (columns) in the training set (784 features or pixels in the neural network implementation). Also, we have to make sure that the number of output units (units) and input units (input_dim) of two consecutive layers match. Our first two layers have 50 units plus one bias unit each. The number of units in the output layer should be equal to the number of unique class labels — the number of columns in the one-hot-encoded class label array. Note that we used glorot_uniform to as the initialization algorithm for weight matrices. Glorot initialization is a more robust way of initialization for deep neural networks. The biases are initialized to zero, which is more common, and in fact the default setting in Keras. Before we can compile our model, we also have to define an optimizer. We chose a stochastic gradient descent optimization. Furthermore, we can set values for the weight decay constant and momentum learning to adjust the learning rate at each epoch. Lastly, we set the cost (or loss) function to categorical_crossentropy. The binary cross-entropy is just a technical term for the cost function in the logistic regression, and the categorical cross-entropy is its generalization for multiclass predictions via softmax. After compiling the model, we can now train it by calling the fit method. Here, we are using mini-batch stochastic gradient with a batch size of 64 training samples per batch. We train the MLP over 50 epochs, and we can follow the optimization of the cost function during training by setting verbose=1. The validation_split parameter is especially handy since it will reserve 10% of the training data (here, 6,000 samples) for validation after each epoch so that we can monitor whether the model is overfitting during training: Printing the value of the cost function is extremely useful during training to quickly spot whether the cost is decreasing during training and stop the algorithm earlier. Otherwise, hyperparameter values will need to be tuned. To predict the class labels, we can then use the predict_classes method to return the class labels directly as integers: First 3 predictions: [5 0 4] Finally, let’s print the model accuracy on training and test sets: Training accuracy: 98.81Test accuracy: 96.27 I hope you enjoyed this tutorial on using TensorFlow's keras API to build and train a multilayered neural network for image classification! Note that this is just a very simple neural network without optimized tuning parameters. In practice you need to know how to optimize the model by tweaking learning rate, momentum, weight decay, and number of hidden units. You also need to learn how to deal with the vanishing gradient problem, wherein error gradients become increasingly small as more layers are added to a network. We cover these topics in Next Tech’s Python Machine Learning (Part 4) course, as well as: Breaking down the mechanics of TensorFlow, such as tensors, activation functions computation graphs, variables, and placeholders Low-level TensorFlow and another high-level API, Layers Modeling sequential data using recurrent neural networks (RNN) and long short-term memory (LSTM) networks Classifying images with deep convolutional neural networks (CNN). You can get started here for free!
[ { "code": null, "e": 266, "s": 172, "text": "Learn how to build and train a multilayer perceptron using TensorFlow’s high-level API Keras!" }, { "code": null, "e": 595, "s": 266, "text": "The development of Keras started in early 2015. As of today, it has evolved into one of the most popular and widely used libraries built on top of Theano and TensorFlow. One of its prominent features is that it has a very intuitive and user-friendly API, which allows us to implement neural networks in only a few lines of code." }, { "code": null, "e": 792, "s": 595, "text": "Keras is also integrated into TensorFlow from version 1.1.0. It is part of the contrib module (which contains packages developed by contributors to TensorFlow and is considered experimental code)." }, { "code": null, "e": 876, "s": 792, "text": "In this tutorial we will look at this high-level TensorFlow API by walking through:" }, { "code": null, "e": 918, "s": 876, "text": "The basics of feedforward neural networks" }, { "code": null, "e": 966, "s": 918, "text": "Loading and preparing the popular MNIST dataset" }, { "code": null, "e": 995, "s": 966, "text": "Building an image classifier" }, { "code": null, "e": 1044, "s": 995, "text": "Train a neural network and evaluate its accuracy" }, { "code": null, "e": 1063, "s": 1044, "text": "Let’s get started!" }, { "code": null, "e": 1424, "s": 1063, "text": "This tutorial is adapted from Part 4 of Next Tech’s Python Machine Learning series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free here!" }, { "code": null, "e": 1673, "s": 1424, "text": "Multilayer feedforward neural networks are a special type of fully connected network with multiple single neurons. They are also called Multilayer Perceptrons (MLP). The following figure illustrates the concept of an MLP consisting of three layers:" }, { "code": null, "e": 2006, "s": 1673, "text": "The MLP depicted in the preceding figure has one input layer, one hidden layer, and one output layer. The units in the hidden layer are fully connected to the input layer, and the output layer is fully connected to the hidden layer. If such a network has more than one hidden layer, we also call it a deep artificial neural network." }, { "code": null, "e": 2266, "s": 2006, "text": "We can add an arbitrary number of hidden layers to the MLP to create deeper network architectures. Practically, we can think of the number of layers and units in a neural network as additional hyperparameters that we want to optimize for a given problem task." }, { "code": null, "e": 2563, "s": 2266, "text": "As shown in the preceding figure, we denote the ith activation unit in the ith layer as a_i^(l). To make the math and code implementations a bit more intuitive, we will use the in superscript for the input layer, the h superscript for the hidden layer, and the o superscript for the output layer." }, { "code": null, "e": 2924, "s": 2563, "text": "For instance, a_i^(in)​ refers to the ith value in the input layer, a_i^(h)​ refers to the ith unit in the hidden layer, and a_i^(out)​ refers to the ith unit in the output layer. Here, the activation units a_0^(in) and a_0^(out)​ are the bias units, which we set equal to 1. The activation of the units in the input layer is just its input plus the bias unit:" }, { "code": null, "e": 3347, "s": 2924, "text": "Each unit in layer l is connected to all units in layer l + 1 via a weight coefficient. For example, the connection between the kth unit in layer l to the jth unit in layer l + 1 will be written as w_{k, j}^(l)​. Referring back to the previous figure, we denote the weight matrix that connects the input to the hidden layer as W^(h)​, and we write the matrix that connects the hidden layer to the output layer as W^(out)​." }, { "code": null, "e": 3426, "s": 3347, "text": "We summarize the weights that connect the input and hidden layers by a matrix:" }, { "code": null, "e": 3739, "s": 3426, "text": "where d is the number of hidden units and m is the number of input units including the bias unit. Since it is important to internalize this notation to follow the concepts later in this tutorial, let’s summarize what we have just learned in a descriptive illustration of a simplified 3–4–3 multilayer perceptron:" }, { "code": null, "e": 4074, "s": 3739, "text": "To see what neural network training via the tensorflow.keras (tf.keras) high-level API looks like, let's implement a multilayer perceptron to classify the handwritten digits from the popular Mixed National Institute of Standards and Technology (MNIST) dataset that serves as a popular benchmark dataset for machine learning algorithm." }, { "code": null, "e": 4310, "s": 4074, "text": "To follow along with the code snippets in this tutorial, you can use this Next Tech sandbox, which has the MNIST dataset and all necessary packages installed. Otherwise, you can use your local environment and download the dataset here." }, { "code": null, "e": 4359, "s": 4310, "text": "The MNIST dataset in four parts, as listed here:" }, { "code": null, "e": 4424, "s": 4359, "text": "Training set images: train-images-idx3-ubyte.gz — 60,000 samples" }, { "code": null, "e": 4488, "s": 4424, "text": "Training set labels: train-labels-idx1-ubyte.gz — 60,000 labels" }, { "code": null, "e": 4548, "s": 4488, "text": "Test set images: t10k-images-idx3-ubyte.gz — 10,000 samples" }, { "code": null, "e": 4607, "s": 4548, "text": "Test set labels: t10k-labels-idx1-ubyte.gz — 10,000 labels" }, { "code": null, "e": 4811, "s": 4607, "text": "The training set consists of handwritten digits from 250 different people (50% high school students, 50% employees from the Census Bureau). The test set contains handwritten digits from different people." }, { "code": null, "e": 4875, "s": 4811, "text": "Note that TensorFlow also provides the same dataset as follows:" }, { "code": null, "e": 5063, "s": 4875, "text": "However, we will work with the MNIST dataset as an external dataset to learn all the steps of data preprocessing separately. This way, you learn what you need to do with your own dataset." }, { "code": null, "e": 5178, "s": 5063, "text": "The first step is to unzip the four parts of the MNIST dataset by running the following commands in your Terminal:" }, { "code": null, "e": 5787, "s": 5178, "text": "The load_mnist function returns two arrays, the first being an n x m dimensional NumPy array (images), where n is the number of samples and m is the number of features (here, pixels). The images in the MNIST dataset consist of 28 x 28 pixels, and each pixel is represented by a gray scale intensity value. Here, we unroll the 28 x 28 pixels into one-dimensional row vectors, which represent the rows in our images array (784 per row or image). The second array (labels) returned by the load_mnist function contains the corresponding target variable, the class labels (integers 0-9) of the handwritten digits." }, { "code": null, "e": 5840, "s": 5787, "text": "Then, the dataset is loaded and prepared as follows:" }, { "code": null, "e": 5945, "s": 5840, "text": "[Out:] Rows: 60000, Columns: 784 Rows: 10000, Columns: 784 (60000, 784) (60000,) (10000, 784) (10000,)" }, { "code": null, "e": 6071, "s": 5945, "text": "To get an idea of how those images in MNIST look, let’s visualize examples of the digits 0–9 via Matplotlib’s imshowfunction:" }, { "code": null, "e": 6173, "s": 6071, "text": "We should now see a plot of the 2 x 5 subfigures showing a representative image of each unique digit:" }, { "code": null, "e": 6209, "s": 6173, "text": "Now let’s start building our model!" }, { "code": null, "e": 6302, "s": 6209, "text": "First, let’s set the random seed for NumPy and TensorFlow so that we get consistent results:" }, { "code": null, "e": 6489, "s": 6302, "text": "To continue with the preparation of the training data, we need to convert the class labels (integers 0–9) into the one-hot format. Fortunately, Keras provides a convenient tool for this:" }, { "code": null, "e": 6637, "s": 6489, "text": "First 3 labels: [5 0 4]First 3 labels (one-hot): [[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]" }, { "code": null, "e": 6993, "s": 6637, "text": "Now, let’s implement our neural network! Briefly, we will have three layers, where the first two layers (the input and hidden layers) each have 50 units with the tanh activation function and the last layer (the output layer) has 10 layers for the 10 class labels and uses softmax to give the probability of each class. Keras makes these tasks very simple:" }, { "code": null, "e": 7383, "s": 6993, "text": "First, we initialize a new model using the Sequential class to implement a feedforward neural network. Then, we can add as many layers to it as we like. However, since the first layer that we add is the input layer, we have to make sure that the input_dim attribute matches the number of features (columns) in the training set (784 features or pixels in the neural network implementation)." }, { "code": null, "e": 7730, "s": 7383, "text": "Also, we have to make sure that the number of output units (units) and input units (input_dim) of two consecutive layers match. Our first two layers have 50 units plus one bias unit each. The number of units in the output layer should be equal to the number of unique class labels — the number of columns in the one-hot-encoded class label array." }, { "code": null, "e": 8006, "s": 7730, "text": "Note that we used glorot_uniform to as the initialization algorithm for weight matrices. Glorot initialization is a more robust way of initialization for deep neural networks. The biases are initialized to zero, which is more common, and in fact the default setting in Keras." }, { "code": null, "e": 8327, "s": 8006, "text": "Before we can compile our model, we also have to define an optimizer. We chose a stochastic gradient descent optimization. Furthermore, we can set values for the weight decay constant and momentum learning to adjust the learning rate at each epoch. Lastly, we set the cost (or loss) function to categorical_crossentropy." }, { "code": null, "e": 8523, "s": 8327, "text": "The binary cross-entropy is just a technical term for the cost function in the logistic regression, and the categorical cross-entropy is its generalization for multiclass predictions via softmax." }, { "code": null, "e": 8826, "s": 8523, "text": "After compiling the model, we can now train it by calling the fit method. Here, we are using mini-batch stochastic gradient with a batch size of 64 training samples per batch. We train the MLP over 50 epochs, and we can follow the optimization of the cost function during training by setting verbose=1." }, { "code": null, "e": 9051, "s": 8826, "text": "The validation_split parameter is especially handy since it will reserve 10% of the training data (here, 6,000 samples) for validation after each epoch so that we can monitor whether the model is overfitting during training:" }, { "code": null, "e": 9278, "s": 9051, "text": "Printing the value of the cost function is extremely useful during training to quickly spot whether the cost is decreasing during training and stop the algorithm earlier. Otherwise, hyperparameter values will need to be tuned." }, { "code": null, "e": 9399, "s": 9278, "text": "To predict the class labels, we can then use the predict_classes method to return the class labels directly as integers:" }, { "code": null, "e": 9428, "s": 9399, "text": "First 3 predictions: [5 0 4]" }, { "code": null, "e": 9495, "s": 9428, "text": "Finally, let’s print the model accuracy on training and test sets:" }, { "code": null, "e": 9540, "s": 9495, "text": "Training accuracy: 98.81Test accuracy: 96.27" }, { "code": null, "e": 9769, "s": 9540, "text": "I hope you enjoyed this tutorial on using TensorFlow's keras API to build and train a multilayered neural network for image classification! Note that this is just a very simple neural network without optimized tuning parameters." }, { "code": null, "e": 10064, "s": 9769, "text": "In practice you need to know how to optimize the model by tweaking learning rate, momentum, weight decay, and number of hidden units. You also need to learn how to deal with the vanishing gradient problem, wherein error gradients become increasingly small as more layers are added to a network." }, { "code": null, "e": 10154, "s": 10064, "text": "We cover these topics in Next Tech’s Python Machine Learning (Part 4) course, as well as:" }, { "code": null, "e": 10283, "s": 10154, "text": "Breaking down the mechanics of TensorFlow, such as tensors, activation functions computation graphs, variables, and placeholders" }, { "code": null, "e": 10339, "s": 10283, "text": "Low-level TensorFlow and another high-level API, Layers" }, { "code": null, "e": 10445, "s": 10339, "text": "Modeling sequential data using recurrent neural networks (RNN) and long short-term memory (LSTM) networks" }, { "code": null, "e": 10511, "s": 10445, "text": "Classifying images with deep convolutional neural networks (CNN)." } ]
Clustering sentence embeddings to identify intents in short text | by David Borrelli | Towards Data Science
TL;DR The unsupervised learning problem of clustering short-text messages can be turned into a constrained optimization problem to automatically tune UMAP + HDBSCAN hyperparameters. The chatintents package makes it easy to implement this tuning process. User dialogue interactions can be a tremendous source of information on how to improve products or services. Understanding why people are reaching out to customer service is also an important first step in automating some or all of the replies (for example, with a chatbot). There are several ways to analyze dialogue interaction data to extract useful insights, and it is common to characterize the interactions by topics discussed, sentiment and intent. Determining the intent is particularly useful from the perspective of wanting to improve products or services because it answers the question: why are people reaching out to begin with? However, a major hurdle to leveraging user message intent is that determining it is typically treated as a classification problem. This means you usually need to already have a significant amount of labeled data to get started. For example, Microsoft’s LUIS and Google’s Dialogflow both start with the premise that you can either use prebuilt domain labeled data or that you already have labeled data. But what if you don’t yet have any labeled data and you don’t think any publicly-available labeled data is relevant (as is often the case)? On top of the challenge of having an unsupervised learning problem, the messages containing the intent are typically quite short (less than 15 words). I was recently tasked with this challenge, with one additional hurdle: we only had about 1,000 samples total. I immediately remembered some sage advice I had seen years ago: After thinking about my particular problem for a bit and making a few unfruitful attempts at treating this as an unsupervised learning problem, I ultimately manually labeled the data (it took about a week...). Doing the labeling manually gave me a helpful appreciation and intuition for the data. But at the same time it made me very curious to see if there is a way to get most of the way to those labeled intents in a much more automated way. This post will provide an approach I learned that can automatically cluster short-text message data to identify and extract intents. Before we go further, let’s first define what we’re trying to do. Here I’m interested in answering the question: given an unlabeled set of dialogues between a user and some company representative, is there a way to obtain a helpful labeling of user intents in an automated way? As this is an unsupervised problem and labeling intents can be quite subjective, I wouldn’t expect to be able to find a perfect solution. But, similar to how auto-EDA libraries aren’t exhaustive but can provide a helpful starting point when confronted with new data, can we do something to provide initial insights before committing to time-consuming manual labeling? It’s possible that the automated results could be good enough, saving someone from a week or more of manually labeling data. Alternatively, it could speed up the labeling process by providing a helpful starting point. Obviously, I’m not able to share the original dataset that inspired this article, so I set out to find something as similar as I could that is publicly available. While several dialogue datasets exist that have labeled intents, a major limitation in many of them is the small number of intents represented (often ~10). Having a small number of intents, or classes, will make the problem too simple. Although the manual labeling process is inherently subjective, I found there to easily be more than 50 intents, unequally represented, for the data I was working with. That seems to be fairly common for real-world applications. Thankfully the PolyAI team published the banking77 dataset, which contains 77 intents represented unequally: The full dataset contains 10,0003 messages in the training dataset across 77 intents. The maximum and minimum category counts are 187 and 35, respectively. In order to more closely match the challenge I previously faced, I’ll randomly sample only 1,000 of the 10,000 total samples from the training set: data_sample = data_full.sample(1000, random_state=123) Note that while this dataset is useful for this exercise for demonstration purposes, this is still somewhat artificial and you’ll face additional challenges in a real-world setting. For example, you’ll first need to identify what message or sentence in a full dialogue sequence actually relates to the intent, as well as handle random system error messages, typos and nonsensical messages. This post on discovering and classifying AirBnB message intents touches on some of the real-world challenges. There are several ways to approach an unsupervised learning problem like this. Topic modeling was the first method that came to mind when confronted with this problem. It’s a technique used to discover latent topics in a collection of documents. Many algorithms can be used to perform topic modeling, but one very common one is Latent Dirichlet Allocation (LDA). LDA is a generative probabilistic model that assumes that each document is made up of a distribution of a fixed number of topics and each topic is made up of a distribution of words. A big challenge when trying to use LDA (and many other topic modeling algorithms) is deciding how many topics to actually use, which is a necessary model hyperparameter. Obviously, if that is what we’re hoping to get out of the analysis then this is a problem. Coherence is one way to assess the quality of the learned topics by measuring how similar the words are in each topic, and a higher coherence score is better. Gensim, a very popular library for topic modeling, makes it easy to calculate model coherence. Unfortunately, for the short texts we’re working with here, it isn’t obvious how many topics to pick using coherence: It appears as though increasing the number of topics continues to increase the coherence for this dataset, giving us little guidance as to how many topics to choose. Adding to the challenges, topic models can be hard to interpret. For example, consider the identified topics below: While some of the topics make sense, many are hard to interpret. This article series about work at Pew Research does a great job walking through the challenges of interpreting topic models. Ultimately, the biggest issue is that intents are more nuanced than topics. A limitation in LDA and other topic modeling approaches is that they treat the vocabulary in the documents as a bag of words, where the order doesn’t matter. This works well for longer documents (and a larger corpus), where identifying words that co-occur can provide a good picture of the topics. Additionally, there are often a relatively small number of topics, and the topics are fairly distinct. However, short-text intents create challenges, such as two phrases having nearly identical words but very different intents or having the same intent but almost no words in common. This severely limits the usefulness of standard topic modeling approaches for identifying intents in short text. Aside from topic modeling, clustering is another very common approach to unsupervised learning problems. In order to be able to cluster text data, we’ll need to make multiple decisions, including how to process the data and what algorithms to use. First, it is necessary to represent our text data numerically. One approach is to create embeddings, or vector representations, of each word to use for the clustering. This article gives a good overview of various ways of embedding words. Since each message consists of several words, one option is to then simply average the individual word embeddings of all the words in each message. This has worked well enough for some applications, but it would be better to directly calculate an embedding for the full sentences to more effectively take meaning into account. Especially given how short each message is, this will help avoid some of the pitfalls of the topic modeling algorithms described above. It turns out that there are many ways to find a single vector representation of a full message or sentence. This article gives a great overview of the various methods to achieve this. Google’s Universal Sentence Encoder (USE), first published by Cer et al in 2018, is a popular sentence embedding model. The USE model was trained on a variety of data, including Wikipedia, web news, web question-answer pages and discussion forums, and it performs well on sentence semantic similarity tasks. In 2019, Reimers and Gurevych published a paper introducing Sentence-BERT, a “modification of the pretrained BERT network that use siamese and triplet network structures to derive semantically meaningful sentence embeddings that can be compared using cosine-similarity”. They also released a Python implementation that makes it easy to download and use many different pre-trained models. Given how small our dataset is, using a pre-trained model is preferable here. For this analysis, I’ll compare the results of four pre-trained sentence embedding models: USE and three different sentence-BERT models (all-mpnet-base-v2, all-MiniLM-L6-v2 and all-distilroberta-v1). Converting our messages into sentence embeddings is then straightforward: As seen above, all of our sentence embeddings have high dimensionality (>500 features each). A manifestation of the Curse of Dimensionality is that distance measures, such as Euclidean and Manhattan, needed for clustering become meaningless at such high dimensions (see for example “On the Surprising Behavior of Distance Metrics in High Dimensional Space” by Aggarwal et al for more details). While some of the sentence-transformer pre-trained models were created in a way to preserve the usefulness of some distance measures, dimensionality reduction before clustering will greatly improve the results. (To prove this to myself, I briefly explored using different clustering algorithms and embeddings without dimensionality reduction first.) Uniform Manifold Approximation and Projection for Dimension Reduction (UMAP), introduced by McInnes et al in 2020, has quickly grown in popularity as a dimensionality reduction technique. UMAP is much faster and more scalable than t-SNE, while also preserving the global structure of the data much better. This makes it useful for both visualization and as a preprocessing dimensionality reduction step to use before clustering. We’ll use it here for both. The Scikit-learn documentation has a helpful overview of the many different clustering algorithms it supports and when each performs best. For our current application, it is preferable to use an algorithm that does not require specifying the number of clusters upfront and can also tolerate noisy data. Density-based algorithms are a good option here as they do not require specifying the number of clusters and are indifferent to cluster shape. Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN) has become popular since it has fewer and more intuitive hyperparameters than DBSCAN and is robust to variable-density clusters. The HDBSCAN documentation provides a helpful comparison of different clustering algorithms. HDBSCAN worked best for the current problem, so we’ll focus on it for this post. There are at least two packages (and likely many more) already available to chain UMAP and HDBSCAN together for the purposes of topic modeling: Top2Vec (github and paper) and BERTopic (github and article). However, the default hyperparameters used in both packages do not work well for problems like the current one with short text and a small corpus (most of the data ends up being classified as noise and only three clusters total are found). To make it easier to tailor to our current problem of intent extraction, we’ll instead directly use the UMAP and HDBSCAN packages for hyperparameter tuning. UMAP has several hyperparameters that control how it performs dimensionality reduction, but two of the most important are n_neighbors and n_components. The n_neighbors parameter controls how UMAP balances local versus global structure in the data. This parameter controls the size of the neighborhood UMAP looks to learn the manifold structure, and so lower values of n_neighbors will focus more on the very local structure. The n_components parameter controls the dimensionality of the final embedded data after performing dimensionality reduction on the input data. Unfortunately, there is no obvious way to pick the best UMAP parameters by itself without ground truth labels. Here we do have the labels, which we’ll use at the end to determine how well we did. But the point of this work is to identify a methodology to use when we have unlabeled data. In Angelov’s Top2Vec paper he mentions that n_neighbors = 15 and n_components = 5 worked best for his downstream tasks, but it is unlikely this would always be the case for any dataset. HDBSCAN also has several important hyperparameters, but the most important one to consider is min_cluster_size. Intuitively, this controls the smallest grouping you want to consider as a cluster. In addition, the min_samples parameter, which defaults to being equal to min_cluster_size if unspecified, controls how conservative the clustering is. The larger it is, the more points are discarded as noise/outliers. Decoupling the two hyperparameters and having a smaller min_samples than min_cluster_size will essentially keep points that would have been labeled as outliers by merging them with their most similar neighboring clusters. This isn’t exactly what we want to happen if we’re trying to uncover the number of clusters. Thus, here I’ll only consider directly modifying the min_cluster_size parameter: Note that UMAP is a stochastic algorithm, using randomness to speed up approximation steps and perform the optimization. Thus, we’ll set the random seed state to a constant value to get consistent results for a given set of UMAP hyperparameters. We now have a pipeline with three hyperparameters (n_neighbors, n_components, and min_cluster_size) that we want to tune. Next, we need to decide how to actually evaluate our clusters to select the best hyperparameters. Although commonly used with various clustering algorithms, Silhouette Score is not a good validation metric for density-based algorithms like DBSCAN and HDBSCAN since it assumes all points are assigned a group and can’t appropriately handle noise/outliers. Density Based Cluster Validation (DBCV) has been proposed and used by some for tuning HDBSCAN hyperparameters. While it likely works well for several applications, for this current problem it favored having a smaller number of clusters and leaving too many samples in the “noise” category. Instead, we’ll leverage the useful probabilities_ HDBSCAN attribute, which from the documentation is: The strength with which each sample is a member of its assigned cluster. Noise points have probability zero; points in clusters have values assigned proportional to the degree that they persist as part of the cluster. This article by Nikolay Oskolkov provides a very intuitive and logical solution of simply defining our cost function that we want to minimize as: Cost = percent of dataset with < 5% cluster label confidence This will help ensure that we assign as many data points as we can to actual clusters instead of labeling them as noise. But what’s stopping us from setting the hyperparameters to make every individual point a “cluster”, or just making one giant cluster? Here we have to use some domain knowledge to apply constraints. For this problem, based on my experience with this kind of data, I expected there to be at least 30 labels, but no more than 100. So our objective function becomes a constrained optimization problem: minimize(Cost = percent of dataset with < 5% cluster label confidence)Subject to: 30 < num_clusters < 100 With the current dataset size of only 1,000 samples, it still takes about 3 seconds to generate the clusters and score them for a given set of inputs. Attempting to do a full grid search of, for example, a 10 x 10 x 10 hyperparameter search space would take almost an hour. Larger dataset sizes would take even longer. I care about finding the right hyperparameters, but not that much. Performing a random search instead of a full grid search is a pretty effective alternative strategy: Running the search for 100 randomly-selected hyperparameter values yields: We see that the runs with the lowest cost also have less than 10 clusters total. The first entry with a number of clusters between 30 and 100 has 59 clusters and a cost of 0.140 (i.e. about 14% of the data was labeled as outliers or low confidence). It only took 6 minutes to run too. Not bad. Randomly searching the hyperparameter space works reasonably well, but there is a better option: Bayesian optimization. Here we’ll leverage the popular hyperopt package to do so. If you’re unfamiliar with hyperopt and Bayesian optimization, this article provides a good overview. First, define the objective function that we want to minimize. The optimization constraints are included within the objective function by adding a penalty term if the number of clusters falls outside of the desired range: Then minimize the objective function over the hyperparameter search space using the Tree-structured Parzen Estimator (TPE) algorithm: Running the Bayesian search with 100 max evaluations over our parameter space yields slightly better results than random search: It’s then easy to run the pipeline using embeddings from multiple different models: At this point we could do a few more things, like visualize the clusters or manually inspect some of them to make sure they make sense. But ultimately we’re trying to find the “best” clustering results from the best analysis pipeline. If we trust our loss function, then it makes sense to pick the configuration with the lowest loss. Of the combinations tried above, it seems that we should go with sentence-transformer #1 (all-mpnet-base-v2), which generated 55 clusters using n_neighbors = 6, n_comonents= 9, and min_cluster_size = 6. In this case, we happen to also know the ground truth labels so we can see how well our loss function correlates with performance. We can manually inspect how well the models did on some of the ground truth clusters: As shown above, all models seem to do relatively well on placing most of messages in the card_about_to_expire ground-truth group in the same clusters. At least for this category, the first sentence-transformer model seems to stand out in correctly assigning all messages to the same cluster. Rather than manually inspecting all groups, we can also quantitatively assess the model performances. Two commonly-used metrics for evaluating text clustering are the Normalized Mutual Information and Adjusted Rand Index. Both metrics have values ranging from 0 to 1, where larger is better. Calculating these metrics for the best hyperparameters of the four models under consideration yields: In agreement with our previous conclusion, sentence-transformer #1 does in fact perform the best, with an ARI of 0.46 and an NMI of 0.81. However, the performance ordering for some of the other models do not follow the order expected from their cost function values. Thus, our scoring method for hyperparameter tuning isn’t perfect, but it is clearly still useful for the current application. To make the results even more helpful, we can also automatically apply descriptive labels to the clusters we found. A paper by Liu et al provides an interesting approach to doing this by extracting the most common action-object pair from the phrases in each cluster as the cluster label (e.g. “book-flight”). The bank77 dataset we’re considering here is a little more complicated than the dataset in that paper, but we can do something similar. Here we’ll concatenate the most common verb, direct object, and top two nouns from each cluster. The spaCy package has a powerful syntactic dependency parser that we can use for this: We can write a simple function to extract these labels for each cluster: Applying these labels to each of the clusters that our best model found yields our final result: Using our tuning method, we’ve automatically extracted and applied descriptive labels to 55 clusters in our dataset. Since in this case we know the ground truth labels for each document, we can also inspect a few documents to see how well our derived labels match the ground truth labels: They aren’t perfect, but the extracted labels match the ground category labels pretty well! In this post, I outlined a framework for leveraging domain knowledge to create a constrained optimization problem to automatically tune UMAP and HDBSCAN hyperparameters. This allows us to easily cluster short-text documents and apply descriptive labels. The focus for this article was on a small dataset, but the same method can be applied to larger datasets as well. The clustering results provide helpful insights of unlabeled text data in a very short amount of time, before deciding or needing to complete time-intensive manual labeling. All code examples from this article, along with the chatintents python package I created to make applying these concepts easier, can be found here: github.com Thanks for reading. If you found this article helpful, drop a comment below or connect on LinkedIn.
[ { "code": null, "e": 426, "s": 172, "text": "TL;DR The unsupervised learning problem of clustering short-text messages can be turned into a constrained optimization problem to automatically tune UMAP + HDBSCAN hyperparameters. The chatintents package makes it easy to implement this tuning process." }, { "code": null, "e": 882, "s": 426, "text": "User dialogue interactions can be a tremendous source of information on how to improve products or services. Understanding why people are reaching out to customer service is also an important first step in automating some or all of the replies (for example, with a chatbot). There are several ways to analyze dialogue interaction data to extract useful insights, and it is common to characterize the interactions by topics discussed, sentiment and intent." }, { "code": null, "e": 1470, "s": 882, "text": "Determining the intent is particularly useful from the perspective of wanting to improve products or services because it answers the question: why are people reaching out to begin with? However, a major hurdle to leveraging user message intent is that determining it is typically treated as a classification problem. This means you usually need to already have a significant amount of labeled data to get started. For example, Microsoft’s LUIS and Google’s Dialogflow both start with the premise that you can either use prebuilt domain labeled data or that you already have labeled data." }, { "code": null, "e": 1935, "s": 1470, "text": "But what if you don’t yet have any labeled data and you don’t think any publicly-available labeled data is relevant (as is often the case)? On top of the challenge of having an unsupervised learning problem, the messages containing the intent are typically quite short (less than 15 words). I was recently tasked with this challenge, with one additional hurdle: we only had about 1,000 samples total. I immediately remembered some sage advice I had seen years ago:" }, { "code": null, "e": 2513, "s": 1935, "text": "After thinking about my particular problem for a bit and making a few unfruitful attempts at treating this as an unsupervised learning problem, I ultimately manually labeled the data (it took about a week...). Doing the labeling manually gave me a helpful appreciation and intuition for the data. But at the same time it made me very curious to see if there is a way to get most of the way to those labeled intents in a much more automated way. This post will provide an approach I learned that can automatically cluster short-text message data to identify and extract intents." }, { "code": null, "e": 2626, "s": 2513, "text": "Before we go further, let’s first define what we’re trying to do. Here I’m interested in answering the question:" }, { "code": null, "e": 2791, "s": 2626, "text": "given an unlabeled set of dialogues between a user and some company representative, is there a way to obtain a helpful labeling of user intents in an automated way?" }, { "code": null, "e": 3377, "s": 2791, "text": "As this is an unsupervised problem and labeling intents can be quite subjective, I wouldn’t expect to be able to find a perfect solution. But, similar to how auto-EDA libraries aren’t exhaustive but can provide a helpful starting point when confronted with new data, can we do something to provide initial insights before committing to time-consuming manual labeling? It’s possible that the automated results could be good enough, saving someone from a week or more of manually labeling data. Alternatively, it could speed up the labeling process by providing a helpful starting point." }, { "code": null, "e": 4004, "s": 3377, "text": "Obviously, I’m not able to share the original dataset that inspired this article, so I set out to find something as similar as I could that is publicly available. While several dialogue datasets exist that have labeled intents, a major limitation in many of them is the small number of intents represented (often ~10). Having a small number of intents, or classes, will make the problem too simple. Although the manual labeling process is inherently subjective, I found there to easily be more than 50 intents, unequally represented, for the data I was working with. That seems to be fairly common for real-world applications." }, { "code": null, "e": 4113, "s": 4004, "text": "Thankfully the PolyAI team published the banking77 dataset, which contains 77 intents represented unequally:" }, { "code": null, "e": 4269, "s": 4113, "text": "The full dataset contains 10,0003 messages in the training dataset across 77 intents. The maximum and minimum category counts are 187 and 35, respectively." }, { "code": null, "e": 4417, "s": 4269, "text": "In order to more closely match the challenge I previously faced, I’ll randomly sample only 1,000 of the 10,000 total samples from the training set:" }, { "code": null, "e": 4472, "s": 4417, "text": "data_sample = data_full.sample(1000, random_state=123)" }, { "code": null, "e": 4972, "s": 4472, "text": "Note that while this dataset is useful for this exercise for demonstration purposes, this is still somewhat artificial and you’ll face additional challenges in a real-world setting. For example, you’ll first need to identify what message or sentence in a full dialogue sequence actually relates to the intent, as well as handle random system error messages, typos and nonsensical messages. This post on discovering and classifying AirBnB message intents touches on some of the real-world challenges." }, { "code": null, "e": 5218, "s": 4972, "text": "There are several ways to approach an unsupervised learning problem like this. Topic modeling was the first method that came to mind when confronted with this problem. It’s a technique used to discover latent topics in a collection of documents." }, { "code": null, "e": 6151, "s": 5218, "text": "Many algorithms can be used to perform topic modeling, but one very common one is Latent Dirichlet Allocation (LDA). LDA is a generative probabilistic model that assumes that each document is made up of a distribution of a fixed number of topics and each topic is made up of a distribution of words. A big challenge when trying to use LDA (and many other topic modeling algorithms) is deciding how many topics to actually use, which is a necessary model hyperparameter. Obviously, if that is what we’re hoping to get out of the analysis then this is a problem. Coherence is one way to assess the quality of the learned topics by measuring how similar the words are in each topic, and a higher coherence score is better. Gensim, a very popular library for topic modeling, makes it easy to calculate model coherence. Unfortunately, for the short texts we’re working with here, it isn’t obvious how many topics to pick using coherence:" }, { "code": null, "e": 6317, "s": 6151, "text": "It appears as though increasing the number of topics continues to increase the coherence for this dataset, giving us little guidance as to how many topics to choose." }, { "code": null, "e": 6433, "s": 6317, "text": "Adding to the challenges, topic models can be hard to interpret. For example, consider the identified topics below:" }, { "code": null, "e": 6623, "s": 6433, "text": "While some of the topics make sense, many are hard to interpret. This article series about work at Pew Research does a great job walking through the challenges of interpreting topic models." }, { "code": null, "e": 7394, "s": 6623, "text": "Ultimately, the biggest issue is that intents are more nuanced than topics. A limitation in LDA and other topic modeling approaches is that they treat the vocabulary in the documents as a bag of words, where the order doesn’t matter. This works well for longer documents (and a larger corpus), where identifying words that co-occur can provide a good picture of the topics. Additionally, there are often a relatively small number of topics, and the topics are fairly distinct. However, short-text intents create challenges, such as two phrases having nearly identical words but very different intents or having the same intent but almost no words in common. This severely limits the usefulness of standard topic modeling approaches for identifying intents in short text." }, { "code": null, "e": 7642, "s": 7394, "text": "Aside from topic modeling, clustering is another very common approach to unsupervised learning problems. In order to be able to cluster text data, we’ll need to make multiple decisions, including how to process the data and what algorithms to use." }, { "code": null, "e": 8344, "s": 7642, "text": "First, it is necessary to represent our text data numerically. One approach is to create embeddings, or vector representations, of each word to use for the clustering. This article gives a good overview of various ways of embedding words. Since each message consists of several words, one option is to then simply average the individual word embeddings of all the words in each message. This has worked well enough for some applications, but it would be better to directly calculate an embedding for the full sentences to more effectively take meaning into account. Especially given how short each message is, this will help avoid some of the pitfalls of the topic modeling algorithms described above." }, { "code": null, "e": 8836, "s": 8344, "text": "It turns out that there are many ways to find a single vector representation of a full message or sentence. This article gives a great overview of the various methods to achieve this. Google’s Universal Sentence Encoder (USE), first published by Cer et al in 2018, is a popular sentence embedding model. The USE model was trained on a variety of data, including Wikipedia, web news, web question-answer pages and discussion forums, and it performs well on sentence semantic similarity tasks." }, { "code": null, "e": 9224, "s": 8836, "text": "In 2019, Reimers and Gurevych published a paper introducing Sentence-BERT, a “modification of the pretrained BERT network that use siamese and triplet network structures to derive semantically meaningful sentence embeddings that can be compared using cosine-similarity”. They also released a Python implementation that makes it easy to download and use many different pre-trained models." }, { "code": null, "e": 9502, "s": 9224, "text": "Given how small our dataset is, using a pre-trained model is preferable here. For this analysis, I’ll compare the results of four pre-trained sentence embedding models: USE and three different sentence-BERT models (all-mpnet-base-v2, all-MiniLM-L6-v2 and all-distilroberta-v1)." }, { "code": null, "e": 9576, "s": 9502, "text": "Converting our messages into sentence embeddings is then straightforward:" }, { "code": null, "e": 10320, "s": 9576, "text": "As seen above, all of our sentence embeddings have high dimensionality (>500 features each). A manifestation of the Curse of Dimensionality is that distance measures, such as Euclidean and Manhattan, needed for clustering become meaningless at such high dimensions (see for example “On the Surprising Behavior of Distance Metrics in High Dimensional Space” by Aggarwal et al for more details). While some of the sentence-transformer pre-trained models were created in a way to preserve the usefulness of some distance measures, dimensionality reduction before clustering will greatly improve the results. (To prove this to myself, I briefly explored using different clustering algorithms and embeddings without dimensionality reduction first.)" }, { "code": null, "e": 10777, "s": 10320, "text": "Uniform Manifold Approximation and Projection for Dimension Reduction (UMAP), introduced by McInnes et al in 2020, has quickly grown in popularity as a dimensionality reduction technique. UMAP is much faster and more scalable than t-SNE, while also preserving the global structure of the data much better. This makes it useful for both visualization and as a preprocessing dimensionality reduction step to use before clustering. We’ll use it here for both." }, { "code": null, "e": 11608, "s": 10777, "text": "The Scikit-learn documentation has a helpful overview of the many different clustering algorithms it supports and when each performs best. For our current application, it is preferable to use an algorithm that does not require specifying the number of clusters upfront and can also tolerate noisy data. Density-based algorithms are a good option here as they do not require specifying the number of clusters and are indifferent to cluster shape. Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN) has become popular since it has fewer and more intuitive hyperparameters than DBSCAN and is robust to variable-density clusters. The HDBSCAN documentation provides a helpful comparison of different clustering algorithms. HDBSCAN worked best for the current problem, so we’ll focus on it for this post." }, { "code": null, "e": 12210, "s": 11608, "text": "There are at least two packages (and likely many more) already available to chain UMAP and HDBSCAN together for the purposes of topic modeling: Top2Vec (github and paper) and BERTopic (github and article). However, the default hyperparameters used in both packages do not work well for problems like the current one with short text and a small corpus (most of the data ends up being classified as noise and only three clusters total are found). To make it easier to tailor to our current problem of intent extraction, we’ll instead directly use the UMAP and HDBSCAN packages for hyperparameter tuning." }, { "code": null, "e": 13252, "s": 12210, "text": "UMAP has several hyperparameters that control how it performs dimensionality reduction, but two of the most important are n_neighbors and n_components. The n_neighbors parameter controls how UMAP balances local versus global structure in the data. This parameter controls the size of the neighborhood UMAP looks to learn the manifold structure, and so lower values of n_neighbors will focus more on the very local structure. The n_components parameter controls the dimensionality of the final embedded data after performing dimensionality reduction on the input data. Unfortunately, there is no obvious way to pick the best UMAP parameters by itself without ground truth labels. Here we do have the labels, which we’ll use at the end to determine how well we did. But the point of this work is to identify a methodology to use when we have unlabeled data. In Angelov’s Top2Vec paper he mentions that n_neighbors = 15 and n_components = 5 worked best for his downstream tasks, but it is unlikely this would always be the case for any dataset." }, { "code": null, "e": 14062, "s": 13252, "text": "HDBSCAN also has several important hyperparameters, but the most important one to consider is min_cluster_size. Intuitively, this controls the smallest grouping you want to consider as a cluster. In addition, the min_samples parameter, which defaults to being equal to min_cluster_size if unspecified, controls how conservative the clustering is. The larger it is, the more points are discarded as noise/outliers. Decoupling the two hyperparameters and having a smaller min_samples than min_cluster_size will essentially keep points that would have been labeled as outliers by merging them with their most similar neighboring clusters. This isn’t exactly what we want to happen if we’re trying to uncover the number of clusters. Thus, here I’ll only consider directly modifying the min_cluster_size parameter:" }, { "code": null, "e": 14308, "s": 14062, "text": "Note that UMAP is a stochastic algorithm, using randomness to speed up approximation steps and perform the optimization. Thus, we’ll set the random seed state to a constant value to get consistent results for a given set of UMAP hyperparameters." }, { "code": null, "e": 15075, "s": 14308, "text": "We now have a pipeline with three hyperparameters (n_neighbors, n_components, and min_cluster_size) that we want to tune. Next, we need to decide how to actually evaluate our clusters to select the best hyperparameters. Although commonly used with various clustering algorithms, Silhouette Score is not a good validation metric for density-based algorithms like DBSCAN and HDBSCAN since it assumes all points are assigned a group and can’t appropriately handle noise/outliers. Density Based Cluster Validation (DBCV) has been proposed and used by some for tuning HDBSCAN hyperparameters. While it likely works well for several applications, for this current problem it favored having a smaller number of clusters and leaving too many samples in the “noise” category." }, { "code": null, "e": 15177, "s": 15075, "text": "Instead, we’ll leverage the useful probabilities_ HDBSCAN attribute, which from the documentation is:" }, { "code": null, "e": 15395, "s": 15177, "text": "The strength with which each sample is a member of its assigned cluster. Noise points have probability zero; points in clusters have values assigned proportional to the degree that they persist as part of the cluster." }, { "code": null, "e": 15541, "s": 15395, "text": "This article by Nikolay Oskolkov provides a very intuitive and logical solution of simply defining our cost function that we want to minimize as:" }, { "code": null, "e": 15602, "s": 15541, "text": "Cost = percent of dataset with < 5% cluster label confidence" }, { "code": null, "e": 15857, "s": 15602, "text": "This will help ensure that we assign as many data points as we can to actual clusters instead of labeling them as noise. But what’s stopping us from setting the hyperparameters to make every individual point a “cluster”, or just making one giant cluster?" }, { "code": null, "e": 16121, "s": 15857, "text": "Here we have to use some domain knowledge to apply constraints. For this problem, based on my experience with this kind of data, I expected there to be at least 30 labels, but no more than 100. So our objective function becomes a constrained optimization problem:" }, { "code": null, "e": 16248, "s": 16121, "text": "minimize(Cost = percent of dataset with < 5% cluster label confidence)Subject to: 30 < num_clusters < 100" }, { "code": null, "e": 16735, "s": 16248, "text": "With the current dataset size of only 1,000 samples, it still takes about 3 seconds to generate the clusters and score them for a given set of inputs. Attempting to do a full grid search of, for example, a 10 x 10 x 10 hyperparameter search space would take almost an hour. Larger dataset sizes would take even longer. I care about finding the right hyperparameters, but not that much. Performing a random search instead of a full grid search is a pretty effective alternative strategy:" }, { "code": null, "e": 16810, "s": 16735, "text": "Running the search for 100 randomly-selected hyperparameter values yields:" }, { "code": null, "e": 17104, "s": 16810, "text": "We see that the runs with the lowest cost also have less than 10 clusters total. The first entry with a number of clusters between 30 and 100 has 59 clusters and a cost of 0.140 (i.e. about 14% of the data was labeled as outliers or low confidence). It only took 6 minutes to run too. Not bad." }, { "code": null, "e": 17384, "s": 17104, "text": "Randomly searching the hyperparameter space works reasonably well, but there is a better option: Bayesian optimization. Here we’ll leverage the popular hyperopt package to do so. If you’re unfamiliar with hyperopt and Bayesian optimization, this article provides a good overview." }, { "code": null, "e": 17606, "s": 17384, "text": "First, define the objective function that we want to minimize. The optimization constraints are included within the objective function by adding a penalty term if the number of clusters falls outside of the desired range:" }, { "code": null, "e": 17740, "s": 17606, "text": "Then minimize the objective function over the hyperparameter search space using the Tree-structured Parzen Estimator (TPE) algorithm:" }, { "code": null, "e": 17869, "s": 17740, "text": "Running the Bayesian search with 100 max evaluations over our parameter space yields slightly better results than random search:" }, { "code": null, "e": 17953, "s": 17869, "text": "It’s then easy to run the pipeline using embeddings from multiple different models:" }, { "code": null, "e": 18490, "s": 17953, "text": "At this point we could do a few more things, like visualize the clusters or manually inspect some of them to make sure they make sense. But ultimately we’re trying to find the “best” clustering results from the best analysis pipeline. If we trust our loss function, then it makes sense to pick the configuration with the lowest loss. Of the combinations tried above, it seems that we should go with sentence-transformer #1 (all-mpnet-base-v2), which generated 55 clusters using n_neighbors = 6, n_comonents= 9, and min_cluster_size = 6." }, { "code": null, "e": 18707, "s": 18490, "text": "In this case, we happen to also know the ground truth labels so we can see how well our loss function correlates with performance. We can manually inspect how well the models did on some of the ground truth clusters:" }, { "code": null, "e": 18999, "s": 18707, "text": "As shown above, all models seem to do relatively well on placing most of messages in the card_about_to_expire ground-truth group in the same clusters. At least for this category, the first sentence-transformer model seems to stand out in correctly assigning all messages to the same cluster." }, { "code": null, "e": 19393, "s": 18999, "text": "Rather than manually inspecting all groups, we can also quantitatively assess the model performances. Two commonly-used metrics for evaluating text clustering are the Normalized Mutual Information and Adjusted Rand Index. Both metrics have values ranging from 0 to 1, where larger is better. Calculating these metrics for the best hyperparameters of the four models under consideration yields:" }, { "code": null, "e": 19786, "s": 19393, "text": "In agreement with our previous conclusion, sentence-transformer #1 does in fact perform the best, with an ARI of 0.46 and an NMI of 0.81. However, the performance ordering for some of the other models do not follow the order expected from their cost function values. Thus, our scoring method for hyperparameter tuning isn’t perfect, but it is clearly still useful for the current application." }, { "code": null, "e": 20415, "s": 19786, "text": "To make the results even more helpful, we can also automatically apply descriptive labels to the clusters we found. A paper by Liu et al provides an interesting approach to doing this by extracting the most common action-object pair from the phrases in each cluster as the cluster label (e.g. “book-flight”). The bank77 dataset we’re considering here is a little more complicated than the dataset in that paper, but we can do something similar. Here we’ll concatenate the most common verb, direct object, and top two nouns from each cluster. The spaCy package has a powerful syntactic dependency parser that we can use for this:" }, { "code": null, "e": 20488, "s": 20415, "text": "We can write a simple function to extract these labels for each cluster:" }, { "code": null, "e": 20585, "s": 20488, "text": "Applying these labels to each of the clusters that our best model found yields our final result:" }, { "code": null, "e": 20702, "s": 20585, "text": "Using our tuning method, we’ve automatically extracted and applied descriptive labels to 55 clusters in our dataset." }, { "code": null, "e": 20874, "s": 20702, "text": "Since in this case we know the ground truth labels for each document, we can also inspect a few documents to see how well our derived labels match the ground truth labels:" }, { "code": null, "e": 20966, "s": 20874, "text": "They aren’t perfect, but the extracted labels match the ground category labels pretty well!" }, { "code": null, "e": 21508, "s": 20966, "text": "In this post, I outlined a framework for leveraging domain knowledge to create a constrained optimization problem to automatically tune UMAP and HDBSCAN hyperparameters. This allows us to easily cluster short-text documents and apply descriptive labels. The focus for this article was on a small dataset, but the same method can be applied to larger datasets as well. The clustering results provide helpful insights of unlabeled text data in a very short amount of time, before deciding or needing to complete time-intensive manual labeling." }, { "code": null, "e": 21656, "s": 21508, "text": "All code examples from this article, along with the chatintents python package I created to make applying these concepts easier, can be found here:" }, { "code": null, "e": 21667, "s": 21656, "text": "github.com" } ]
JDBC - Transactions
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion. That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions − To increase performance. To increase performance. To maintain the integrity of business processes. To maintain the integrity of business processes. To use distributed transactions. To use distributed transactions. Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails. To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again. For example, if you have a Connection object named conn, code the following to turn off auto-commit − conn.setAutoCommit(false); Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows − conn.commit( ); Otherwise, to roll back updates to the database made using the Connection named conn, use the following code − conn.rollback( ); The following example illustrates the use of a commit and rollback object − try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')"; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Singh')"; stmt.executeUpdate(SQL); // If there is no error. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(); } In this case, none of the above INSERT statement would success and everything would be rolled back. For a better understanding, let us study the Commit - Example Code. The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS, support savepoints within their environments such as Oracle's PL/SQL. When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint. The Connection object has two new methods that help you manage savepoints − setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object. setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object. releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method. releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method. There is one rollback (String savepointName) method, which rolls back work to the specified savepoint. The following example illustrates the use of a Savepoint object − try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); //set a Savepoint Savepoint savepoint1 = conn.setSavepoint("Savepoint1"); String SQL = "INSERT INTO Employees " + "VALUES (106, 20, 'Rita', 'Tez')"; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Sita', 'Tez')"; stmt.executeUpdate(SQL); // If there is no error, commit the changes. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(savepoint1); } In this case, none of the above INSERT statement would success and everything would be rolled back. For a better understanding, let us study the Savepoints - Example Code. 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": 2309, "s": 2162, "text": "If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion." }, { "code": null, "e": 2459, "s": 2309, "text": "That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-commit and manage your own transactions −" }, { "code": null, "e": 2484, "s": 2459, "text": "To increase performance." }, { "code": null, "e": 2509, "s": 2484, "text": "To increase performance." }, { "code": null, "e": 2558, "s": 2509, "text": "To maintain the integrity of business processes." }, { "code": null, "e": 2607, "s": 2558, "text": "To maintain the integrity of business processes." }, { "code": null, "e": 2640, "s": 2607, "text": "To use distributed transactions." }, { "code": null, "e": 2673, "s": 2640, "text": "To use distributed transactions." }, { "code": null, "e": 2899, "s": 2673, "text": "Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails." }, { "code": null, "e": 3188, "s": 2899, "text": "To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again." }, { "code": null, "e": 3290, "s": 3188, "text": "For example, if you have a Connection object named conn, code the following to turn off auto-commit −" }, { "code": null, "e": 3317, "s": 3290, "text": "conn.setAutoCommit(false);" }, { "code": null, "e": 3448, "s": 3317, "text": "Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows −" }, { "code": null, "e": 3464, "s": 3448, "text": "conn.commit( );" }, { "code": null, "e": 3575, "s": 3464, "text": "Otherwise, to roll back updates to the database made using the Connection named conn, use the following code −" }, { "code": null, "e": 3593, "s": 3575, "text": "conn.rollback( );" }, { "code": null, "e": 3669, "s": 3593, "text": "The following example illustrates the use of a commit and rollback object −" }, { "code": null, "e": 4217, "s": 3669, "text": "try{\n //Assume a valid connection object conn\n conn.setAutoCommit(false);\n Statement stmt = conn.createStatement();\n \n String SQL = \"INSERT INTO Employees \" +\n \"VALUES (106, 20, 'Rita', 'Tez')\";\n stmt.executeUpdate(SQL); \n //Submit a malformed SQL statement that breaks\n String SQL = \"INSERTED IN Employees \" +\n \"VALUES (107, 22, 'Sita', 'Singh')\";\n stmt.executeUpdate(SQL);\n // If there is no error.\n conn.commit();\n}catch(SQLException se){\n // If there is any error.\n conn.rollback();\n}" }, { "code": null, "e": 4317, "s": 4217, "text": "In this case, none of the above INSERT statement would success and everything would be rolled back." }, { "code": null, "e": 4385, "s": 4317, "text": "For a better understanding, let us study the Commit - Example Code." }, { "code": null, "e": 4558, "s": 4385, "text": "The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern DBMS, support savepoints within their environments such as Oracle's PL/SQL." }, { "code": null, "e": 4787, "s": 4558, "text": "When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint." }, { "code": null, "e": 4863, "s": 4787, "text": "The Connection object has two new methods that help you manage savepoints −" }, { "code": null, "e": 4961, "s": 4863, "text": "setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object." }, { "code": null, "e": 5059, "s": 4961, "text": "setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object." }, { "code": null, "e": 5258, "s": 5059, "text": "releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method." }, { "code": null, "e": 5457, "s": 5258, "text": "releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint object as a parameter. This object is usually a savepoint generated by the setSavepoint() method." }, { "code": null, "e": 5560, "s": 5457, "text": "There is one rollback (String savepointName) method, which rolls back work to the specified savepoint." }, { "code": null, "e": 5626, "s": 5560, "text": "The following example illustrates the use of a Savepoint object −" }, { "code": null, "e": 6281, "s": 5626, "text": "try{\n //Assume a valid connection object conn\n conn.setAutoCommit(false);\n Statement stmt = conn.createStatement();\n \n //set a Savepoint\n Savepoint savepoint1 = conn.setSavepoint(\"Savepoint1\");\n String SQL = \"INSERT INTO Employees \" +\n \"VALUES (106, 20, 'Rita', 'Tez')\";\n stmt.executeUpdate(SQL); \n //Submit a malformed SQL statement that breaks\n String SQL = \"INSERTED IN Employees \" +\n \"VALUES (107, 22, 'Sita', 'Tez')\";\n stmt.executeUpdate(SQL);\n // If there is no error, commit the changes.\n conn.commit();\n\n}catch(SQLException se){\n // If there is any error.\n conn.rollback(savepoint1);\n}" }, { "code": null, "e": 6381, "s": 6281, "text": "In this case, none of the above INSERT statement would success and everything would be rolled back." }, { "code": null, "e": 6453, "s": 6381, "text": "For a better understanding, let us study the Savepoints - Example Code." }, { "code": null, "e": 6486, "s": 6453, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6502, "s": 6486, "text": " Malhar Lathkar" }, { "code": null, "e": 6535, "s": 6502, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6551, "s": 6535, "text": " Malhar Lathkar" }, { "code": null, "e": 6586, "s": 6551, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6600, "s": 6586, "text": " Anadi Sharma" }, { "code": null, "e": 6634, "s": 6600, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6648, "s": 6634, "text": " Tushar Kale" }, { "code": null, "e": 6685, "s": 6648, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6700, "s": 6685, "text": " Monica Mittal" }, { "code": null, "e": 6733, "s": 6700, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6752, "s": 6733, "text": " Arnab Chakraborty" }, { "code": null, "e": 6759, "s": 6752, "text": " Print" }, { "code": null, "e": 6770, "s": 6759, "text": " Add Notes" } ]
PHP | hash_pbkdf2() Function - GeeksforGeeks
29 Oct, 2018 The hash_pbkdf2() function is an inbuilt function in PHP which is used to generate a PBKDF2 key derivation of a supplied password. Syntax: string hash_pbkdf2( $algo, $pass, $salt, $itr, $len, $raw_opt ) Parameters: This function accept six parameters as mention above and describe below. $algo: It is the required parameter which specifies the selected hashing algorithm (like- “md5”, “sha256”, “sha1”). $pass: This parameter is used to specify the password to use for the derivation. $salt: This parameter is used for the derivation and the value should be generated randomly. $itr: This parameter count the number of internal iterations. $len: This parameter is used to hold the length of the output string. $raw_opt: If this parameter set to True then its output will be raw binary data and if this parameter set to false then output will be lowercase hexits. Return Value: This function returns the string containing the calculated message digest as lowercase hexits. Below programs illustrate the hash_pbkdf2() function in PHP:Program 1: <?php$gfg = "GeeksforGeeks";$iterations = 142; // Generate a random IV using // openssl_random_pseudo_bytes()// random_bytes() or another // suitable source of randomness.$salt = openssl_random_pseudo_bytes(16); // Using hash_pbkdf2 function$hash = hash_pbkdf2("md5", $gfg, $salt, $iterations, 30); // Display resultecho $hash;?> f0ebbbf59869d76f946c4b15340761 Program 2: <?php$gfg = "Contribute1234";$iterations = 100; // Generate a random IV using // openssl_random_pseudo_bytes()// random_bytes() or another // suitable source of randomness.$salt = openssl_random_pseudo_bytes(8); // Using hash_pbkdf2 function$hash = hash_pbkdf2("md5", $gfg, $salt, $iterations, 20, false); // Display resultecho $hash;?> 715b385158045923923c Reference: http://php.net/manual/en/function.hash-pbkdf2.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel 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?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n29 Oct, 2018" }, { "code": null, "e": 24712, "s": 24581, "text": "The hash_pbkdf2() function is an inbuilt function in PHP which is used to generate a PBKDF2 key derivation of a supplied password." }, { "code": null, "e": 24720, "s": 24712, "text": "Syntax:" }, { "code": null, "e": 24784, "s": 24720, "text": "string hash_pbkdf2( $algo, $pass, $salt, $itr, $len, $raw_opt )" }, { "code": null, "e": 24869, "s": 24784, "text": "Parameters: This function accept six parameters as mention above and describe below." }, { "code": null, "e": 24985, "s": 24869, "text": "$algo: It is the required parameter which specifies the selected hashing algorithm (like- “md5”, “sha256”, “sha1”)." }, { "code": null, "e": 25066, "s": 24985, "text": "$pass: This parameter is used to specify the password to use for the derivation." }, { "code": null, "e": 25159, "s": 25066, "text": "$salt: This parameter is used for the derivation and the value should be generated randomly." }, { "code": null, "e": 25221, "s": 25159, "text": "$itr: This parameter count the number of internal iterations." }, { "code": null, "e": 25291, "s": 25221, "text": "$len: This parameter is used to hold the length of the output string." }, { "code": null, "e": 25444, "s": 25291, "text": "$raw_opt: If this parameter set to True then its output will be raw binary data and if this parameter set to false then output will be lowercase hexits." }, { "code": null, "e": 25553, "s": 25444, "text": "Return Value: This function returns the string containing the calculated message digest as lowercase hexits." }, { "code": null, "e": 25624, "s": 25553, "text": "Below programs illustrate the hash_pbkdf2() function in PHP:Program 1:" }, { "code": "<?php$gfg = \"GeeksforGeeks\";$iterations = 142; // Generate a random IV using // openssl_random_pseudo_bytes()// random_bytes() or another // suitable source of randomness.$salt = openssl_random_pseudo_bytes(16); // Using hash_pbkdf2 function$hash = hash_pbkdf2(\"md5\", $gfg, $salt, $iterations, 30); // Display resultecho $hash;?>", "e": 25960, "s": 25624, "text": null }, { "code": null, "e": 25992, "s": 25960, "text": "f0ebbbf59869d76f946c4b15340761\n" }, { "code": null, "e": 26003, "s": 25992, "text": "Program 2:" }, { "code": "<?php$gfg = \"Contribute1234\";$iterations = 100; // Generate a random IV using // openssl_random_pseudo_bytes()// random_bytes() or another // suitable source of randomness.$salt = openssl_random_pseudo_bytes(8); // Using hash_pbkdf2 function$hash = hash_pbkdf2(\"md5\", $gfg, $salt, $iterations, 20, false); // Display resultecho $hash;?>", "e": 26346, "s": 26003, "text": null }, { "code": null, "e": 26368, "s": 26346, "text": "715b385158045923923c\n" }, { "code": null, "e": 26429, "s": 26368, "text": "Reference: http://php.net/manual/en/function.hash-pbkdf2.php" }, { "code": null, "e": 26442, "s": 26429, "text": "PHP-function" }, { "code": null, "e": 26446, "s": 26442, "text": "PHP" }, { "code": null, "e": 26463, "s": 26446, "text": "Web Technologies" }, { "code": null, "e": 26467, "s": 26463, "text": "PHP" }, { "code": null, "e": 26565, "s": 26467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26574, "s": 26565, "text": "Comments" }, { "code": null, "e": 26587, "s": 26574, "text": "Old Comments" }, { "code": null, "e": 26669, "s": 26587, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26733, "s": 26669, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 26807, "s": 26733, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 26849, "s": 26807, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26900, "s": 26849, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 26956, "s": 26900, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26989, "s": 26956, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27051, "s": 26989, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27094, "s": 27051, "text": "How to fetch data from an API in ReactJS ?" } ]
Using Bayesian Classifiers to detect Fake News | by Victor Sim | Towards Data Science
There is so much fake news in circulation, it is difficult to find sources of accurate and unfabricated news. This article aims to use the Naive Bayes Classifier to classify real and fake news. The Naive Bayes Classifier is a deterministic algorithm that uses the Bayes theorem to classify data. Let’s look at an example: Suppose that you wanted to predict the probability that it would rain today: In the last few days, you have collected data by looking at the clouds in the sky. Here is the table of your data: This table represents the number of times a certain feature appears, given that it rained or it didn’t. What we have is actually a table containing the probability of it raining, given that grey clouds or white clouds appeared. Now armed with data, let’s make a prediction. Today we have seen grey clouds and no white clouds, is it more likely for it to be a rainy day or a sunny day? To answer this question, we have to use Bayes Theorem: This theorem uses past data to make better decisions. The probability of raining given that grey clouds appeared is equal to the probability that it rained, given that there were grey clouds, multiplied by the probability of it raining, divided the probability of grey clouds appearing. Based on our data: P(B|A) (Probability of raining, given grey clouds) = 10/11 P(A) (Probability of raining) = 11/50+11 = 11/66 = 1/6 P(B) (Probability of grey clouds) = 1 (Grey clouds have confirmed to have appeared) P(A|B) = P(B|A) * P(A) / P(B) P(A|B) = 10/11 * 1/6 / 1 P(A|B) = 10/66 This is our result! Given that grey clouds appeared, the probability that it will rain is 10/66, that is, in 66 different probabilities in which the scenarios are the same, in 10 of them it will rain. With that brief introduction to Naive Bayes Classifiers, let’s talk about fake news detection with Naive Bayes Classifiers. We will count the number of times a word appears in the headline, given that the news is fake. Change that to a probability, and then calculate the probability that the headline is fake, as compared to the headline being real. The dataset I used has over 21,000 instances of real news, and instances 23,000 of fake news. To a normal dataset, this might seem unbalanced, but this unbalance is necessary to calculate the initial probability: that is the probability of a headline being fake, without considering what it is. You can contact me for the dataset at victorwtsim@gmail.com. import pandas as pdimport string These are the three dependencies for the program: pandas is to read the csv file and string is to manipulate the casing of the words. true_text = {}fake_text = {}true = pd.read_csv('/Users/XXXXXXXX/Desktop/True.csv')fake = pd.read_csv('/Users/XXXXXXXX/Desktop/Fake.csv') This script is to read the two datasets, containing the instances of fake and true news. def extract_words(category,dictionary): for entry in category['title']: words = entry.split() for word in words: lower_word = word.lower() if word in dictionary: dictionary[lower_word] += 1 else: dictionary[lower_word] = 1 return dictionary This script counts how many times a word appears, given that the headline is of fake news, and adds one count to its entry into the dictionary that counts how many times each word appears. def count_to_prob(dictionary,length): for term in dictionary: dictionary[term] = dictionary[term]/length return dictionary This function changes the number into a probability, by calculating the total number of words for fake news headlines, or real news headlines. def calculate_probability(dictionary,X,initial): X.translate(str.maketrans('', '', string.punctuation)) X = X.lower() split = X.split() probability = initial for term in split: if term in dictionary: probability *= dictionary[term] print(term,dictionary[term]) return probability This function multiplies the relevant probabilites, to compute a “score” for the headline. To make the prediction, compare the score when using the fake news and real news dictionary. If the fake news dictionary returns a higher score, the model has predicted the headline to be fake news. true_text = extract_words(true,true_text)fake_text = extract_words(fake,fake_text)true_count = count_total(true_text)fake_count = count_total(fake_text)true_text = count_to_prob(true_text,true_count)fake_text = count_to_prob(fake_text,fake_count)total_count = true_count + fake_countfake_initial = fake_count/total_counttrue_initial = true_count/total_count This script uses all the above functions to create a dictionary of probabilities for each word, to later calculate the “score” for the headline. X = 'Hillary Clinton eats Donald Trump'calculate_probability(fake_text,X,1)>calculate_probability(true_text,X,1) This final script evaluates the headline: “Hillary Clinton eats Donald Trump”, to test the model. True The model outputs True, as the headline is obviously fake news. I created this program as a framework, so that others could improve upon it. Here are a few things you could consider: Consider phrases, as well as words A word itself has no meaning, but a phrase could give more insight into if the news is fake Gain a larger dataset, by web scraping There are plenty of sources of real news and fake news online, you just need to find it.
[ { "code": null, "e": 365, "s": 171, "text": "There is so much fake news in circulation, it is difficult to find sources of accurate and unfabricated news. This article aims to use the Naive Bayes Classifier to classify real and fake news." }, { "code": null, "e": 493, "s": 365, "text": "The Naive Bayes Classifier is a deterministic algorithm that uses the Bayes theorem to classify data. Let’s look at an example:" }, { "code": null, "e": 685, "s": 493, "text": "Suppose that you wanted to predict the probability that it would rain today: In the last few days, you have collected data by looking at the clouds in the sky. Here is the table of your data:" }, { "code": null, "e": 913, "s": 685, "text": "This table represents the number of times a certain feature appears, given that it rained or it didn’t. What we have is actually a table containing the probability of it raining, given that grey clouds or white clouds appeared." }, { "code": null, "e": 1125, "s": 913, "text": "Now armed with data, let’s make a prediction. Today we have seen grey clouds and no white clouds, is it more likely for it to be a rainy day or a sunny day? To answer this question, we have to use Bayes Theorem:" }, { "code": null, "e": 1179, "s": 1125, "text": "This theorem uses past data to make better decisions." }, { "code": null, "e": 1412, "s": 1179, "text": "The probability of raining given that grey clouds appeared is equal to the probability that it rained, given that there were grey clouds, multiplied by the probability of it raining, divided the probability of grey clouds appearing." }, { "code": null, "e": 1431, "s": 1412, "text": "Based on our data:" }, { "code": null, "e": 1490, "s": 1431, "text": "P(B|A) (Probability of raining, given grey clouds) = 10/11" }, { "code": null, "e": 1545, "s": 1490, "text": "P(A) (Probability of raining) = 11/50+11 = 11/66 = 1/6" }, { "code": null, "e": 1629, "s": 1545, "text": "P(B) (Probability of grey clouds) = 1 (Grey clouds have confirmed to have appeared)" }, { "code": null, "e": 1659, "s": 1629, "text": "P(A|B) = P(B|A) * P(A) / P(B)" }, { "code": null, "e": 1684, "s": 1659, "text": "P(A|B) = 10/11 * 1/6 / 1" }, { "code": null, "e": 1699, "s": 1684, "text": "P(A|B) = 10/66" }, { "code": null, "e": 1900, "s": 1699, "text": "This is our result! Given that grey clouds appeared, the probability that it will rain is 10/66, that is, in 66 different probabilities in which the scenarios are the same, in 10 of them it will rain." }, { "code": null, "e": 2024, "s": 1900, "text": "With that brief introduction to Naive Bayes Classifiers, let’s talk about fake news detection with Naive Bayes Classifiers." }, { "code": null, "e": 2251, "s": 2024, "text": "We will count the number of times a word appears in the headline, given that the news is fake. Change that to a probability, and then calculate the probability that the headline is fake, as compared to the headline being real." }, { "code": null, "e": 2607, "s": 2251, "text": "The dataset I used has over 21,000 instances of real news, and instances 23,000 of fake news. To a normal dataset, this might seem unbalanced, but this unbalance is necessary to calculate the initial probability: that is the probability of a headline being fake, without considering what it is. You can contact me for the dataset at victorwtsim@gmail.com." }, { "code": null, "e": 2640, "s": 2607, "text": "import pandas as pdimport string" }, { "code": null, "e": 2774, "s": 2640, "text": "These are the three dependencies for the program: pandas is to read the csv file and string is to manipulate the casing of the words." }, { "code": null, "e": 2911, "s": 2774, "text": "true_text = {}fake_text = {}true = pd.read_csv('/Users/XXXXXXXX/Desktop/True.csv')fake = pd.read_csv('/Users/XXXXXXXX/Desktop/Fake.csv')" }, { "code": null, "e": 3000, "s": 2911, "text": "This script is to read the two datasets, containing the instances of fake and true news." }, { "code": null, "e": 3324, "s": 3000, "text": "def extract_words(category,dictionary): for entry in category['title']: words = entry.split() for word in words: lower_word = word.lower() if word in dictionary: dictionary[lower_word] += 1 else: dictionary[lower_word] = 1 return dictionary" }, { "code": null, "e": 3513, "s": 3324, "text": "This script counts how many times a word appears, given that the headline is of fake news, and adds one count to its entry into the dictionary that counts how many times each word appears." }, { "code": null, "e": 3649, "s": 3513, "text": "def count_to_prob(dictionary,length): for term in dictionary: dictionary[term] = dictionary[term]/length return dictionary" }, { "code": null, "e": 3792, "s": 3649, "text": "This function changes the number into a probability, by calculating the total number of words for fake news headlines, or real news headlines." }, { "code": null, "e": 4119, "s": 3792, "text": "def calculate_probability(dictionary,X,initial): X.translate(str.maketrans('', '', string.punctuation)) X = X.lower() split = X.split() probability = initial for term in split: if term in dictionary: probability *= dictionary[term] print(term,dictionary[term]) return probability" }, { "code": null, "e": 4409, "s": 4119, "text": "This function multiplies the relevant probabilites, to compute a “score” for the headline. To make the prediction, compare the score when using the fake news and real news dictionary. If the fake news dictionary returns a higher score, the model has predicted the headline to be fake news." }, { "code": null, "e": 4767, "s": 4409, "text": "true_text = extract_words(true,true_text)fake_text = extract_words(fake,fake_text)true_count = count_total(true_text)fake_count = count_total(fake_text)true_text = count_to_prob(true_text,true_count)fake_text = count_to_prob(fake_text,fake_count)total_count = true_count + fake_countfake_initial = fake_count/total_counttrue_initial = true_count/total_count" }, { "code": null, "e": 4912, "s": 4767, "text": "This script uses all the above functions to create a dictionary of probabilities for each word, to later calculate the “score” for the headline." }, { "code": null, "e": 5025, "s": 4912, "text": "X = 'Hillary Clinton eats Donald Trump'calculate_probability(fake_text,X,1)>calculate_probability(true_text,X,1)" }, { "code": null, "e": 5123, "s": 5025, "text": "This final script evaluates the headline: “Hillary Clinton eats Donald Trump”, to test the model." }, { "code": null, "e": 5128, "s": 5123, "text": "True" }, { "code": null, "e": 5192, "s": 5128, "text": "The model outputs True, as the headline is obviously fake news." }, { "code": null, "e": 5311, "s": 5192, "text": "I created this program as a framework, so that others could improve upon it. Here are a few things you could consider:" }, { "code": null, "e": 5346, "s": 5311, "text": "Consider phrases, as well as words" }, { "code": null, "e": 5438, "s": 5346, "text": "A word itself has no meaning, but a phrase could give more insight into if the news is fake" }, { "code": null, "e": 5477, "s": 5438, "text": "Gain a larger dataset, by web scraping" } ]
Use this clustering method if you have many outliers | by Martin Helm | Towards Data Science
If you have ever wanted to segment your data into groups, you have probably tried the famous k-means algorithm for it. Since it is so simple, it is widely used, but its simplicity also comes with several drawbacks. One of them is its sensitivity to outliers, as it uses classic euclidean distance as the dissimilaritymetric. Unfortunately, real-world data sets often come with many outliers that you might not be able to remove completely during the data cleanup phase. If you have run into this problem, I want to introduce you to the k-medians algorithm. By using the median instead of the mean, and using a more robust dissimilarity metric, it is much less sensitive to outliers. In this article, I will show you the following: k-medians intuition Implementation from scratch in R As usual, you can also find all the code for this article on my GitHub. k-medians tries to alleviate the sensitivity of k-means to outliers by choosinga different dissimilarity metric. Instead of the euclidean distance, we typically use the absolute difference, which is also called the L1 norm or the Manhattan or Taxicab distance (Because you can use it to calculate the number of turns a taxi needs to take to reach its target in a rectangular grid of blocks). This is much less sensitive to outliers because these are only contributing withtheir actual distance to the center, instead of the square of the distance, as is the case for euclidean distance: But one could also use other metrics here, if they are more appropriate, such as the Kullback-Leibler divergence to compare distributions. To make it even more reliable, we also choose the median instead of the mean for the centers. So finally we need to optimize the following problem: The approach of k-medians is very similar to k-means, it is again Llodyd’salgorithm. To summarize it briefly: Input parameter k (number of clusters) and n_iter (number of iterations)Randomly initialize k objects in the data set as centersDo n_iter times: Assign each object to its closest center Calculate the new centers You can find a much more detailed explanation on Lloyds algorithm in my post on k-means: towardsdatascience.com If we look at the programmatic implementation, we recognize that is it not asubiquitously available as k-means. For example in R, there is no k-medians function available in the stats package. So let’s code it ourselves: Next, let’s see how our function performs on the common iris data set. We willcompare it also to the base R k-means implementation, to see where they might differ: For this data set we only observe minor differences between k-medians and k-means, but it also does not contain too many outliers to begin with. As you can see, it is really similar to k-means, we really only use a different distance function and use the median. One common misconception about k-medians is that the medians returned as centers always are actual points in the data set. This can be easily seen to not be true. Consider the following example cluster, consisting of 5 points: Because the median is calculated for each dimension separately in k-medians, the medians would be x = 3, and y = 3. But there exists no point (3, 3) in the data set. Finally, of course you could couple k-medians together with an improvedinitialization, like kmeans++, to make it even more robust. You can find thedetails how to do that from my article on it here: towardsdatascience.com See you next time, when we will discuss the most advanced variation of k-means, partitioning around medoids, concluding this mini-series.
[ { "code": null, "e": 496, "s": 171, "text": "If you have ever wanted to segment your data into groups, you have probably tried the famous k-means algorithm for it. Since it is so simple, it is widely used, but its simplicity also comes with several drawbacks. One of them is its sensitivity to outliers, as it uses classic euclidean distance as the dissimilaritymetric." }, { "code": null, "e": 854, "s": 496, "text": "Unfortunately, real-world data sets often come with many outliers that you might not be able to remove completely during the data cleanup phase. If you have run into this problem, I want to introduce you to the k-medians algorithm. By using the median instead of the mean, and using a more robust dissimilarity metric, it is much less sensitive to outliers." }, { "code": null, "e": 902, "s": 854, "text": "In this article, I will show you the following:" }, { "code": null, "e": 922, "s": 902, "text": "k-medians intuition" }, { "code": null, "e": 955, "s": 922, "text": "Implementation from scratch in R" }, { "code": null, "e": 1027, "s": 955, "text": "As usual, you can also find all the code for this article on my GitHub." }, { "code": null, "e": 1614, "s": 1027, "text": "k-medians tries to alleviate the sensitivity of k-means to outliers by choosinga different dissimilarity metric. Instead of the euclidean distance, we typically use the absolute difference, which is also called the L1 norm or the Manhattan or Taxicab distance (Because you can use it to calculate the number of turns a taxi needs to take to reach its target in a rectangular grid of blocks). This is much less sensitive to outliers because these are only contributing withtheir actual distance to the center, instead of the square of the distance, as is the case for euclidean distance:" }, { "code": null, "e": 1753, "s": 1614, "text": "But one could also use other metrics here, if they are more appropriate, such as the Kullback-Leibler divergence to compare distributions." }, { "code": null, "e": 1901, "s": 1753, "text": "To make it even more reliable, we also choose the median instead of the mean for the centers. So finally we need to optimize the following problem:" }, { "code": null, "e": 2011, "s": 1901, "text": "The approach of k-medians is very similar to k-means, it is again Llodyd’salgorithm. To summarize it briefly:" }, { "code": null, "e": 2226, "s": 2011, "text": "Input parameter k (number of clusters) and n_iter (number of iterations)Randomly initialize k objects in the data set as centersDo n_iter times: Assign each object to its closest center Calculate the new centers" }, { "code": null, "e": 2315, "s": 2226, "text": "You can find a much more detailed explanation on Lloyds algorithm in my post on k-means:" }, { "code": null, "e": 2338, "s": 2315, "text": "towardsdatascience.com" }, { "code": null, "e": 2559, "s": 2338, "text": "If we look at the programmatic implementation, we recognize that is it not asubiquitously available as k-means. For example in R, there is no k-medians function available in the stats package. So let’s code it ourselves:" }, { "code": null, "e": 2723, "s": 2559, "text": "Next, let’s see how our function performs on the common iris data set. We willcompare it also to the base R k-means implementation, to see where they might differ:" }, { "code": null, "e": 2868, "s": 2723, "text": "For this data set we only observe minor differences between k-medians and k-means, but it also does not contain too many outliers to begin with." }, { "code": null, "e": 2986, "s": 2868, "text": "As you can see, it is really similar to k-means, we really only use a different distance function and use the median." }, { "code": null, "e": 3213, "s": 2986, "text": "One common misconception about k-medians is that the medians returned as centers always are actual points in the data set. This can be easily seen to not be true. Consider the following example cluster, consisting of 5 points:" }, { "code": null, "e": 3379, "s": 3213, "text": "Because the median is calculated for each dimension separately in k-medians, the medians would be x = 3, and y = 3. But there exists no point (3, 3) in the data set." }, { "code": null, "e": 3577, "s": 3379, "text": "Finally, of course you could couple k-medians together with an improvedinitialization, like kmeans++, to make it even more robust. You can find thedetails how to do that from my article on it here:" }, { "code": null, "e": 3600, "s": 3577, "text": "towardsdatascience.com" } ]
Java - FileReader Class
This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters. This class has several constructors to create required objects. Following is the list of constructors provided by the FileReader class. FileReader(File file) This constructor creates a new FileReader, given the File to read from. FileReader(FileDescriptor fd) This constructor creates a new FileReader, given the FileDescriptor to read from. FileReader(String fileName) This constructor creates a new FileReader, given the name of the file to read from. Once you have FileReader object in hand then there is a list of helper methods which can be used to manipulate the files. public int read() throws IOException Reads a single character. Returns an int, which represents the character read. public int read(char [] c, int offset, int len) Reads characters into an array. Returns the number of characters read. Following is an example to demonstrate class − import java.io.*; public class FileRead { public static void main(String args[])throws IOException { File file = new File("Hello1.txt"); // creates the file file.createNewFile(); // creates a FileWriter Object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This\n is\n an\n example\n"); writer.flush(); writer.close(); // Creates a FileReader Object FileReader fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one fr.close(); } } This will produce the following result − This is an example 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": 2485, "s": 2377, "text": "This class inherits from the InputStreamReader class. FileReader is used for reading streams of characters." }, { "code": null, "e": 2621, "s": 2485, "text": "This class has several constructors to create required objects. Following is the list of constructors provided by the FileReader class." }, { "code": null, "e": 2643, "s": 2621, "text": "FileReader(File file)" }, { "code": null, "e": 2715, "s": 2643, "text": "This constructor creates a new FileReader, given the File to read from." }, { "code": null, "e": 2745, "s": 2715, "text": "FileReader(FileDescriptor fd)" }, { "code": null, "e": 2827, "s": 2745, "text": "This constructor creates a new FileReader, given the FileDescriptor to read from." }, { "code": null, "e": 2855, "s": 2827, "text": "FileReader(String fileName)" }, { "code": null, "e": 2939, "s": 2855, "text": "This constructor creates a new FileReader, given the name of the file to read from." }, { "code": null, "e": 3061, "s": 2939, "text": "Once you have FileReader object in hand then there is a list of helper methods which can be used to manipulate the files." }, { "code": null, "e": 3098, "s": 3061, "text": "public int read() throws IOException" }, { "code": null, "e": 3177, "s": 3098, "text": "Reads a single character. Returns an int, which represents the character read." }, { "code": null, "e": 3225, "s": 3177, "text": "public int read(char [] c, int offset, int len)" }, { "code": null, "e": 3296, "s": 3225, "text": "Reads characters into an array. Returns the number of characters read." }, { "code": null, "e": 3343, "s": 3296, "text": "Following is an example to demonstrate class −" }, { "code": null, "e": 4077, "s": 3343, "text": "import java.io.*;\npublic class FileRead {\n\n public static void main(String args[])throws IOException {\n File file = new File(\"Hello1.txt\");\n \n // creates the file\n file.createNewFile();\n \n // creates a FileWriter Object\n FileWriter writer = new FileWriter(file); \n \n // Writes the content to the file\n writer.write(\"This\\n is\\n an\\n example\\n\"); \n writer.flush();\n writer.close();\n\n // Creates a FileReader Object\n FileReader fr = new FileReader(file); \n char [] a = new char[50];\n fr.read(a); // reads the content to the array\n \n for(char c : a)\n System.out.print(c); // prints the characters one by one\n fr.close();\n }\n}" }, { "code": null, "e": 4118, "s": 4077, "text": "This will produce the following result −" }, { "code": null, "e": 4138, "s": 4118, "text": "This\nis\nan\nexample\n" }, { "code": null, "e": 4171, "s": 4138, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4187, "s": 4171, "text": " Malhar Lathkar" }, { "code": null, "e": 4220, "s": 4187, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4236, "s": 4220, "text": " Malhar Lathkar" }, { "code": null, "e": 4271, "s": 4236, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4285, "s": 4271, "text": " Anadi Sharma" }, { "code": null, "e": 4319, "s": 4285, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4333, "s": 4319, "text": " Tushar Kale" }, { "code": null, "e": 4370, "s": 4333, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4385, "s": 4370, "text": " Monica Mittal" }, { "code": null, "e": 4418, "s": 4385, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4437, "s": 4418, "text": " Arnab Chakraborty" }, { "code": null, "e": 4444, "s": 4437, "text": " Print" }, { "code": null, "e": 4455, "s": 4444, "text": " Add Notes" } ]
How to return a Pointer from a Function in C - GeeksforGeeks
19 Aug, 2020 Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns. Program 1: The below program will give segmentation fault since ‘A’ was local to the function: C // C program to illustrate the concept of// returning pointer from a function#include <stdio.h> // Function returning pointerint* fun(){ int A = 10; return (&A);} // Driver Codeint main(){ // Declare a pointer int* p; // Function call p = fun(); printf("%p\n", p); printf("%d\n", *p); return 0;} The main reason behind this scenario is that compiler always make a stack for a function call. As soon as the function exits the function stack also gets removed which causes the local variables of functions goes out of scope. Static Variables have a property of preserving their value even after they are out of their scope. So to execute the concept of returning a pointer from function in C you must define the local variable as a static variable. Program 2: C // C program to illustrate the concept of// returning pointer from a function#include <stdio.h> // Function that returns pointerint* fun(){ // Declare a static integer static int A = 10; return (&A);} // Driver Codeint main(){ // Declare a pointer int* p; // Function call p = fun(); // Print Address printf("%p\n", p); // Print value at the above address printf("%d\n", *p); return 0;} 0x601038 10 C-Functions C-Pointers C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C Regular expressions in C How to store words in an array in C? Handling multiple clients on server with multithreading using Socket Programming in C/C++ Conditional wait and signal in multi-threading C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
[ { "code": null, "e": 24563, "s": 24535, "text": "\n19 Aug, 2020" }, { "code": null, "e": 24892, "s": 24563, "text": "Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns." }, { "code": null, "e": 24903, "s": 24892, "text": "Program 1:" }, { "code": null, "e": 24987, "s": 24903, "text": "The below program will give segmentation fault since ‘A’ was local to the function:" }, { "code": null, "e": 24989, "s": 24987, "text": "C" }, { "code": "// C program to illustrate the concept of// returning pointer from a function#include <stdio.h> // Function returning pointerint* fun(){ int A = 10; return (&A);} // Driver Codeint main(){ // Declare a pointer int* p; // Function call p = fun(); printf(\"%p\\n\", p); printf(\"%d\\n\", *p); return 0;}", "e": 25318, "s": 24989, "text": null }, { "code": null, "e": 25545, "s": 25318, "text": "The main reason behind this scenario is that compiler always make a stack for a function call. As soon as the function exits the function stack also gets removed which causes the local variables of functions goes out of scope." }, { "code": null, "e": 25769, "s": 25545, "text": "Static Variables have a property of preserving their value even after they are out of their scope. So to execute the concept of returning a pointer from function in C you must define the local variable as a static variable." }, { "code": null, "e": 25780, "s": 25769, "text": "Program 2:" }, { "code": null, "e": 25782, "s": 25780, "text": "C" }, { "code": "// C program to illustrate the concept of// returning pointer from a function#include <stdio.h> // Function that returns pointerint* fun(){ // Declare a static integer static int A = 10; return (&A);} // Driver Codeint main(){ // Declare a pointer int* p; // Function call p = fun(); // Print Address printf(\"%p\\n\", p); // Print value at the above address printf(\"%d\\n\", *p); return 0;}", "e": 26213, "s": 25782, "text": null }, { "code": null, "e": 26226, "s": 26213, "text": "0x601038\n10\n" }, { "code": null, "e": 26238, "s": 26226, "text": "C-Functions" }, { "code": null, "e": 26249, "s": 26238, "text": "C-Pointers" }, { "code": null, "e": 26260, "s": 26249, "text": "C Programs" }, { "code": null, "e": 26358, "s": 26260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26367, "s": 26358, "text": "Comments" }, { "code": null, "e": 26380, "s": 26367, "text": "Old Comments" }, { "code": null, "e": 26421, "s": 26380, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26452, "s": 26421, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26493, "s": 26452, "text": "C program to find the length of a string" }, { "code": null, "e": 26527, "s": 26493, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 26580, "s": 26527, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 26605, "s": 26580, "text": "Regular expressions in C" }, { "code": null, "e": 26642, "s": 26605, "text": "How to store words in an array in C?" }, { "code": null, "e": 26732, "s": 26642, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 26779, "s": 26732, "text": "Conditional wait and signal in multi-threading" } ]
CouchDB - Updating a Document
You can update a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to update a document. curl -X PUT http://127.0.0.1:5984/database_name/document_id/ -d '{ "field" : "value", "_rev" : "revision id" }' Suppose there is a document with id 001 in the database named my_database. You can delete this as shown below. First of all, get the revision id of the document that is to be updated. You can find the _rev of the document in the document itself, therefore get the document as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { "_id" : "001", "_rev" : "2-04d8eac1680d237ca25b68b36b8899d3 " , "age" : "23" } Use revision id _rev from the document to update the document. Here we are updating the age from 23 to 24. $ curl -X PUT http://127.0.0.1:5984/my_database/001/ -d ' { " age " : " 24 " , " _rev " : " 1-1c2fae390fa5475d9b809301bbf3f25e " } ' { " ok " : true , " id " : " 001 " , " rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " } To verify the document, get the document again using GET request as shown below. $ curl -X GET http://127.0.0.1:5984/my_database/001 { " _id " : " 001 ", " _rev " : " 2-04d8eac1680d237ca25b68b36b8899d3 " , " age " : " 23 " } Following are some important points to be noted while updating a document. The URL we send in the request containing the database name and the document id. The URL we send in the request containing the database name and the document id. Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID. Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID. We have to supply the revision number as a part of the JSON request. We have to supply the revision number as a part of the JSON request. In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number. In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number. To delete a document open the http://127.0.0.1:5984/_utils/ url to get an Overview/index page of CouchDB as shown below. Select the database in which the document to be updated exists and click it. Here we are updating a document in the database named tutorials_point. You will get the list of documents in the database as shown below. Select a document that you want to update and click on it. You will get the contents of the documents as shown below. Here, to update the location from Delhi to Hyderabad, click on the text box, edit the field, and click the green button to save the changes as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2001, "s": 1838, "text": "You can update a document in CouchDB by sending an HTTP request to the server using PUT method through cURL utility. Following is the syntax to update a document." }, { "code": null, "e": 2113, "s": 2001, "text": "curl -X PUT http://127.0.0.1:5984/database_name/document_id/ -d '{ \"field\" : \"value\", \"_rev\" : \"revision id\" }'" }, { "code": null, "e": 2224, "s": 2113, "text": "Suppose there is a document with id 001 in the database named my_database. You can delete this as shown below." }, { "code": null, "e": 2402, "s": 2224, "text": "First of all, get the revision id of the document that is to be updated. You can find the _rev of the document in the document itself, therefore get the document as shown below." }, { "code": null, "e": 2544, "s": 2402, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \"_id\" : \"001\",\n \"_rev\" : \"2-04d8eac1680d237ca25b68b36b8899d3 \" ,\n \"age\" : \"23\"\n}" }, { "code": null, "e": 2651, "s": 2544, "text": "Use revision id _rev from the document to update the document. Here we are updating the age from 23 to 24." }, { "code": null, "e": 2873, "s": 2651, "text": "$ curl -X PUT http://127.0.0.1:5984/my_database/001/ -d\n' { \" age \" : \" 24 \" , \" _rev \" : \" 1-1c2fae390fa5475d9b809301bbf3f25e \" } '\n\n{ \" ok \" : true , \" id \" : \" 001 \" , \" rev \" : \" 2-04d8eac1680d237ca25b68b36b8899d3 \" }" }, { "code": null, "e": 2954, "s": 2873, "text": "To verify the document, get the document again using GET request as shown below." }, { "code": null, "e": 3109, "s": 2954, "text": "$ curl -X GET http://127.0.0.1:5984/my_database/001\n{\n \" _id \" : \" 001 \",\n \" _rev \" : \" 2-04d8eac1680d237ca25b68b36b8899d3 \" ,\n \" age \" : \" 23 \"\n }\n" }, { "code": null, "e": 3184, "s": 3109, "text": "Following are some important points to be noted while updating a document." }, { "code": null, "e": 3265, "s": 3184, "text": "The URL we send in the request containing the database name and the document id." }, { "code": null, "e": 3346, "s": 3265, "text": "The URL we send in the request containing the database name and the document id." }, { "code": null, "e": 3569, "s": 3346, "text": "Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID." }, { "code": null, "e": 3792, "s": 3569, "text": "Updating an existing document is same as updating the entire document. You cannot add a field to an existing document. You can only write an entirely new version of the document into the database with the same document ID." }, { "code": null, "e": 3861, "s": 3792, "text": "We have to supply the revision number as a part of the JSON request." }, { "code": null, "e": 3930, "s": 3861, "text": "We have to supply the revision number as a part of the JSON request." }, { "code": null, "e": 4149, "s": 3930, "text": "In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number." }, { "code": null, "e": 4368, "s": 4149, "text": "In return JSON contains the success message, the ID of the document being updated, and the new revision information. If you want to update the new version of the document, you have to quote this latest revision number." }, { "code": null, "e": 4489, "s": 4368, "text": "To delete a document open the http://127.0.0.1:5984/_utils/ url to get an\nOverview/index page of CouchDB as shown below." }, { "code": null, "e": 4704, "s": 4489, "text": "Select the database in which the document to be updated exists and click it. Here we are updating a document in the database named tutorials_point. You will get the list of documents in the database as shown below." }, { "code": null, "e": 4822, "s": 4704, "text": "Select a document that you want to update and click on it. You will get the contents of the documents as shown below." }, { "code": null, "e": 4978, "s": 4822, "text": "Here, to update the location from Delhi to Hyderabad, click on the text box, edit the field, and click the green button to save the changes as shown below." }, { "code": null, "e": 4985, "s": 4978, "text": " Print" }, { "code": null, "e": 4996, "s": 4985, "text": " Add Notes" } ]
jQuery - Event Handling
Any modern web application can't be imagined without an event associated with it. Events are the mechanism to build an interactive web page. jQuery is smart enough to handle any event generated on an HTML page. First let's try to understand what is an event. A jQuery Event is the result of an action that can be detected by jQuery (JavaScript). When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers. The jQuery library provides methods to handle all the DOM events and make complete event handling considerably easier than in JavaScript. Following are the examples of events − A mouse click A web page loading Taking mouse over an element Submitting an HTML form A keystroke on your keyboard, etc. The following table lists some of the important DOM events. This chapter coveres only few event methods and properties, For a complete reference of all the jQuery event method and properties, you can go to through jQuery Event Reference. Consider a situation when you want to click a <div> in an HTML document and then you want to perform some action against this click. To achieve this you will have to bind a jQuery click event with the <div> elements and then define an action against the click event. Following is jQuery syntax to bind a click event with all the <div> elements: $("div").click(); The next step is to define an action against the click event. Following is the syntax to define a function which will be executed when click event will be fired. This function is called jQuery Event Handler $("div").click(function(){ // jQuery code goes here }); Following is another syntax to bind a click event with any of the DOM elements: $("div").bind('click', function(){ // jQuery code goes here }); Following is an example to bind a click event with <div> where an alert box is displayed whenever you click on any of the divs. Try to click the icon to run the following jQuery code: <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").click(function(){ alert('Hi there!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Let's re-write the above code to bind a dblclick event with <div> where an alert box is displayed whenever you double click on any of the divs. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").dblclick(function(){ alert('Hi there!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Double click on any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Following is an example to bind a mouseenter event with <div> where an alert box is displayed whenever you bring cursor over any of the divs. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").mouseenter(function(){ alert('Cursor is in!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Bring cursor over any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Following is an example to bind a mouseleave event with <div> where an alert box is displayed whenever you take cursor out of the div. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").mouseleave(function(){ alert('Curosr is out!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Take cursor out of any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Following is an example to bind a mousedown event with <div> where an alert box is displayed whenever the left, middle or right mouse button is pressed down over any of the divs. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").mousedown(function(){ alert('Mouse button is down!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Press mouse button down over any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Following is an example to bind a mouseup event with <div> where an alert box is displayed whenever the left, middle or right mouse button is released over any of the divs. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").mouseup(function(){ alert('Mouse button is released!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Release mouse button over any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function.The event object provides various useful information about the event. The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed. The following event properties/attributes are available and safe to access in a platform independent manner − altKey Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards. ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not. data The value, if any, passed as the second parameter to the bind() command when the handler was established. keyCode For keyup and keydown events, this returns the key that was pressed. metaKey Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs. pageX For mouse events, specifies the horizontal coordinate of the event relative from the page origin. pageY For mouse events, specifies the vertical coordinate of the event relative from the page origin. relatedTarget For some mouse events, identifies the element that the cursor left or entered when the event was triggered. screenX For mouse events, specifies the horizontal coordinate of the event relative from the screen origin. screenY For mouse events, specifies the vertical coordinate of the event relative from the screen origin. shiftKey Set to true if the Shift key was pressed when the event was triggered, false if not. target Identifies the element for which the event was triggered. timeStamp The timestamp (in milliseconds) when the event was created. type For all events, specifies the type of event that was triggered (for example, click). which For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right). Following is an example to show how different square clicks give different coordinates. <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").click(function(eventObj){ alert('Event type is ' + eventObj.type); alert('pageX : ' + eventObj.pageX); alert('pageY : ' + eventObj.pageY); alert('Target : ' + eventObj.target.innerHTML); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Many times it becomes very easy to make use of this keyword inside an event handler. This keyword represents a DOM element which triggers the event. Following example will show the content of the clicked <div>: <html> <head> <title>The jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { $("div").click(function(){ alert($(this).text()); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </body> </html> Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler. jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows − selector.unbind(eventType, handler) or selector.unbind(eventType) Following is the description of the parameters − eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types. eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types. handler − If provided, identifies the specific listener that's to be removed. handler − If provided, identifies the specific listener that's to be removed. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2581, "s": 2322, "text": "Any modern web application can't be imagined without an event associated with it. Events are the mechanism to build an interactive web page. jQuery is smart enough to handle any event generated on an HTML page. First let's try to understand what is an event." }, { "code": null, "e": 2832, "s": 2581, "text": "A jQuery Event is the result of an action that can be detected by jQuery (JavaScript). When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers." }, { "code": null, "e": 2970, "s": 2832, "text": "The jQuery library provides methods to handle all the DOM events and make complete event handling considerably easier than in JavaScript." }, { "code": null, "e": 3009, "s": 2970, "text": "Following are the examples of events −" }, { "code": null, "e": 3023, "s": 3009, "text": "A mouse click" }, { "code": null, "e": 3042, "s": 3023, "text": "A web page loading" }, { "code": null, "e": 3071, "s": 3042, "text": "Taking mouse over an element" }, { "code": null, "e": 3095, "s": 3071, "text": "Submitting an HTML form" }, { "code": null, "e": 3130, "s": 3095, "text": "A keystroke on your keyboard, etc." }, { "code": null, "e": 3190, "s": 3130, "text": "The following table lists some of the important DOM events." }, { "code": null, "e": 3370, "s": 3190, "text": "This chapter coveres only few event methods and properties, For a complete reference of all the jQuery event method and properties, you can go to through jQuery Event Reference. \n" }, { "code": null, "e": 3637, "s": 3370, "text": "Consider a situation when you want to click a <div> in an HTML document and then you want to perform some action against this click. To achieve this you will have to bind a jQuery click event with the <div> elements and then define an action against the click event." }, { "code": null, "e": 3715, "s": 3637, "text": "Following is jQuery syntax to bind a click event with all the <div> elements:" }, { "code": null, "e": 3734, "s": 3715, "text": "$(\"div\").click();\n" }, { "code": null, "e": 3941, "s": 3734, "text": "The next step is to define an action against the click event. Following is the syntax to define a function which will be executed when click event will be fired. This function is called jQuery Event Handler" }, { "code": null, "e": 4001, "s": 3941, "text": "$(\"div\").click(function(){\n // jQuery code goes here\n});\n" }, { "code": null, "e": 4081, "s": 4001, "text": "Following is another syntax to bind a click event with any of the DOM elements:" }, { "code": null, "e": 4149, "s": 4081, "text": "$(\"div\").bind('click', function(){\n // jQuery code goes here\n});\n" }, { "code": null, "e": 4334, "s": 4149, "text": "Following is an example to bind a click event with <div> where an alert box is displayed whenever you click on any of the divs. Try to click the icon to run the following jQuery code:" }, { "code": null, "e": 5118, "s": 4334, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").click(function(){\n alert('Hi there!');\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 5262, "s": 5118, "text": "Let's re-write the above code to bind a dblclick event with <div> where an alert box is displayed whenever you double click on any of the divs." }, { "code": null, "e": 6056, "s": 5262, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").dblclick(function(){\n alert('Hi there!');\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Double click on any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 6198, "s": 6056, "text": "Following is an example to bind a mouseenter event with <div> where an alert box is displayed whenever you bring cursor over any of the divs." }, { "code": null, "e": 7000, "s": 6198, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").mouseenter(function(){\n alert('Cursor is in!');\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Bring cursor over any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 7135, "s": 7000, "text": "Following is an example to bind a mouseleave event with <div> where an alert box is displayed whenever you take cursor out of the div." }, { "code": null, "e": 7939, "s": 7135, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").mouseleave(function(){\n alert('Curosr is out!');\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Take cursor out of any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 8118, "s": 7939, "text": "Following is an example to bind a mousedown event with <div> where an alert box is displayed whenever the left, middle or right mouse button is pressed down over any of the divs." }, { "code": null, "e": 8938, "s": 8118, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").mousedown(function(){\n alert('Mouse button is down!');\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Press mouse button down over any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 9111, "s": 8938, "text": "Following is an example to bind a mouseup event with <div> where an alert box is displayed whenever the left, middle or right mouse button is released over any of the divs." }, { "code": null, "e": 9930, "s": 9111, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").mouseup(function(){\n alert('Mouse button is released!');\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Release mouse button over any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 10096, "s": 9930, "text": "Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function.The event object provides various useful information about the event." }, { "code": null, "e": 10376, "s": 10096, "text": "The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed." }, { "code": null, "e": 10486, "s": 10376, "text": "The following event properties/attributes are available and safe to access in a platform independent manner −" }, { "code": null, "e": 10493, "s": 10486, "text": "altKey" }, { "code": null, "e": 10629, "s": 10493, "text": "Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards." }, { "code": null, "e": 10637, "s": 10629, "text": "ctrlKey" }, { "code": null, "e": 10721, "s": 10637, "text": "Set to true if the Ctrl key was pressed when the event was triggered, false if not." }, { "code": null, "e": 10726, "s": 10721, "text": "data" }, { "code": null, "e": 10832, "s": 10726, "text": "The value, if any, passed as the second parameter to the bind() command when the handler was established." }, { "code": null, "e": 10840, "s": 10832, "text": "keyCode" }, { "code": null, "e": 10909, "s": 10840, "text": "For keyup and keydown events, this returns the key that was pressed." }, { "code": null, "e": 10917, "s": 10909, "text": "metaKey" }, { "code": null, "e": 11066, "s": 10917, "text": "Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs." }, { "code": null, "e": 11072, "s": 11066, "text": "pageX" }, { "code": null, "e": 11170, "s": 11072, "text": "For mouse events, specifies the horizontal coordinate of the event relative from the page origin." }, { "code": null, "e": 11176, "s": 11170, "text": "pageY" }, { "code": null, "e": 11272, "s": 11176, "text": "For mouse events, specifies the vertical coordinate of the event relative from the page origin." }, { "code": null, "e": 11286, "s": 11272, "text": "relatedTarget" }, { "code": null, "e": 11394, "s": 11286, "text": "For some mouse events, identifies the element that the cursor left or entered when the event was triggered." }, { "code": null, "e": 11402, "s": 11394, "text": "screenX" }, { "code": null, "e": 11502, "s": 11402, "text": "For mouse events, specifies the horizontal coordinate of the event relative from the screen origin." }, { "code": null, "e": 11510, "s": 11502, "text": "screenY" }, { "code": null, "e": 11608, "s": 11510, "text": "For mouse events, specifies the vertical coordinate of the event relative from the screen origin." }, { "code": null, "e": 11617, "s": 11608, "text": "shiftKey" }, { "code": null, "e": 11702, "s": 11617, "text": "Set to true if the Shift key was pressed when the event was triggered, false if not." }, { "code": null, "e": 11709, "s": 11702, "text": "target" }, { "code": null, "e": 11767, "s": 11709, "text": "Identifies the element for which the event was triggered." }, { "code": null, "e": 11777, "s": 11767, "text": "timeStamp" }, { "code": null, "e": 11837, "s": 11777, "text": "The timestamp (in milliseconds) when the event was created." }, { "code": null, "e": 11842, "s": 11837, "text": "type" }, { "code": null, "e": 11927, "s": 11842, "text": "For all events, specifies the type of event that was triggered (for example, click)." }, { "code": null, "e": 11933, "s": 11927, "text": "which" }, { "code": null, "e": 12114, "s": 11933, "text": "For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right)." }, { "code": null, "e": 12202, "s": 12114, "text": "Following is an example to show how different square clicks give different coordinates." }, { "code": null, "e": 13179, "s": 12202, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").click(function(eventObj){\n alert('Event type is ' + eventObj.type);\n alert('pageX : ' + eventObj.pageX);\n alert('pageY : ' + eventObj.pageY);\n alert('Target : ' + eventObj.target.innerHTML);\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 13328, "s": 13179, "text": "Many times it becomes very easy to make use of this keyword inside an event handler. This keyword represents a DOM element which triggers the event." }, { "code": null, "e": 13390, "s": 13328, "text": "Following example will show the content of the clicked <div>:" }, { "code": null, "e": 14177, "s": 13390, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\">\n </script>\n <script type = \"text/javascript\">\n $(document).ready(function() {\n $(\"div\").click(function(){\n alert($(this).text());\n });\n });\n </script>\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n </body>\n</html>\n" }, { "code": null, "e": 14355, "s": 14177, "text": "Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler." }, { "code": null, "e": 14467, "s": 14355, "text": "jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −" }, { "code": null, "e": 14537, "s": 14467, "text": "selector.unbind(eventType, handler)\n\nor \n\nselector.unbind(eventType)\n" }, { "code": null, "e": 14586, "s": 14537, "text": "Following is the description of the parameters −" }, { "code": null, "e": 14730, "s": 14586, "text": "eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types." }, { "code": null, "e": 14874, "s": 14730, "text": "eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types." }, { "code": null, "e": 14952, "s": 14874, "text": "handler − If provided, identifies the specific listener that's to be removed." }, { "code": null, "e": 15030, "s": 14952, "text": "handler − If provided, identifies the specific listener that's to be removed." }, { "code": null, "e": 15063, "s": 15030, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 15077, "s": 15063, "text": " Mahesh Kumar" }, { "code": null, "e": 15112, "s": 15077, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 15126, "s": 15112, "text": " Pratik Singh" }, { "code": null, "e": 15161, "s": 15126, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 15178, "s": 15161, "text": " Frahaan Hussain" }, { "code": null, "e": 15211, "s": 15178, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 15239, "s": 15211, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 15272, "s": 15239, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 15293, "s": 15272, "text": " Sandip Bhattacharya" }, { "code": null, "e": 15325, "s": 15293, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 15342, "s": 15325, "text": " Laurence Svekis" }, { "code": null, "e": 15349, "s": 15342, "text": " Print" }, { "code": null, "e": 15360, "s": 15349, "text": " Add Notes" } ]
How to use the front camera in Swift?
To use the front camera in swift we first need to get a list of cameras available in the device we are using. In this article we’ll see how to get the list of devices and then check if the front camera is available or not. We’ll do it in a series of steps. Import AVFoundation Check if the list of cameras exists Filter out the front camera if exists. guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front }) .first as? AVCaptureDevice else { fatalError("Front camera not found") } The devices() method of AVCapture returns the list of cameras available. From that list of the camera, we’ll use the filter function in which we’ll check if the position is a camera in front or not. We can convert this to a function and use the front camera. func checkCamera() { guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front }) .first as? AVCaptureDevice else { fatalError("Front camera not found") } } Note − This cannot be run on a simulator as a simulator does not have any camera.
[ { "code": null, "e": 1319, "s": 1062, "text": "To use the front camera in swift we first need to get a list of cameras available in the device we are using. In this article we’ll see how to get the list of devices and then check if the front camera is available or not. We’ll do it in a series of steps." }, { "code": null, "e": 1339, "s": 1319, "text": "Import AVFoundation" }, { "code": null, "e": 1375, "s": 1339, "text": "Check if the list of cameras exists" }, { "code": null, "e": 1414, "s": 1375, "text": "Filter out the front camera if exists." }, { "code": null, "e": 1574, "s": 1414, "text": "guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front })\n.first as? AVCaptureDevice else {\n fatalError(\"Front camera not found\")\n}" }, { "code": null, "e": 1833, "s": 1574, "text": "The devices() method of AVCapture returns the list of cameras available. From that list of the camera, we’ll use the filter function in which we’ll check if the position is a camera in front or not. We can convert this to a function and use the front camera." }, { "code": null, "e": 2028, "s": 1833, "text": "func checkCamera() {\n guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front })\n .first as? AVCaptureDevice else {\n fatalError(\"Front camera not found\")\n }\n}" }, { "code": null, "e": 2110, "s": 2028, "text": "Note − This cannot be run on a simulator as a simulator does not have any camera." } ]
Interactive Simulation with Tableau and Jupytab | by Brian Tribondeau | Towards Data Science
This article shows how to let Tableau, a leading interactive data visualization tool, access dynamic data instead of static data. This opens up new applications, such as dashboards that can display real-time data, or the ability of users to display dynamic predictions obtained by machine learning models. We start with a gentle introduction to dynamic data access in Tableau, both through Tableau’s native language and through Python (via Analytics Extensions). Since this is a hands-on article, we describe how to install the necessary components (Tableau, and Jupyter notebooks) and then illustrate how to configure them and quickly obtain a Tableau dashboard that displays dynamic data based on machine learning. Tableau is a Business Intelligence tool widely used by the industry (along with PowerBI and QlikView). It allows non-technical people to create and deploy web application with a drag and drop interface. The only drawback is that by default, the data need to be readily available in a supported database, which cannot itself be updated through the interface. You can however create blazingly fast interactive dashboards that connect to numerous data sources, and quickly get an overview of your data at scale. Tableau offers an Excel-like language that allows users to create custom calculations and manipulate different types of data (numeric, string, boolean). However the limitations of this scripting language can be very frustrating as there is no data manipulation like pivot tables, and even some simple transformations (like splitting a field into multiple columns) often require numerous steps. Tableau’s scripting language is mainly there to transform values at the cell level, or to operate on the full data set for filtering or computing an aggregation. That said, your options are rather limited and you will have to mainly prepare your data outside of Tableau and create a precomputed dataset will all the data that you want to display. But what if you want to create a simulation or apply some machine learning techniques and visualize the resulting changes after updating some parameters? The way Tableau works with data source simply does not allow this kind of operation, or that would force you to code your algorithm without any library, which is thoroughly impractical. To achieve real-time analytics with Tableau, or at least on-the-fly computations using custom algorithms, a very interesting feature of Tableau is hidden in Help → Settings and Performance → Manage Analytics Extension Connection.... It allows you to achieve what we would expect from a web application. Here is where Analytics Extension Connections fit in the Tableau data ecosystem: The two places in Tableau where we can expect Python code are in data source creation, and on-the-fly computations (based on the displayed data). Data source creation The data source is often an existing database. It is possible to write a custom data injector that writes to this database. This approach should be fast, but it obviously requires a full-blown database, and also a scheduler that regularly invokes the data injector program. Another approach consists in connecting directly to a custom data source. Tableau thus allows us to create custom Web Data Connector (WDC) and use the WDC API. A fair number of connectors are available, some of which may fit your need. If this is not the case you will have to create a custom connector, but be warned: the learning curve is steep. Another alternative is that illustrated in this article: by using Jupytab, you can directly export your Pandas Dataframes to Tableau from a Jupyter notebook. (This approach uses the WDC API under the hood, so that you don’t have to wrangle with it.) By using Jupytab, you also get scheduled data refreshes for free, as you can use the Tableau internal scheduler to poll data on demand. A minor limitation of this approach is the maximum size of data sources: data sets with a billion rows typically do not fit easily in a Pandas Dataframe! On-the-fly computations Besides Jupytab, not many other Tableau tools perform on-the-fly data source creation and computation. We must however mention TabPy, which is Tableau’s own tool for interactive analytics in Python. It creates a server that allows you to use Python code in Tableau, by executing code on demand. Jupytab serves exactly the same purpose, but with a few key differences: All your Python code comes from a single notebook: you create the data source and expose it for Tableau there. You don’t write Python code in Tableau, you always call a Python function from your notebook. The set of available libraries is linked to the notebook. This means that you can create multiple execution environments with different sets of libraries and use all of them in Tableau, possibly from multiple notebooks. If your main development tool is a Jupyter notebook with Pandas and some data science libraries, and you want to quickly create interactive dashboards ready for production, Jupytab is a tool that is worth a try. We assume that you are familiar with Python, Conda (or virtualenv), Jupyter and use Linux/macOS for your development. Jupytab works on Windows but is not as well tested—using WSL (Windows Subsystem for Linux) works with this article, though. We will be using conda for the installation, but it should work with pip as well. Jupytab has two components, jupytab and jupytab-server, that need to be installed in their own environment: jupytab: a very simple API that exposes dataframes and custom functions from a notebook. It needs be installed in the notebook environment, and only requires Pandas as a dependency. jupytab-server: provides the Web Data Connector, spawns kernels, manages the configuration and so on... Do not install this component in the same environment as your notebook, so as to prevent conflicts. We first create a virtual environment using Python 3.7 to keep everything clean and reproducible (you can also skip this part if you are ready to follow along in a Conda environment that you already have): (base) % conda create -n jupytab-notebook-env python=3.7(base) % conda activate jupytab-notebook-env Then we install the latest jupytab version and the ipykernel library so as to make our Jupyter kernel available in notebooks: (jupytab-notebook-env) % conda install jupytab=0.9.11 Then we install the kernel in Jupyter: (jupytab-notebook-env) % conda install ipykernel(jupytab-notebook-env) % python -m ipykernel install --user --name jupytab-simulation-demo You can now create, in Jupyter, a notebook that will use the newly installed kernel. It is best to check that Jupytab has been properly installed by checking its version, for example by doing: import jupytabprint(jupytab.__version__) [Output]: 0.9.11 We also create a new virtual environment based on Python 3.7. You can open a new terminal or just deactivate your previous environment using the command conda deactivate: (base) % conda create -n jupytab-server-env python=3.7(base) % conda activate jupytab-server-env Then we install the latest jupytab-server version and... that’s all! (jupytab-server-env) % conda install jupytab-server=0.9.11 The notebook and dashboard that inspired this article are freely available: don’t hesitate to download them and use them to follow along. For our simulation we will only use Pandas and scikit-learn but you may of course install your own libraries. We start by installing scikit-learn in the jupytab-notebook-env (from the base environment, so either in a new terminal or after conda deactivate): (base) % conda activate jupytab-notebook-env# No need to install pandas, it is already installed with jupytab:(jupytab-notebook-env) % conda install scikit-learn We create a new notebook named jupytab-simulation-notebook We will use the well known iris data set, which is included in scikit-learn, and load everything in Pandas dataframes: import pandas as pdimport jupytabfrom sklearn.datasets import load_irisiris = load_iris()iris_data_df = pd.DataFrame(columns=iris.feature_names, data=iris.data)iris_target_df = pd.DataFrame(columns=['target'], data=iris.target)iris_target_class_df = pd.DataFrame(columns=['target_name'], data=iris.target_names)iris_data_df.sample(2) [Output]: Then we load the dataframe in a Jupytab Tables dictionary, to indicate that we want to expose those data to Tableau: tables = jupytab.Tables()tables['iris'] = jupytab.DataFrameTable("Iris DataSet", iris_data_df, include_index=True)tables['iris_target'] = jupytab.DataFrameTable("Iris Classification Target", iris_target_df, include_index=True)tables['iris_target_class'] = jupytab.DataFrameTable("Iris Classes", iris_target_class_df, include_index=True) A DataFrameTable defines how to expose data to Tableau: Here, we simply exposed static DataFrames along with their index. In order to allow jupytab-server to retrieve data, we need to add two cells. The first cell generates a schema that declares all our Dataframes. It needs to be exactly like the cell below (you can copy and paste directly in your notebook): # GET /schematables.render_schema() Executing this cell prints the schema exported to Tableau. [Output]: [{“id”: “iris”, “alias”: “Iris DataSet”, “columns”: [{“id”: “index”, “dataType”: “int”}, {“id”: “sepal_length_cm_”, “dataType”: “float”}, {“id”: “sepal_width_cm_”, “dataType”: “float”}, {“id”: “petal_length_cm_”, “dataType”: “float”}, {“id”: “petal_width_cm_”, “dataType”: “float”}]}, {“id”: “iris_target”, “alias”: “Iris Classification Target”, “columns”: [{“id”: “index”, “dataType”: “int”}, {“id”: “target”, “dataType”: “int”}]}, {“id”: “iris_target_class”, “alias”: “Iris Classes”, “columns”: [{“id”: “index”, “dataType”: “int”}, {“id”: “target_name”, “dataType”: “string”}]}] The second cell is where data is exported: # GET /datatables.render_data(REQUEST) Executing this cell generates a harmless error in the notebook: the REQUEST variable is only available when the notebook is executed by the Jupytab server: [Output]: NameError Traceback (most recent call last)<ipython-input-1-c5e1a6b1cfcd> in <module> 1 # GET /data — → 2 tables.render_data(REQUEST) If you don’t want to get the error during execution, you can wrap render_data() with a simple try block: # GET /datatry: tables.render_data(REQUEST)except NameError: print("Not available outside jupytab context") That’s it! You may also find several Jupytab notebook examples in the Jupytab GitHub repository under the jupitab-server/samples directory. In the Jupytab server environment, we need to create a configuration file that will allow us to configure a few parameters like the server port, a secret token and of course the list of notebooks that the server must exposes. The config file may be created using a simple cat command (under Unix), or by writing a config.ini file using any text editor: (base) % conda activate jupytab-server-env(jupytab-server-env) % cat << EOF > config.ini[main]listen_port = 8123notebooks = JupytabSimulator [JupytabSimulator]path = /path/to/your/notebook/jupytab-simulation-notebook.ipynbEOF More configuration options are also available. When you are done, you only need to start the Jupytab server: (jupytab-server-env) % jupytab --config=/path/to/your/config.iniStarting Jupytab-Server 0.9.11SSL not enabledStart notebook /path/to/your/notebook/jupytab-simulation-notebook.ipynb on 127.0.0.1:35453You have no defined token. Please note your process is not secured ! Please open : http://computer_name:8123INFO:[KernelGatewayApp] Kernel started: a6abe896-2cb8-403a-8661-3236e16d8defINFO:[KernelGatewayApp] Registering resource: /schema, methods: (['GET'])INFO:[KernelGatewayApp] Registering resource: /data, methods: (['GET'])INFO:[KernelGatewayApp] Registering resource: /_api/spec/swagger.json, methods: (GET)INFO:[KernelGatewayApp] Jupyter Kernel Gateway at http://127.0.0.1:35453 This will run the notebook and create a server allowing you to access it. Please note that you need to wait for the registration of your notebook resources to appear in the log, otherwise you will not be able to access it from Tableau. This is the part below: INFO:[KernelGatewayApp] Registering resource: /schema, methods: (['GET'])INFO:[KernelGatewayApp] Registering resource: /data, methods: (['GET']) If your notebook takes time to compute, this may take a few minutes to appear. If you don’t have Tableau installed already, you can download it and try it for free. This article was tested with Tableau 2020.2, so you might have to adapt the instructions slightly as needed. Select the Web Data Connector from the Start screen: You can then input the web data connector URL that was printed in the terminal: Start notebook /path/to/your/notebook/jupytab-simulation-notebook.ipynb on 127.0.0.1:35453You have no defined token. Please note your process is not secured ! Please open : http://computer_name:8123 You should be able to select your first notebook and view all available actions: Proceed to Explore in Tableau and create your data set using the provided tables. Pay attention to the order and join between the tables: We now have a data set to work with, imported from a Jupyter notebook. We will create a Tableau simulator based on the Iris data set. It is often used as a common machine learning example. The task at hand consists in classifying 3 types of iris according to only four dimensions (sepal and petal length/width). The goal of this simulator is only to get a glimpse of the creation of dashboards using Tableau. They can be created without writing a single line of code and, more importantly, in only a few minutes. We will use a Multi-Layer Perceptron (MLP) classifier and train it with the full content of the data set. Our goal is not to achieve any kind of high-accuracy predictions, but instead to showcase how you can dynamically make predictions from within Tableau, thanks to Jupytab. As we did with jupytab.Tables, we need to add a jupytab.Functions dictionary for registering our predictor method: from sklearn.neural_network import MLPClassifierclf = MLPClassifier(max_iter=600).fit(iris.data, iris.target)def predictor(sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm): class_predict = clf.predict([[sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm]]) return iris.target_names[class_predict][0] # We return the only predictionfunctions = jupytab.Functions()functions['predict'] = jupytab.Function('A predictor for the Iris DataSet', predictor)predictor(0.5, 5, 4, 2) [Output]: ‘virginica’ We also need to define a new endpoint that will be used by the Jupytab server: # POST /evaluatetry: functions.render_evaluate(REQUEST)except NameError: print("Not available outside jupytab context") [Output]: Not available outside jupytab context We must then save the notebook and restart the kernel from Tableau so that our changes are taken into account by Tableau. Before using the predictor function in Tableau, we need to register our Jupytab server as an analytics extension in Tableau. This is easily done from the Help → Settings and Performance → Manage Analytics Extension Connection item from the Tableau Desktop menu. Check that everything works fine by using the Test Connection button: To display a data point for each specimen, we need to transform our Iris DataSet Index to a dimension: Then drop this value as Detail: We get the following result: We will then display a grid to visualize all dimensions against each others. Select all measures from the Iris DataSet: And drop in Columns: Do the same with Rows: Your visualization is almost ready! Just drop the Target Name from Iris Classes in the Color marks. The output allows you to visualize the result as a grid graph comparing all dimensions: Now we would like to check that our model correctly predicts the Iris type. We want to call our predictor for each Iris sample and display misclassified data in the graph above. We need to create a Calculated Field to achieve that: The following formula returns the predicted Iris type: SCRIPT_STR("JupytabSimulator.predict", AVG([Sepal Length Cm]), AVG([Sepal Width Cm]), AVG([Petal Length Cm]), AVG([Petal Width Cm])) JupytabSimulator is the name of our registered notebook in our config.ini file, and predict the name of our registered function. The join of the two values is the target. This means that you can target different notebooks, each one using its own virtual environment and set of libraries. Function parameters are the four parameters that you defined in your predictor function, and of course they need to be inserted in the same order. We also need another function that will compare the real Iris type with the predictor and return False if there is a mismatch. The ATTR function is required, as Iris Predictor is already an aggregated data: ATTR([Target Name]) = [Iris Predictor] We will then replace the current Clusters color using Prediction Matching and choose Circle as the representation. Tableau will communicate with Jupytab for a few minutes, as it needs to predict the Iris class for all the displayed marks (i.e., data points): This is an important point of the Tableau Analytics extension: you need to minimize the number of marks displayed in your Dashboard to guarantee quick results and a more interactive experience. Incorrect predictions can then be displayed thanks to the Prediction Matching calculation above: By comparing this graph with the previous one, we see how mis-predicted iris types tend to happen at the frontier between iris groups. A visualization that only gives us the number of mismatch, would drastically the number of marks, while still providing some important informations. We only need to remove all measures from Columns & Rows to replace them by our Prediction Matching calculation. This new visualization will load in a few seconds: Last but not least, we would like to understand how the number of iterations of our MLP training impacts our results. This will require us to use another cool feature of Tableau: Parameters. We start by updating our predictor function in the notebook, adding a new optional variable that will train (again) our MLP. We only need to cache the result to avoid training with the same number of iterations at each invocation: from sklearn.neural_network import MLPClassifierlast_max_iter = 0clf = Nonedef train(request_max_iter): global clf, last_max_iter if not clf or last_max_iter != request_max_iter: clf = MLPClassifier(max_iter=request_max_iter, random_state=1).fit(iris.data, iris.target) last_max_iter = request_max_iter return clfdef predictor(sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, request_max_iter=1000): clf = train(request_max_iter) # We now train as needed class_predict = clf.predict([[sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm]]) return iris.target_names[class_predict][0]functions = jupytab.Functions()functions['predict'] = jupytab.Function('A predictor for the Iris DataSet', predictor)predictor(0.5, 5, 4, 2) [Output]: ‘virginica’ Do not forget to restart the kernel in Tableau through the Jupytab UI so as to apply the changes. On the Tableau side, we will create a parameter with a range from 10 to 1000 in order to visualize the impact of the number of training iterations on our predictions: We then add this parameter to our view: We can now dynamically change the maximum number of training iteration of our MLP: We also need to update the Iris Predictor calculation and add this new parameter: SCRIPT_STR("JupytabSimulator.predict", AVG([Sepal Length Cm]), AVG([Sepal Width Cm]), AVG([Petal Length Cm]), AVG([Petal Width Cm]), [MLP Max Iteration]) Just after clicking on apply, the result is immediately updated with our default value of 10 iterations. MLP Training 10 Iterations MLP Training 100 Iterations Tableau is a very powerful tool for data visualization. Using Jupyter notebooks to compute data and get an almost immediate feedback is very convenient. We have barely scratched the surface of Tableau features, and there is almost no limit to the kind of visualisations and interactions that you may create in your dashboard. The Jupytab project is open source and accessible on GitHub under the MIT license. You can also peruse online many impressive dashboards done with Tableau. This is the first project I have ever published on GitHub and it would probably never have left my computer without the strong support of CFM‘s Open-Source Program and the help of people working there. I would especially like to thanks Jean-Sébastien Dieu, Eric Lebigot and Florent Zara for their support on various aspects of Jupytab and for helping me to publish this article.
[ { "code": null, "e": 478, "s": 172, "text": "This article shows how to let Tableau, a leading interactive data visualization tool, access dynamic data instead of static data. This opens up new applications, such as dashboards that can display real-time data, or the ability of users to display dynamic predictions obtained by machine learning models." }, { "code": null, "e": 889, "s": 478, "text": "We start with a gentle introduction to dynamic data access in Tableau, both through Tableau’s native language and through Python (via Analytics Extensions). Since this is a hands-on article, we describe how to install the necessary components (Tableau, and Jupyter notebooks) and then illustrate how to configure them and quickly obtain a Tableau dashboard that displays dynamic data based on machine learning." }, { "code": null, "e": 1092, "s": 889, "text": "Tableau is a Business Intelligence tool widely used by the industry (along with PowerBI and QlikView). It allows non-technical people to create and deploy web application with a drag and drop interface." }, { "code": null, "e": 1398, "s": 1092, "text": "The only drawback is that by default, the data need to be readily available in a supported database, which cannot itself be updated through the interface. You can however create blazingly fast interactive dashboards that connect to numerous data sources, and quickly get an overview of your data at scale." }, { "code": null, "e": 1792, "s": 1398, "text": "Tableau offers an Excel-like language that allows users to create custom calculations and manipulate different types of data (numeric, string, boolean). However the limitations of this scripting language can be very frustrating as there is no data manipulation like pivot tables, and even some simple transformations (like splitting a field into multiple columns) often require numerous steps." }, { "code": null, "e": 2139, "s": 1792, "text": "Tableau’s scripting language is mainly there to transform values at the cell level, or to operate on the full data set for filtering or computing an aggregation. That said, your options are rather limited and you will have to mainly prepare your data outside of Tableau and create a precomputed dataset will all the data that you want to display." }, { "code": null, "e": 2479, "s": 2139, "text": "But what if you want to create a simulation or apply some machine learning techniques and visualize the resulting changes after updating some parameters? The way Tableau works with data source simply does not allow this kind of operation, or that would force you to code your algorithm without any library, which is thoroughly impractical." }, { "code": null, "e": 2782, "s": 2479, "text": "To achieve real-time analytics with Tableau, or at least on-the-fly computations using custom algorithms, a very interesting feature of Tableau is hidden in Help → Settings and Performance → Manage Analytics Extension Connection.... It allows you to achieve what we would expect from a web application." }, { "code": null, "e": 2863, "s": 2782, "text": "Here is where Analytics Extension Connections fit in the Tableau data ecosystem:" }, { "code": null, "e": 3009, "s": 2863, "text": "The two places in Tableau where we can expect Python code are in data source creation, and on-the-fly computations (based on the displayed data)." }, { "code": null, "e": 3030, "s": 3009, "text": "Data source creation" }, { "code": null, "e": 3304, "s": 3030, "text": "The data source is often an existing database. It is possible to write a custom data injector that writes to this database. This approach should be fast, but it obviously requires a full-blown database, and also a scheduler that regularly invokes the data injector program." }, { "code": null, "e": 3652, "s": 3304, "text": "Another approach consists in connecting directly to a custom data source. Tableau thus allows us to create custom Web Data Connector (WDC) and use the WDC API. A fair number of connectors are available, some of which may fit your need. If this is not the case you will have to create a custom connector, but be warned: the learning curve is steep." }, { "code": null, "e": 4192, "s": 3652, "text": "Another alternative is that illustrated in this article: by using Jupytab, you can directly export your Pandas Dataframes to Tableau from a Jupyter notebook. (This approach uses the WDC API under the hood, so that you don’t have to wrangle with it.) By using Jupytab, you also get scheduled data refreshes for free, as you can use the Tableau internal scheduler to poll data on demand. A minor limitation of this approach is the maximum size of data sources: data sets with a billion rows typically do not fit easily in a Pandas Dataframe!" }, { "code": null, "e": 4216, "s": 4192, "text": "On-the-fly computations" }, { "code": null, "e": 4511, "s": 4216, "text": "Besides Jupytab, not many other Tableau tools perform on-the-fly data source creation and computation. We must however mention TabPy, which is Tableau’s own tool for interactive analytics in Python. It creates a server that allows you to use Python code in Tableau, by executing code on demand." }, { "code": null, "e": 4584, "s": 4511, "text": "Jupytab serves exactly the same purpose, but with a few key differences:" }, { "code": null, "e": 4695, "s": 4584, "text": "All your Python code comes from a single notebook: you create the data source and expose it for Tableau there." }, { "code": null, "e": 4789, "s": 4695, "text": "You don’t write Python code in Tableau, you always call a Python function from your notebook." }, { "code": null, "e": 5009, "s": 4789, "text": "The set of available libraries is linked to the notebook. This means that you can create multiple execution environments with different sets of libraries and use all of them in Tableau, possibly from multiple notebooks." }, { "code": null, "e": 5221, "s": 5009, "text": "If your main development tool is a Jupyter notebook with Pandas and some data science libraries, and you want to quickly create interactive dashboards ready for production, Jupytab is a tool that is worth a try." }, { "code": null, "e": 5545, "s": 5221, "text": "We assume that you are familiar with Python, Conda (or virtualenv), Jupyter and use Linux/macOS for your development. Jupytab works on Windows but is not as well tested—using WSL (Windows Subsystem for Linux) works with this article, though. We will be using conda for the installation, but it should work with pip as well." }, { "code": null, "e": 5653, "s": 5545, "text": "Jupytab has two components, jupytab and jupytab-server, that need to be installed in their own environment:" }, { "code": null, "e": 5835, "s": 5653, "text": "jupytab: a very simple API that exposes dataframes and custom functions from a notebook. It needs be installed in the notebook environment, and only requires Pandas as a dependency." }, { "code": null, "e": 6039, "s": 5835, "text": "jupytab-server: provides the Web Data Connector, spawns kernels, manages the configuration and so on... Do not install this component in the same environment as your notebook, so as to prevent conflicts." }, { "code": null, "e": 6245, "s": 6039, "text": "We first create a virtual environment using Python 3.7 to keep everything clean and reproducible (you can also skip this part if you are ready to follow along in a Conda environment that you already have):" }, { "code": null, "e": 6346, "s": 6245, "text": "(base) % conda create -n jupytab-notebook-env python=3.7(base) % conda activate jupytab-notebook-env" }, { "code": null, "e": 6472, "s": 6346, "text": "Then we install the latest jupytab version and the ipykernel library so as to make our Jupyter kernel available in notebooks:" }, { "code": null, "e": 6526, "s": 6472, "text": "(jupytab-notebook-env) % conda install jupytab=0.9.11" }, { "code": null, "e": 6565, "s": 6526, "text": "Then we install the kernel in Jupyter:" }, { "code": null, "e": 6704, "s": 6565, "text": "(jupytab-notebook-env) % conda install ipykernel(jupytab-notebook-env) % python -m ipykernel install --user --name jupytab-simulation-demo" }, { "code": null, "e": 6789, "s": 6704, "text": "You can now create, in Jupyter, a notebook that will use the newly installed kernel." }, { "code": null, "e": 6897, "s": 6789, "text": "It is best to check that Jupytab has been properly installed by checking its version, for example by doing:" }, { "code": null, "e": 6938, "s": 6897, "text": "import jupytabprint(jupytab.__version__)" }, { "code": null, "e": 6955, "s": 6938, "text": "[Output]: 0.9.11" }, { "code": null, "e": 7126, "s": 6955, "text": "We also create a new virtual environment based on Python 3.7. You can open a new terminal or just deactivate your previous environment using the command conda deactivate:" }, { "code": null, "e": 7223, "s": 7126, "text": "(base) % conda create -n jupytab-server-env python=3.7(base) % conda activate jupytab-server-env" }, { "code": null, "e": 7292, "s": 7223, "text": "Then we install the latest jupytab-server version and... that’s all!" }, { "code": null, "e": 7351, "s": 7292, "text": "(jupytab-server-env) % conda install jupytab-server=0.9.11" }, { "code": null, "e": 7489, "s": 7351, "text": "The notebook and dashboard that inspired this article are freely available: don’t hesitate to download them and use them to follow along." }, { "code": null, "e": 7747, "s": 7489, "text": "For our simulation we will only use Pandas and scikit-learn but you may of course install your own libraries. We start by installing scikit-learn in the jupytab-notebook-env (from the base environment, so either in a new terminal or after conda deactivate):" }, { "code": null, "e": 7909, "s": 7747, "text": "(base) % conda activate jupytab-notebook-env# No need to install pandas, it is already installed with jupytab:(jupytab-notebook-env) % conda install scikit-learn" }, { "code": null, "e": 7968, "s": 7909, "text": "We create a new notebook named jupytab-simulation-notebook" }, { "code": null, "e": 8087, "s": 7968, "text": "We will use the well known iris data set, which is included in scikit-learn, and load everything in Pandas dataframes:" }, { "code": null, "e": 8421, "s": 8087, "text": "import pandas as pdimport jupytabfrom sklearn.datasets import load_irisiris = load_iris()iris_data_df = pd.DataFrame(columns=iris.feature_names, data=iris.data)iris_target_df = pd.DataFrame(columns=['target'], data=iris.target)iris_target_class_df = pd.DataFrame(columns=['target_name'], data=iris.target_names)iris_data_df.sample(2)" }, { "code": null, "e": 8431, "s": 8421, "text": "[Output]:" }, { "code": null, "e": 8548, "s": 8431, "text": "Then we load the dataframe in a Jupytab Tables dictionary, to indicate that we want to expose those data to Tableau:" }, { "code": null, "e": 8885, "s": 8548, "text": "tables = jupytab.Tables()tables['iris'] = jupytab.DataFrameTable(\"Iris DataSet\", iris_data_df, include_index=True)tables['iris_target'] = jupytab.DataFrameTable(\"Iris Classification Target\", iris_target_df, include_index=True)tables['iris_target_class'] = jupytab.DataFrameTable(\"Iris Classes\", iris_target_class_df, include_index=True)" }, { "code": null, "e": 8941, "s": 8885, "text": "A DataFrameTable defines how to expose data to Tableau:" }, { "code": null, "e": 9007, "s": 8941, "text": "Here, we simply exposed static DataFrames along with their index." }, { "code": null, "e": 9084, "s": 9007, "text": "In order to allow jupytab-server to retrieve data, we need to add two cells." }, { "code": null, "e": 9247, "s": 9084, "text": "The first cell generates a schema that declares all our Dataframes. It needs to be exactly like the cell below (you can copy and paste directly in your notebook):" }, { "code": null, "e": 9283, "s": 9247, "text": "# GET /schematables.render_schema()" }, { "code": null, "e": 9342, "s": 9283, "text": "Executing this cell prints the schema exported to Tableau." }, { "code": null, "e": 9933, "s": 9342, "text": "[Output]: [{“id”: “iris”, “alias”: “Iris DataSet”, “columns”: [{“id”: “index”, “dataType”: “int”}, {“id”: “sepal_length_cm_”, “dataType”: “float”}, {“id”: “sepal_width_cm_”, “dataType”: “float”}, {“id”: “petal_length_cm_”, “dataType”: “float”}, {“id”: “petal_width_cm_”, “dataType”: “float”}]}, {“id”: “iris_target”, “alias”: “Iris Classification Target”, “columns”: [{“id”: “index”, “dataType”: “int”}, {“id”: “target”, “dataType”: “int”}]}, {“id”: “iris_target_class”, “alias”: “Iris Classes”, “columns”: [{“id”: “index”, “dataType”: “int”}, {“id”: “target_name”, “dataType”: “string”}]}]" }, { "code": null, "e": 9976, "s": 9933, "text": "The second cell is where data is exported:" }, { "code": null, "e": 10015, "s": 9976, "text": "# GET /datatables.render_data(REQUEST)" }, { "code": null, "e": 10171, "s": 10015, "text": "Executing this cell generates a harmless error in the notebook: the REQUEST variable is only available when the notebook is executed by the Jupytab server:" }, { "code": null, "e": 10315, "s": 10171, "text": "[Output]: NameError Traceback (most recent call last)<ipython-input-1-c5e1a6b1cfcd> in <module> 1 # GET /data — → 2 tables.render_data(REQUEST)" }, { "code": null, "e": 10420, "s": 10315, "text": "If you don’t want to get the error during execution, you can wrap render_data() with a simple try block:" }, { "code": null, "e": 10534, "s": 10420, "text": "# GET /datatry: tables.render_data(REQUEST)except NameError: print(\"Not available outside jupytab context\")" }, { "code": null, "e": 10674, "s": 10534, "text": "That’s it! You may also find several Jupytab notebook examples in the Jupytab GitHub repository under the jupitab-server/samples directory." }, { "code": null, "e": 10900, "s": 10674, "text": "In the Jupytab server environment, we need to create a configuration file that will allow us to configure a few parameters like the server port, a secret token and of course the list of notebooks that the server must exposes." }, { "code": null, "e": 11027, "s": 10900, "text": "The config file may be created using a simple cat command (under Unix), or by writing a config.ini file using any text editor:" }, { "code": null, "e": 11253, "s": 11027, "text": "(base) % conda activate jupytab-server-env(jupytab-server-env) % cat << EOF > config.ini[main]listen_port = 8123notebooks = JupytabSimulator [JupytabSimulator]path = /path/to/your/notebook/jupytab-simulation-notebook.ipynbEOF" }, { "code": null, "e": 11300, "s": 11253, "text": "More configuration options are also available." }, { "code": null, "e": 11362, "s": 11300, "text": "When you are done, you only need to start the Jupytab server:" }, { "code": null, "e": 12054, "s": 11362, "text": "(jupytab-server-env) % jupytab --config=/path/to/your/config.iniStarting Jupytab-Server 0.9.11SSL not enabledStart notebook /path/to/your/notebook/jupytab-simulation-notebook.ipynb on 127.0.0.1:35453You have no defined token. Please note your process is not secured ! Please open : http://computer_name:8123INFO:[KernelGatewayApp] Kernel started: a6abe896-2cb8-403a-8661-3236e16d8defINFO:[KernelGatewayApp] Registering resource: /schema, methods: (['GET'])INFO:[KernelGatewayApp] Registering resource: /data, methods: (['GET'])INFO:[KernelGatewayApp] Registering resource: /_api/spec/swagger.json, methods: (GET)INFO:[KernelGatewayApp] Jupyter Kernel Gateway at http://127.0.0.1:35453" }, { "code": null, "e": 12128, "s": 12054, "text": "This will run the notebook and create a server allowing you to access it." }, { "code": null, "e": 12314, "s": 12128, "text": "Please note that you need to wait for the registration of your notebook resources to appear in the log, otherwise you will not be able to access it from Tableau. This is the part below:" }, { "code": null, "e": 12459, "s": 12314, "text": "INFO:[KernelGatewayApp] Registering resource: /schema, methods: (['GET'])INFO:[KernelGatewayApp] Registering resource: /data, methods: (['GET'])" }, { "code": null, "e": 12538, "s": 12459, "text": "If your notebook takes time to compute, this may take a few minutes to appear." }, { "code": null, "e": 12733, "s": 12538, "text": "If you don’t have Tableau installed already, you can download it and try it for free. This article was tested with Tableau 2020.2, so you might have to adapt the instructions slightly as needed." }, { "code": null, "e": 12786, "s": 12733, "text": "Select the Web Data Connector from the Start screen:" }, { "code": null, "e": 12866, "s": 12786, "text": "You can then input the web data connector URL that was printed in the terminal:" }, { "code": null, "e": 13072, "s": 12866, "text": "Start notebook /path/to/your/notebook/jupytab-simulation-notebook.ipynb on 127.0.0.1:35453You have no defined token. Please note your process is not secured ! Please open : http://computer_name:8123" }, { "code": null, "e": 13153, "s": 13072, "text": "You should be able to select your first notebook and view all available actions:" }, { "code": null, "e": 13291, "s": 13153, "text": "Proceed to Explore in Tableau and create your data set using the provided tables. Pay attention to the order and join between the tables:" }, { "code": null, "e": 13362, "s": 13291, "text": "We now have a data set to work with, imported from a Jupyter notebook." }, { "code": null, "e": 13603, "s": 13362, "text": "We will create a Tableau simulator based on the Iris data set. It is often used as a common machine learning example. The task at hand consists in classifying 3 types of iris according to only four dimensions (sepal and petal length/width)." }, { "code": null, "e": 13804, "s": 13603, "text": "The goal of this simulator is only to get a glimpse of the creation of dashboards using Tableau. They can be created without writing a single line of code and, more importantly, in only a few minutes." }, { "code": null, "e": 14081, "s": 13804, "text": "We will use a Multi-Layer Perceptron (MLP) classifier and train it with the full content of the data set. Our goal is not to achieve any kind of high-accuracy predictions, but instead to showcase how you can dynamically make predictions from within Tableau, thanks to Jupytab." }, { "code": null, "e": 14196, "s": 14081, "text": "As we did with jupytab.Tables, we need to add a jupytab.Functions dictionary for registering our predictor method:" }, { "code": null, "e": 14706, "s": 14196, "text": "from sklearn.neural_network import MLPClassifierclf = MLPClassifier(max_iter=600).fit(iris.data, iris.target)def predictor(sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm): class_predict = clf.predict([[sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm]]) return iris.target_names[class_predict][0] # We return the only predictionfunctions = jupytab.Functions()functions['predict'] = jupytab.Function('A predictor for the Iris DataSet', predictor)predictor(0.5, 5, 4, 2)" }, { "code": null, "e": 14728, "s": 14706, "text": "[Output]: ‘virginica’" }, { "code": null, "e": 14807, "s": 14728, "text": "We also need to define a new endpoint that will be used by the Jupytab server:" }, { "code": null, "e": 14933, "s": 14807, "text": "# POST /evaluatetry: functions.render_evaluate(REQUEST)except NameError: print(\"Not available outside jupytab context\")" }, { "code": null, "e": 14981, "s": 14933, "text": "[Output]: Not available outside jupytab context" }, { "code": null, "e": 15103, "s": 14981, "text": "We must then save the notebook and restart the kernel from Tableau so that our changes are taken into account by Tableau." }, { "code": null, "e": 15228, "s": 15103, "text": "Before using the predictor function in Tableau, we need to register our Jupytab server as an analytics extension in Tableau." }, { "code": null, "e": 15365, "s": 15228, "text": "This is easily done from the Help → Settings and Performance → Manage Analytics Extension Connection item from the Tableau Desktop menu." }, { "code": null, "e": 15435, "s": 15365, "text": "Check that everything works fine by using the Test Connection button:" }, { "code": null, "e": 15538, "s": 15435, "text": "To display a data point for each specimen, we need to transform our Iris DataSet Index to a dimension:" }, { "code": null, "e": 15570, "s": 15538, "text": "Then drop this value as Detail:" }, { "code": null, "e": 15599, "s": 15570, "text": "We get the following result:" }, { "code": null, "e": 15719, "s": 15599, "text": "We will then display a grid to visualize all dimensions against each others. Select all measures from the Iris DataSet:" }, { "code": null, "e": 15740, "s": 15719, "text": "And drop in Columns:" }, { "code": null, "e": 15763, "s": 15740, "text": "Do the same with Rows:" }, { "code": null, "e": 15799, "s": 15763, "text": "Your visualization is almost ready!" }, { "code": null, "e": 15863, "s": 15799, "text": "Just drop the Target Name from Iris Classes in the Color marks." }, { "code": null, "e": 15951, "s": 15863, "text": "The output allows you to visualize the result as a grid graph comparing all dimensions:" }, { "code": null, "e": 16183, "s": 15951, "text": "Now we would like to check that our model correctly predicts the Iris type. We want to call our predictor for each Iris sample and display misclassified data in the graph above. We need to create a Calculated Field to achieve that:" }, { "code": null, "e": 16238, "s": 16183, "text": "The following formula returns the predicted Iris type:" }, { "code": null, "e": 16371, "s": 16238, "text": "SCRIPT_STR(\"JupytabSimulator.predict\", AVG([Sepal Length Cm]), AVG([Sepal Width Cm]), AVG([Petal Length Cm]), AVG([Petal Width Cm]))" }, { "code": null, "e": 16659, "s": 16371, "text": "JupytabSimulator is the name of our registered notebook in our config.ini file, and predict the name of our registered function. The join of the two values is the target. This means that you can target different notebooks, each one using its own virtual environment and set of libraries." }, { "code": null, "e": 16806, "s": 16659, "text": "Function parameters are the four parameters that you defined in your predictor function, and of course they need to be inserted in the same order." }, { "code": null, "e": 17013, "s": 16806, "text": "We also need another function that will compare the real Iris type with the predictor and return False if there is a mismatch. The ATTR function is required, as Iris Predictor is already an aggregated data:" }, { "code": null, "e": 17052, "s": 17013, "text": "ATTR([Target Name]) = [Iris Predictor]" }, { "code": null, "e": 17167, "s": 17052, "text": "We will then replace the current Clusters color using Prediction Matching and choose Circle as the representation." }, { "code": null, "e": 17311, "s": 17167, "text": "Tableau will communicate with Jupytab for a few minutes, as it needs to predict the Iris class for all the displayed marks (i.e., data points):" }, { "code": null, "e": 17505, "s": 17311, "text": "This is an important point of the Tableau Analytics extension: you need to minimize the number of marks displayed in your Dashboard to guarantee quick results and a more interactive experience." }, { "code": null, "e": 17602, "s": 17505, "text": "Incorrect predictions can then be displayed thanks to the Prediction Matching calculation above:" }, { "code": null, "e": 17737, "s": 17602, "text": "By comparing this graph with the previous one, we see how mis-predicted iris types tend to happen at the frontier between iris groups." }, { "code": null, "e": 18049, "s": 17737, "text": "A visualization that only gives us the number of mismatch, would drastically the number of marks, while still providing some important informations. We only need to remove all measures from Columns & Rows to replace them by our Prediction Matching calculation. This new visualization will load in a few seconds:" }, { "code": null, "e": 18240, "s": 18049, "text": "Last but not least, we would like to understand how the number of iterations of our MLP training impacts our results. This will require us to use another cool feature of Tableau: Parameters." }, { "code": null, "e": 18471, "s": 18240, "text": "We start by updating our predictor function in the notebook, adding a new optional variable that will train (again) our MLP. We only need to cache the result to avoid training with the same number of iterations at each invocation:" }, { "code": null, "e": 19261, "s": 18471, "text": "from sklearn.neural_network import MLPClassifierlast_max_iter = 0clf = Nonedef train(request_max_iter): global clf, last_max_iter if not clf or last_max_iter != request_max_iter: clf = MLPClassifier(max_iter=request_max_iter, random_state=1).fit(iris.data, iris.target) last_max_iter = request_max_iter return clfdef predictor(sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, request_max_iter=1000): clf = train(request_max_iter) # We now train as needed class_predict = clf.predict([[sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm]]) return iris.target_names[class_predict][0]functions = jupytab.Functions()functions['predict'] = jupytab.Function('A predictor for the Iris DataSet', predictor)predictor(0.5, 5, 4, 2)" }, { "code": null, "e": 19283, "s": 19261, "text": "[Output]: ‘virginica’" }, { "code": null, "e": 19381, "s": 19283, "text": "Do not forget to restart the kernel in Tableau through the Jupytab UI so as to apply the changes." }, { "code": null, "e": 19548, "s": 19381, "text": "On the Tableau side, we will create a parameter with a range from 10 to 1000 in order to visualize the impact of the number of training iterations on our predictions:" }, { "code": null, "e": 19588, "s": 19548, "text": "We then add this parameter to our view:" }, { "code": null, "e": 19671, "s": 19588, "text": "We can now dynamically change the maximum number of training iteration of our MLP:" }, { "code": null, "e": 19753, "s": 19671, "text": "We also need to update the Iris Predictor calculation and add this new parameter:" }, { "code": null, "e": 19907, "s": 19753, "text": "SCRIPT_STR(\"JupytabSimulator.predict\", AVG([Sepal Length Cm]), AVG([Sepal Width Cm]), AVG([Petal Length Cm]), AVG([Petal Width Cm]), [MLP Max Iteration])" }, { "code": null, "e": 20012, "s": 19907, "text": "Just after clicking on apply, the result is immediately updated with our default value of 10 iterations." }, { "code": null, "e": 20039, "s": 20012, "text": "MLP Training 10 Iterations" }, { "code": null, "e": 20067, "s": 20039, "text": "MLP Training 100 Iterations" }, { "code": null, "e": 20220, "s": 20067, "text": "Tableau is a very powerful tool for data visualization. Using Jupyter notebooks to compute data and get an almost immediate feedback is very convenient." }, { "code": null, "e": 20393, "s": 20220, "text": "We have barely scratched the surface of Tableau features, and there is almost no limit to the kind of visualisations and interactions that you may create in your dashboard." }, { "code": null, "e": 20476, "s": 20393, "text": "The Jupytab project is open source and accessible on GitHub under the MIT license." }, { "code": null, "e": 20549, "s": 20476, "text": "You can also peruse online many impressive dashboards done with Tableau." }, { "code": null, "e": 20751, "s": 20549, "text": "This is the first project I have ever published on GitHub and it would probably never have left my computer without the strong support of CFM‘s Open-Source Program and the help of people working there." } ]
Program to convert given Matrix to a Diagonal Matrix in C++
Given with the matrix of size nxn the task it to convert any type of given matrix to a diagonal matrix. Diagonal matrix is the nxn matrix whose all the non-diagonal elements are zero and diagonal elements can be any value. Given below is the diagram of converting non-diagonal elements to 0. [123456789]→[103050709] The approach is to start one loop for all non-diagonal elements and another loop for diagonal elements and replace the value of non-diagonals with zero and leave diagonals elements unchanged. Input-: matrix[3][3] = {{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }} Output-: {{ 1, 0, 3}, { 0, 5, 0}, { 7, 0, 9}} Input-: matrix[3][3] = {{ 91, 32, 23 }, { 40, 51, 26 }, { 72, 81, 93 }} Output-: {{ 91, 0, 23}, { 0, 51, 0}, { 72, 0, 93}} Start Step 1-> define macro for matrix size as const int n = 10 Step 2-> Declare function for converting to diagonal matrix void diagonal(int arr[][n], int a, int m) Loop For int i = 0 i < a i++ Loop For int j = 0 j < m j++ IF i != j & i + j + 1 != a Set arr[i][j] = 0 End End End Loop For int i = 0 i < a i++ Loop For int j = 0 j < m j++ Print arr[i][j] End Print \n End Step 2-> In main() Declare matrix as int arr[][n] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } Call function as diagonal(arr, 3, 3) Stop Live Demo #include <iostream> using namespace std; const int n = 10; //print 0 at diagonals in matrix of nxn void diagonal(int arr[][n], int a, int m) { for (int i = 0; i < a; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != a) arr[i][j] = 0; } } for (int i = 0; i < a; i++) { for (int j = 0; j < m; j++) { cout << arr[i][j] << " "; } cout << endl; } } int main() { int arr[][n] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; diagonal(arr, 3, 3); return 0; } IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT 0 2 0 4 0 6 0 8 0
[ { "code": null, "e": 1166, "s": 1062, "text": "Given with the matrix of size nxn the task it to convert any type of given matrix to a diagonal matrix." }, { "code": null, "e": 1285, "s": 1166, "text": "Diagonal matrix is the nxn matrix whose all the non-diagonal elements are zero and diagonal elements can be any value." }, { "code": null, "e": 1354, "s": 1285, "text": "Given below is the diagram of converting non-diagonal elements to 0." }, { "code": null, "e": 1378, "s": 1354, "text": "[123456789]→[103050709]" }, { "code": null, "e": 1570, "s": 1378, "text": "The approach is to start one loop for all non-diagonal elements and another loop for diagonal elements and replace the value of non-diagonals with zero and leave diagonals elements unchanged." }, { "code": null, "e": 1826, "s": 1570, "text": "Input-: matrix[3][3] = {{ 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 }}\nOutput-: {{ 1, 0, 3},\n { 0, 5, 0},\n { 7, 0, 9}}\nInput-: matrix[3][3] = {{ 91, 32, 23 },\n { 40, 51, 26 },\n { 72, 81, 93 }}\nOutput-: {{ 91, 0, 23},\n { 0, 51, 0},\n { 72, 0, 93}}" }, { "code": null, "e": 2475, "s": 1826, "text": "Start\nStep 1-> define macro for matrix size as const int n = 10\nStep 2-> Declare function for converting to diagonal matrix\n void diagonal(int arr[][n], int a, int m)\n Loop For int i = 0 i < a i++\n Loop For int j = 0 j < m j++\n IF i != j & i + j + 1 != a\n Set arr[i][j] = 0\n End\n End\n End\n Loop For int i = 0 i < a i++\n Loop For int j = 0 j < m j++\n Print arr[i][j]\n End\n Print \\n\n End\nStep 2-> In main()\n Declare matrix as int arr[][n] = { { 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 } }\n Call function as diagonal(arr, 3, 3)\nStop" }, { "code": null, "e": 2486, "s": 2475, "text": " Live Demo" }, { "code": null, "e": 3038, "s": 2486, "text": "#include <iostream>\nusing namespace std;\nconst int n = 10;\n//print 0 at diagonals in matrix of nxn\nvoid diagonal(int arr[][n], int a, int m) {\n for (int i = 0; i < a; i++) {\n for (int j = 0; j < m; j++) {\n if (i != j && i + j + 1 != a)\n arr[i][j] = 0;\n }\n }\n for (int i = 0; i < a; i++) {\n for (int j = 0; j < m; j++) {\n cout << arr[i][j] << \" \";\n }\n cout << endl;\n }\n}\nint main() {\n int arr[][n] = { { 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 } };\n diagonal(arr, 3, 3);\n return 0;\n}" }, { "code": null, "e": 3097, "s": 3038, "text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT" }, { "code": null, "e": 3115, "s": 3097, "text": "0 2 0\n4 0 6\n0 8 0" } ]
Tk - Button Widget
Tk button widget is a clickable widget that triggers an action. The syntax for button widget is shown below − button buttonName options The options available for the button widget are listed below in table − -font fontDescriptor Used to set font for widget. -height number Used to set height for widget. -command action Sets the command action for button. -text text Sets the text for the widget. -width number Sets the width for widget. A simple button widget is shown below − #!/usr/bin/wish grid [label .myLabel -text "Click the buttons" -textvariable labelText] grid [button .myButton1 -text "Button 1" -font {Helvetica -18 bold} -height 5 -width 10 -command "set labelText clicked_top_btn"] grid [button .myButton2 -text "Button 2" -font {Helvetica -18 bold} -height 5 -width 10 -command "set labelText clicked_bottom_btn"] When we run the above program, we will get the following output − When we click the Button1, we will get the following output − When we click the Button2, we will get the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2311, "s": 2201, "text": "Tk button widget is a clickable widget that triggers an action. The syntax for button widget is shown below −" }, { "code": null, "e": 2338, "s": 2311, "text": "button buttonName options\n" }, { "code": null, "e": 2410, "s": 2338, "text": "The options available for the button widget are listed below in table −" }, { "code": null, "e": 2431, "s": 2410, "text": "-font fontDescriptor" }, { "code": null, "e": 2460, "s": 2431, "text": "Used to set font for widget." }, { "code": null, "e": 2475, "s": 2460, "text": "-height number" }, { "code": null, "e": 2506, "s": 2475, "text": "Used to set height for widget." }, { "code": null, "e": 2522, "s": 2506, "text": "-command action" }, { "code": null, "e": 2558, "s": 2522, "text": "Sets the command action for button." }, { "code": null, "e": 2569, "s": 2558, "text": "-text text" }, { "code": null, "e": 2599, "s": 2569, "text": "Sets the text for the widget." }, { "code": null, "e": 2613, "s": 2599, "text": "-width number" }, { "code": null, "e": 2640, "s": 2613, "text": "Sets the width for widget." }, { "code": null, "e": 2680, "s": 2640, "text": "A simple button widget is shown below −" }, { "code": null, "e": 3040, "s": 2680, "text": "#!/usr/bin/wish\n\ngrid [label .myLabel -text \"Click the buttons\" -textvariable labelText]\ngrid [button .myButton1 -text \"Button 1\" -font {Helvetica -18 bold} -height 5 -width 10\n -command \"set labelText clicked_top_btn\"]\ngrid [button .myButton2 -text \"Button 2\" -font {Helvetica -18 bold} -height 5 -width 10\n -command \"set labelText clicked_bottom_btn\"]" }, { "code": null, "e": 3106, "s": 3040, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 3168, "s": 3106, "text": "When we click the Button1, we will get the following output −" }, { "code": null, "e": 3230, "s": 3168, "text": "When we click the Button2, we will get the following output −" }, { "code": null, "e": 3237, "s": 3230, "text": " Print" }, { "code": null, "e": 3248, "s": 3237, "text": " Add Notes" } ]
Get the index of maximum value in DataFrame column - GeeksforGeeks
01 Nov, 2021 Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we get the index of maximum value in DataFrame column.Observe this dataset first. We’ll use ‘Weight’ and ‘Salary’ columns of this data in order to get the index of maximum values from a particular column in Pandas DataFrame. Python3 # importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") df.head(10) Code #1: Check the index at which maximum weight value is present. Python3 # importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv("nba.csv") # Returns index of maximum weightdf[['Weight']].idxmax() Output: We can verify whether the maximum value is present in index or not. Python3 # importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv("nba.csv") # from index 400 to 409df.iloc[400:410] Output: Code #2: Let’s insert a new row at index 0, having maximum salary and then verify. Python3 # importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv("nba.csv") new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':999999999} , index=[0]) df = pd.concat([new_row, df]).reset_index(drop=True)df.head(5) Output: Now, let’s check if the maximum salary is present at index 0 or not. Python3 # Returns index of minimum salarydf[['Salary']].idxmax() Output: prachisoda1234 pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26173, "s": 26145, "text": "\n01 Nov, 2021" }, { "code": null, "e": 26554, "s": 26173, "text": "Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let’s see how can we get the index of maximum value in DataFrame column.Observe this dataset first. We’ll use ‘Weight’ and ‘Salary’ columns of this data in order to get the index of maximum values from a particular column in Pandas DataFrame. " }, { "code": null, "e": 26562, "s": 26554, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") df.head(10)", "e": 26719, "s": 26562, "text": null }, { "code": null, "e": 26788, "s": 26719, "text": "Code #1: Check the index at which maximum weight value is present. " }, { "code": null, "e": 26796, "s": 26788, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv(\"nba.csv\") # Returns index of maximum weightdf[['Weight']].idxmax()", "e": 26947, "s": 26796, "text": null }, { "code": null, "e": 26957, "s": 26947, "text": "Output: " }, { "code": null, "e": 27027, "s": 26957, "text": "We can verify whether the maximum value is present in index or not. " }, { "code": null, "e": 27035, "s": 27027, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv(\"nba.csv\") # from index 400 to 409df.iloc[400:410]", "e": 27171, "s": 27035, "text": null }, { "code": null, "e": 27181, "s": 27171, "text": "Output: " }, { "code": null, "e": 27268, "s": 27181, "text": " Code #2: Let’s insert a new row at index 0, having maximum salary and then verify. " }, { "code": null, "e": 27276, "s": 27268, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data framedf = pd.read_csv(\"nba.csv\") new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3, 'Position':'PG', 'Age':33, 'Height':'6-2', 'Weight':189, 'College':'MIT', 'Salary':999999999} , index=[0]) df = pd.concat([new_row, df]).reset_index(drop=True)df.head(5)", "e": 27681, "s": 27276, "text": null }, { "code": null, "e": 27691, "s": 27681, "text": "Output: " }, { "code": null, "e": 27762, "s": 27691, "text": "Now, let’s check if the maximum salary is present at index 0 or not. " }, { "code": null, "e": 27770, "s": 27762, "text": "Python3" }, { "code": "# Returns index of minimum salarydf[['Salary']].idxmax()", "e": 27827, "s": 27770, "text": null }, { "code": null, "e": 27837, "s": 27827, "text": "Output: " }, { "code": null, "e": 27854, "s": 27839, "text": "prachisoda1234" }, { "code": null, "e": 27879, "s": 27854, "text": "pandas-dataframe-program" }, { "code": null, "e": 27903, "s": 27879, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27917, "s": 27903, "text": "Python-pandas" }, { "code": null, "e": 27924, "s": 27917, "text": "Python" }, { "code": null, "e": 28022, "s": 27924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28040, "s": 28022, "text": "Python Dictionary" }, { "code": null, "e": 28072, "s": 28040, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28094, "s": 28072, "text": "Enumerate() in Python" }, { "code": null, "e": 28136, "s": 28094, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28166, "s": 28136, "text": "Iterate over a list in Python" }, { "code": null, "e": 28192, "s": 28166, "text": "Python String | replace()" }, { "code": null, "e": 28221, "s": 28192, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28265, "s": 28221, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28302, "s": 28265, "text": "Create a Pandas DataFrame from Lists" } ]
Maximum OR value of a pair in an array - GeeksforGeeks
20 May, 2021 Given an array arr[] of N positive elements. The task is to find the maximum bitwise OR value of a pair from the given array.Examples: Input: arr[] = {4, 8, 12, 16} Output: 28 (12, 16) is the pair with the maximum bitwise OR. 12 | 16 = 28 Input: arr[] = {4, 8, 16, 2} Output: 24 Approach: Iterate over all the possible pairs and calculate the OR value of these pairs. Finally, print the maximum of all the values. 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; // Function to return the maximum bitwise OR// for any pair of the given arrayint maxOR(int arr[], int n){ // To store the maximum OR value int maxVal = 0; // For every possible pair for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = max(maxVal, arr[i] | arr[j]); } return maxVal;} // Driver codeint main(){ int arr[] = { 4, 8, 12, 16 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxOR(arr, n); return 0;} // Java implementation of the approachclass GFG { // Function to return the maximum bitwise OR // for any pair of the given array static int maxOR(int arr[], int n) { // To store the maximum OR value int maxVal = 0; // For every possible pair for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = Math.max(maxVal, arr[i] | arr[j]); } return maxVal; } // Driver code public static void main(String[] args) { int arr[] = { 4, 8, 12, 16 }; int n = arr.length; System.out.println(maxOR(arr, n)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the maximum bitwise OR# for any pair of the given arraydef maxOR(arr, n): # To store the maximum OR value maxVal = 0; # For every possible pair for i in range(n - 1): for j in range(i + 1, n): # Update the maximum OR value maxVal = max(maxVal, arr[i] | arr[j]); return maxVal; # Driver codeif __name__ == '__main__': arr = [4, 8, 12, 16]; n = len(arr); print(maxOR(arr, n)); # This code is contributed by 29AjayKumar // C# implementation of the approachusing System; class GFG { // Function to return the maximum bitwise OR // for any pair of the given array static int maxOR(int[] arr, int n) { // To store the maximum OR value int maxVal = 0; // For every possible pair for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = Math.Max(maxVal, arr[i] | arr[j]); } return maxVal; } // Driver code static public void Main() { int[] arr = { 4, 8, 12, 16 }; int n = arr.Length; Console.Write(maxOR(arr, n)); }} // This code is contributed by ajit. <script> // Javascript implementation of the approach // Function to return the maximum bitwise OR // for any pair of the given array function maxOR(arr, n) { // To store the maximum OR value let maxVal = 0; // For every possible pair for (let i = 0; i < n - 1; i++) for (let j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = Math.max(maxVal, arr[i] | arr[j]); } return maxVal; } let arr = [ 4, 8, 12, 16 ]; let n = arr.length; document.write(maxOR(arr, n));</script> 28 Efficient Approach: As we have to find such a pair that will give maximum OR value i.e, our output must have set bits such that it will form the maximum OR value pair. For this we will find maximum element in our array as it has set bits arrangement contributing in maximum value and hence we only have to find maximum OR value with maximum array element, as there must be a pair giving max OR value where one element is the maximum array element. C++ Java Python3 C# Javascript // C++ implementation of the approach ( Linear time Complexity ) #include <bits/stdc++.h>using namespace std; // Function to return the maximum bitwise OR// for any pair of the given array// in O(n) time complexity.int maxOR(int arr[], int n){ // find maximum element in the array int max_value = *max_element(arr, arr + n); // To store the maximum OR value int ans = 0; // iterate over rest array elements and find maximum OR value pair for (int i = 0; i < n; i++) { ans = max(ans, (max_value | arr[i])); } return ans;} // Driver codeint main(){ int arr[] = { 3, 6, 8, 16 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxOR(arr, n); return 0;} // Java implementation of the approach// (Linear time Complexity)import java.util.Arrays; class GFG{ // Function to return the maximum bitwise// OR for any pair of the given array// in O(n) time complexity.public static int maxOR(int[] arr, int n){ // Find maximum element in the array int max_value = Arrays.stream(arr).max().getAsInt(); // To store the maximum OR value int ans = 0; // Iterate over rest array elements and // find maximum OR value pair for(int i = 0; i < n; i++) { ans = Math.max(ans, (max_value | arr[i])); } return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 6, 8, 16 }; int n = arr.length; System.out.print(maxOR(arr, n));}} // This code is contributed by divyeshrabadiya07 # Python3 implementation of the approach# (Linear time Complexity) # Function to return the maximum bitwise# OR for any pair of the given arraydef maxOR(arr, n): # To store the maximum element # of the array maxVal = max(arr) # To store the maximum OR value ans = 0 # Iterate over rest array elements and # find maximum OR value pair for i in range(n - 1): # Update the maximum OR value ans = max(ans, maxVal | arr[i]) return ans # Driver codeif __name__ == '__main__': arr = [ 3, 6, 8, 16 ] n = len(arr) print(maxOR(arr, n)) # This code is contributed by math_lover // C# implementation of the approach// (Linear time Complexity)using System;using System.Linq; class GFG{ // Function to return the maximum bitwise// OR for any pair of the given array// in O(n) time complexity.static int maxOR(int []arr, int n){ // Find maximum element in the array int max_value = arr.Max(); // To store the maximum OR value int ans = 0; // Iterate over rest array elements and // find maximum OR value pair for(int i = 0; i < n; i++) { ans = Math.Max(ans, (max_value | arr[i])); } return ans;} // Driver codepublic static void Main(String[] args){ int []arr = { 3, 6, 8, 16 }; int n = arr.Length; Console.Write(maxOR(arr, n));}} // This code is contributed by doreamon_ <script> // Javascript implementation of the approach // (Linear time Complexity) // Function to return the maximum bitwise // OR for any pair of the given array // in O(n) time complexity. function maxOR(arr, n) { // Find maximum element in the array let max_value = Number.MIN_VALUE; for(let i = 0; i < n; i++) { max_value = Math.max(max_value, arr[i]); } // To store the maximum OR value let ans = 0; // Iterate over rest array elements and // find maximum OR value pair for(let i = 0; i < n; i++) { ans = Math.max(ans, (max_value | arr[i])); } return ans; } let arr = [ 3, 6, 8, 16 ]; let n = arr.length; document.write(maxOR(arr, n)); </script> Output: 24 Time Complexity: O(n) ankthon jit_t 29AjayKumar yomad_ divyeshrabadiya07 math_lover doreamon_ suresh07 divyesh072019 Bitwise-OR Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26070, "s": 26042, "text": "\n20 May, 2021" }, { "code": null, "e": 26206, "s": 26070, "text": "Given an array arr[] of N positive elements. The task is to find the maximum bitwise OR value of a pair from the given array.Examples: " }, { "code": null, "e": 26310, "s": 26206, "text": "Input: arr[] = {4, 8, 12, 16} Output: 28 (12, 16) is the pair with the maximum bitwise OR. 12 | 16 = 28" }, { "code": null, "e": 26351, "s": 26310, "text": "Input: arr[] = {4, 8, 16, 2} Output: 24 " }, { "code": null, "e": 26486, "s": 26351, "text": "Approach: Iterate over all the possible pairs and calculate the OR value of these pairs. Finally, print the maximum of all the values." }, { "code": null, "e": 26538, "s": 26486, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26542, "s": 26538, "text": "C++" }, { "code": null, "e": 26547, "s": 26542, "text": "Java" }, { "code": null, "e": 26555, "s": 26547, "text": "Python3" }, { "code": null, "e": 26558, "s": 26555, "text": "C#" }, { "code": null, "e": 26569, "s": 26558, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum bitwise OR// for any pair of the given arrayint maxOR(int arr[], int n){ // To store the maximum OR value int maxVal = 0; // For every possible pair for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = max(maxVal, arr[i] | arr[j]); } return maxVal;} // Driver codeint main(){ int arr[] = { 4, 8, 12, 16 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxOR(arr, n); return 0;}", "e": 27185, "s": 26569, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the maximum bitwise OR // for any pair of the given array static int maxOR(int arr[], int n) { // To store the maximum OR value int maxVal = 0; // For every possible pair for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = Math.max(maxVal, arr[i] | arr[j]); } return maxVal; } // Driver code public static void main(String[] args) { int arr[] = { 4, 8, 12, 16 }; int n = arr.length; System.out.println(maxOR(arr, n)); }} // This code is contributed by AnkitRai01", "e": 27916, "s": 27185, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum bitwise OR# for any pair of the given arraydef maxOR(arr, n): # To store the maximum OR value maxVal = 0; # For every possible pair for i in range(n - 1): for j in range(i + 1, n): # Update the maximum OR value maxVal = max(maxVal, arr[i] | arr[j]); return maxVal; # Driver codeif __name__ == '__main__': arr = [4, 8, 12, 16]; n = len(arr); print(maxOR(arr, n)); # This code is contributed by 29AjayKumar", "e": 28469, "s": 27916, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG { // Function to return the maximum bitwise OR // for any pair of the given array static int maxOR(int[] arr, int n) { // To store the maximum OR value int maxVal = 0; // For every possible pair for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = Math.Max(maxVal, arr[i] | arr[j]); } return maxVal; } // Driver code static public void Main() { int[] arr = { 4, 8, 12, 16 }; int n = arr.Length; Console.Write(maxOR(arr, n)); }} // This code is contributed by ajit.", "e": 29189, "s": 28469, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum bitwise OR // for any pair of the given array function maxOR(arr, n) { // To store the maximum OR value let maxVal = 0; // For every possible pair for (let i = 0; i < n - 1; i++) for (let j = i + 1; j < n; j++) { // Update the maximum OR value maxVal = Math.max(maxVal, arr[i] | arr[j]); } return maxVal; } let arr = [ 4, 8, 12, 16 ]; let n = arr.length; document.write(maxOR(arr, n));</script>", "e": 29807, "s": 29189, "text": null }, { "code": null, "e": 29810, "s": 29807, "text": "28" }, { "code": null, "e": 30260, "s": 29812, "text": "Efficient Approach: As we have to find such a pair that will give maximum OR value i.e, our output must have set bits such that it will form the maximum OR value pair. For this we will find maximum element in our array as it has set bits arrangement contributing in maximum value and hence we only have to find maximum OR value with maximum array element, as there must be a pair giving max OR value where one element is the maximum array element." }, { "code": null, "e": 30264, "s": 30260, "text": "C++" }, { "code": null, "e": 30269, "s": 30264, "text": "Java" }, { "code": null, "e": 30277, "s": 30269, "text": "Python3" }, { "code": null, "e": 30280, "s": 30277, "text": "C#" }, { "code": null, "e": 30291, "s": 30280, "text": "Javascript" }, { "code": "// C++ implementation of the approach ( Linear time Complexity ) #include <bits/stdc++.h>using namespace std; // Function to return the maximum bitwise OR// for any pair of the given array// in O(n) time complexity.int maxOR(int arr[], int n){ // find maximum element in the array int max_value = *max_element(arr, arr + n); // To store the maximum OR value int ans = 0; // iterate over rest array elements and find maximum OR value pair for (int i = 0; i < n; i++) { ans = max(ans, (max_value | arr[i])); } return ans;} // Driver codeint main(){ int arr[] = { 3, 6, 8, 16 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxOR(arr, n); return 0;}", "e": 30986, "s": 30291, "text": null }, { "code": "// Java implementation of the approach// (Linear time Complexity)import java.util.Arrays; class GFG{ // Function to return the maximum bitwise// OR for any pair of the given array// in O(n) time complexity.public static int maxOR(int[] arr, int n){ // Find maximum element in the array int max_value = Arrays.stream(arr).max().getAsInt(); // To store the maximum OR value int ans = 0; // Iterate over rest array elements and // find maximum OR value pair for(int i = 0; i < n; i++) { ans = Math.max(ans, (max_value | arr[i])); } return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 6, 8, 16 }; int n = arr.length; System.out.print(maxOR(arr, n));}} // This code is contributed by divyeshrabadiya07", "e": 31783, "s": 30986, "text": null }, { "code": "# Python3 implementation of the approach# (Linear time Complexity) # Function to return the maximum bitwise# OR for any pair of the given arraydef maxOR(arr, n): # To store the maximum element # of the array maxVal = max(arr) # To store the maximum OR value ans = 0 # Iterate over rest array elements and # find maximum OR value pair for i in range(n - 1): # Update the maximum OR value ans = max(ans, maxVal | arr[i]) return ans # Driver codeif __name__ == '__main__': arr = [ 3, 6, 8, 16 ] n = len(arr) print(maxOR(arr, n)) # This code is contributed by math_lover", "e": 32445, "s": 31783, "text": null }, { "code": "// C# implementation of the approach// (Linear time Complexity)using System;using System.Linq; class GFG{ // Function to return the maximum bitwise// OR for any pair of the given array// in O(n) time complexity.static int maxOR(int []arr, int n){ // Find maximum element in the array int max_value = arr.Max(); // To store the maximum OR value int ans = 0; // Iterate over rest array elements and // find maximum OR value pair for(int i = 0; i < n; i++) { ans = Math.Max(ans, (max_value | arr[i])); } return ans;} // Driver codepublic static void Main(String[] args){ int []arr = { 3, 6, 8, 16 }; int n = arr.Length; Console.Write(maxOR(arr, n));}} // This code is contributed by doreamon_", "e": 33193, "s": 32445, "text": null }, { "code": "<script> // Javascript implementation of the approach // (Linear time Complexity) // Function to return the maximum bitwise // OR for any pair of the given array // in O(n) time complexity. function maxOR(arr, n) { // Find maximum element in the array let max_value = Number.MIN_VALUE; for(let i = 0; i < n; i++) { max_value = Math.max(max_value, arr[i]); } // To store the maximum OR value let ans = 0; // Iterate over rest array elements and // find maximum OR value pair for(let i = 0; i < n; i++) { ans = Math.max(ans, (max_value | arr[i])); } return ans; } let arr = [ 3, 6, 8, 16 ]; let n = arr.length; document.write(maxOR(arr, n)); </script>", "e": 34008, "s": 33193, "text": null }, { "code": null, "e": 34016, "s": 34008, "text": "Output:" }, { "code": null, "e": 34019, "s": 34016, "text": "24" }, { "code": null, "e": 34042, "s": 34019, "text": "Time Complexity: O(n) " }, { "code": null, "e": 34050, "s": 34042, "text": "ankthon" }, { "code": null, "e": 34056, "s": 34050, "text": "jit_t" }, { "code": null, "e": 34068, "s": 34056, "text": "29AjayKumar" }, { "code": null, "e": 34075, "s": 34068, "text": "yomad_" }, { "code": null, "e": 34093, "s": 34075, "text": "divyeshrabadiya07" }, { "code": null, "e": 34104, "s": 34093, "text": "math_lover" }, { "code": null, "e": 34114, "s": 34104, "text": "doreamon_" }, { "code": null, "e": 34123, "s": 34114, "text": "suresh07" }, { "code": null, "e": 34137, "s": 34123, "text": "divyesh072019" }, { "code": null, "e": 34148, "s": 34137, "text": "Bitwise-OR" }, { "code": null, "e": 34155, "s": 34148, "text": "Arrays" }, { "code": null, "e": 34162, "s": 34155, "text": "Arrays" }, { "code": null, "e": 34260, "s": 34162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34328, "s": 34260, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34372, "s": 34328, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34420, "s": 34372, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34443, "s": 34420, "text": "Introduction to Arrays" }, { "code": null, "e": 34475, "s": 34443, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34489, "s": 34475, "text": "Linear Search" }, { "code": null, "e": 34510, "s": 34489, "text": "Linked List vs Array" }, { "code": null, "e": 34595, "s": 34510, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34640, "s": 34595, "text": "Python | Using 2D arrays/lists the right way" } ]
Finding Login Counts and Creation Dates in SQL Server - GeeksforGeeks
11 Jun, 2021 A SQL login is another credential that allows you to access SQL Server. When you log on to Windows or even your e-mail account, for example, you enter your username and password. The logins are made up of such a username and password. As a result, SQL logins are just a username and password. A SQL login is a security principal that applies to the whole SQL Server instance, which can contain many databases. Windows authenticated login and SQL Server authenticated login are the two basic forms of login. We usually require access to a specific database once we have joined SQL Server. This login must be mapped to a database user in order to gain access to the database. A login is mapped and identified to a user using a security identifier within SQL Server (SID). There are four different types of logins available in SQL Server: Windows credentials are used to log in. A SQL Server-specific login. A login that is associated with a certificate. A symmetric key is mapped to a logon. Refer Create Login in SQL Server to find out how to create a login. How can I find out how many logins and when they were built in a SQL Server database?Several SQL Server queries that return information about logins are mentioned below. You may use the following question to determine the number of logins on your SQL Server: SELECT COUNT(*) FROM master..syslogins GO Running the above query in SQL Server Management Studio : To get a list of logins on your server as well as the date they were created, run the following query: SELECT name, createdate FROM master..syslogins GO Running the above query in SQL Server Management Studio : Similarly, you can use the following SQL queries to get the number of users in a database, a list of user names, and the dates the users were created: USE <database_name> GO SELECT COUNT(*) FROM sysusers GO SELECT name, createdate FROM sysusers GO The above-mentioned queries should provide you with the required username and user details. Example – USE SQL_DBA GO SELECT COUNT(*) FROM sysusers SELECT name, createdate FROM sysusers Running the above query in SQL Server Management Studio : DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL | Subquery SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n11 Jun, 2021" }, { "code": null, "e": 25806, "s": 25513, "text": "A SQL login is another credential that allows you to access SQL Server. When you log on to Windows or even your e-mail account, for example, you enter your username and password. The logins are made up of such a username and password. As a result, SQL logins are just a username and password." }, { "code": null, "e": 26020, "s": 25806, "text": "A SQL login is a security principal that applies to the whole SQL Server instance, which can contain many databases. Windows authenticated login and SQL Server authenticated login are the two basic forms of login." }, { "code": null, "e": 26283, "s": 26020, "text": "We usually require access to a specific database once we have joined SQL Server. This login must be mapped to a database user in order to gain access to the database. A login is mapped and identified to a user using a security identifier within SQL Server (SID)." }, { "code": null, "e": 26349, "s": 26283, "text": "There are four different types of logins available in SQL Server:" }, { "code": null, "e": 26389, "s": 26349, "text": "Windows credentials are used to log in." }, { "code": null, "e": 26418, "s": 26389, "text": "A SQL Server-specific login." }, { "code": null, "e": 26465, "s": 26418, "text": "A login that is associated with a certificate." }, { "code": null, "e": 26503, "s": 26465, "text": "A symmetric key is mapped to a logon." }, { "code": null, "e": 26572, "s": 26503, "text": "Refer Create Login in SQL Server to find out how to create a login. " }, { "code": null, "e": 26831, "s": 26572, "text": "How can I find out how many logins and when they were built in a SQL Server database?Several SQL Server queries that return information about logins are mentioned below. You may use the following question to determine the number of logins on your SQL Server:" }, { "code": null, "e": 26875, "s": 26831, "text": "SELECT COUNT(*)\n FROM master..syslogins\nGO" }, { "code": null, "e": 26934, "s": 26875, "text": "Running the above query in SQL Server Management Studio : " }, { "code": null, "e": 27037, "s": 26934, "text": "To get a list of logins on your server as well as the date they were created, run the following query:" }, { "code": null, "e": 27089, "s": 27037, "text": "SELECT name, createdate\n FROM master..syslogins\nGO" }, { "code": null, "e": 27148, "s": 27089, "text": "Running the above query in SQL Server Management Studio : " }, { "code": null, "e": 27299, "s": 27148, "text": "Similarly, you can use the following SQL queries to get the number of users in a database, a list of user names, and the dates the users were created:" }, { "code": null, "e": 27400, "s": 27299, "text": "USE <database_name>\nGO\nSELECT COUNT(*)\n FROM sysusers\nGO\nSELECT name, createdate\n FROM sysusers\nGO" }, { "code": null, "e": 27492, "s": 27400, "text": "The above-mentioned queries should provide you with the required username and user details." }, { "code": null, "e": 27503, "s": 27492, "text": "Example – " }, { "code": null, "e": 27586, "s": 27503, "text": "USE SQL_DBA\nGO\nSELECT COUNT(*)\nFROM sysusers\nSELECT name, createdate\nFROM sysusers" }, { "code": null, "e": 27645, "s": 27586, "text": "Running the above query in SQL Server Management Studio : " }, { "code": null, "e": 27654, "s": 27645, "text": "DBMS-SQL" }, { "code": null, "e": 27665, "s": 27654, "text": "SQL-Server" }, { "code": null, "e": 27669, "s": 27665, "text": "SQL" }, { "code": null, "e": 27673, "s": 27669, "text": "SQL" }, { "code": null, "e": 27771, "s": 27673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27837, "s": 27771, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27894, "s": 27837, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27926, "s": 27894, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27941, "s": 27926, "text": "SQL | Subquery" }, { "code": null, "e": 28019, "s": 27941, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28055, "s": 28019, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 28072, "s": 28055, "text": "SQL using Python" }, { "code": null, "e": 28138, "s": 28072, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 28200, "s": 28138, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Convert a series of date strings to a time series in Pandas Dataframe - GeeksforGeeks
18 Aug, 2020 During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized for converting a series of date strings to a time series. Let’s see some examples:Example 1: Python3 # import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['28 July 2020', '16 January 2013', '29 February 2016 18:14']) # display the series initiallyprint("Series of date strings:")print(dt_series) # display the series after being # converted to a time seriesprint("\nSeries of date strings after" + " being converted to a timeseries:") print(pd.to_datetime(dt_series)) Output: Example 2: Python3 # import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['2020/07/28', '2013/01/16', '2016/02/29 18:14']) # display the series initiallyprint("Series of date strings:")print(dt_series) # display the series after being# converted to a time seriesprint("\nSeries of date strings after " + "being converted to a timeseries:") print(pd.to_datetime(dt_series)) Output: Example 3: Python3 # import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['2020-07-28', '2013-01-16', '2016-02-29 18:14']) # display the series initiallyprint("Series of date strings:")print(dt_series) # display the series after # being converted to a time seriesprint("\nSeries of date strings after " + "being converted to a timeseries:") print(pd.to_datetime(dt_series)) Output: Example 4: Python3 # import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['28/07/2020', '01/16/2013', '29/02/2016 18:14']) # display the series initiallyprint("Series of date strings:")print(dt_series) # display the series after being# converted to a time seriesprint("\nSeries of date strings after " + "being converted to a timeseries:") print(pd.to_datetime(dt_series)) Output: Example 5: Python3 # import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['20200728', '20130116', '20160229 181431']) # display the series initiallyprint("Series of date strings:")print(dt_series) # display the series after # being converted to a time seriesprint("\nSeries of date strings after " + "being converted to a timeseries:") print(pd.to_datetime(dt_series)) Output: Example 6: Python3 # import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['28 July 2020', '2013-01-16', '20160229 18:14', '5/03/2019 2215', '20151204 09:23']) # display the series initiallyprint("Series of date strings:")print(dt_series) # display the series after # being converted to a time seriesprint("\nSeries of date strings after " + "being converted to a timeseries:") print(pd.to_datetime(dt_series)) Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25669, "s": 25641, "text": "\n18 Aug, 2020" }, { "code": null, "e": 25909, "s": 25669, "text": "During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. " }, { "code": null, "e": 26079, "s": 25909, "text": "pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized for converting a series of date strings to a time series." }, { "code": null, "e": 26115, "s": 26079, "text": "Let’s see some examples:Example 1: " }, { "code": null, "e": 26123, "s": 26115, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['28 July 2020', '16 January 2013', '29 February 2016 18:14']) # display the series initiallyprint(\"Series of date strings:\")print(dt_series) # display the series after being # converted to a time seriesprint(\"\\nSeries of date strings after\" + \" being converted to a timeseries:\") print(pd.to_datetime(dt_series))", "e": 26568, "s": 26123, "text": null }, { "code": null, "e": 26577, "s": 26568, "text": "Output: " }, { "code": null, "e": 26589, "s": 26577, "text": "Example 2: " }, { "code": null, "e": 26597, "s": 26589, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['2020/07/28', '2013/01/16', '2016/02/29 18:14']) # display the series initiallyprint(\"Series of date strings:\")print(dt_series) # display the series after being# converted to a time seriesprint(\"\\nSeries of date strings after \" + \"being converted to a timeseries:\") print(pd.to_datetime(dt_series))", "e": 27027, "s": 26597, "text": null }, { "code": null, "e": 27036, "s": 27027, "text": "Output: " }, { "code": null, "e": 27048, "s": 27036, "text": "Example 3: " }, { "code": null, "e": 27056, "s": 27048, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['2020-07-28', '2013-01-16', '2016-02-29 18:14']) # display the series initiallyprint(\"Series of date strings:\")print(dt_series) # display the series after # being converted to a time seriesprint(\"\\nSeries of date strings after \" + \"being converted to a timeseries:\") print(pd.to_datetime(dt_series))", "e": 27487, "s": 27056, "text": null }, { "code": null, "e": 27496, "s": 27487, "text": "Output: " }, { "code": null, "e": 27508, "s": 27496, "text": "Example 4: " }, { "code": null, "e": 27516, "s": 27508, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['28/07/2020', '01/16/2013', '29/02/2016 18:14']) # display the series initiallyprint(\"Series of date strings:\")print(dt_series) # display the series after being# converted to a time seriesprint(\"\\nSeries of date strings after \" + \"being converted to a timeseries:\") print(pd.to_datetime(dt_series))", "e": 27946, "s": 27516, "text": null }, { "code": null, "e": 27955, "s": 27946, "text": "Output: " }, { "code": null, "e": 27967, "s": 27955, "text": "Example 5: " }, { "code": null, "e": 27975, "s": 27967, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['20200728', '20130116', '20160229 181431']) # display the series initiallyprint(\"Series of date strings:\")print(dt_series) # display the series after # being converted to a time seriesprint(\"\\nSeries of date strings after \" + \"being converted to a timeseries:\") print(pd.to_datetime(dt_series))", "e": 28401, "s": 27975, "text": null }, { "code": null, "e": 28410, "s": 28401, "text": "Output: " }, { "code": null, "e": 28422, "s": 28410, "text": "Example 6: " }, { "code": null, "e": 28430, "s": 28422, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # create a series of date stringsdt_series = pd.Series(['28 July 2020', '2013-01-16', '20160229 18:14', '5/03/2019 2215', '20151204 09:23']) # display the series initiallyprint(\"Series of date strings:\")print(dt_series) # display the series after # being converted to a time seriesprint(\"\\nSeries of date strings after \" + \"being converted to a timeseries:\") print(pd.to_datetime(dt_series))", "e": 28919, "s": 28430, "text": null }, { "code": null, "e": 28928, "s": 28919, "text": "Output: " }, { "code": null, "e": 28952, "s": 28928, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28975, "s": 28952, "text": "Python Pandas-exercise" }, { "code": null, "e": 28989, "s": 28975, "text": "Python-pandas" }, { "code": null, "e": 28996, "s": 28989, "text": "Python" }, { "code": null, "e": 29094, "s": 28996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29112, "s": 29094, "text": "Python Dictionary" }, { "code": null, "e": 29147, "s": 29112, "text": "Read a file line by line in Python" }, { "code": null, "e": 29179, "s": 29147, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29201, "s": 29179, "text": "Enumerate() in Python" }, { "code": null, "e": 29243, "s": 29201, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29273, "s": 29243, "text": "Iterate over a list in Python" }, { "code": null, "e": 29299, "s": 29273, "text": "Python String | replace()" }, { "code": null, "e": 29328, "s": 29299, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29372, "s": 29328, "text": "Reading and Writing to text files in Python" } ]
Check if the objects or variables are defined in Julia - isdefined() and @isdefined() Methods - GeeksforGeeks
01 Apr, 2020 The isdefined() is an inbuilt function in julia which is used to test whether the specified global variable or object field is defined or not. The passed parameters can be a module and a symbol or a composite object and field name (as a symbol) or index. Syntax:isdefined(m::Module, s::Symbol)orisdefined(object, s::Symbol)orisdefined(object, index::Int) Parameters: m::Module: Specified module. s::Symbol: Specified symbol. object: Specified composite object. index::Int: Specified index. Returns: It returns true for the defined specified global variable or object field else returns false. Example: # Julia program to illustrate # the use of isdefined() method # Getting true for the defined # specified global variable or # object field else returns false.println(isdefined(Base, :sum))println(isdefined(Base, :num))println(isdefined(Base, :NonExistentMethod)) # Initialising a composite type value with # Floor division operatora = 2//3;println(isdefined(a, 1))println(isdefined(a, 2))println(isdefined(a, :num))println(isdefined(a, :numerator)) Output: true true false true true true false The @isdefined() is an inbuilt function in julia which is used to tests whether the specified variable s is defined in the current scope or not. Syntax:@isdefined s Parameters: s: Specified variable. Returns: It returns true if the specified variable s is defined in the current scope else returns false. Example: # Julia program to illustrate # the use of @isdefined() method # Getting true if the specified variable# s is defined in the current scope# else returns false.function f() println(@isdefined x) x = 10 println(@isdefined x) endf (generic function with 1 method)println(f()) Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors 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 Creating array with repeated elements in Julia - repeat() Method Reshaping array dimensions in Julia | Array reshape() Method while loop in Julia Get array dimensions and size of a dimension in Julia - size() Method
[ { "code": null, "e": 25599, "s": 25571, "text": "\n01 Apr, 2020" }, { "code": null, "e": 25854, "s": 25599, "text": "The isdefined() is an inbuilt function in julia which is used to test whether the specified global variable or object field is defined or not. The passed parameters can be a module and a symbol or a composite object and field name (as a symbol) or index." }, { "code": null, "e": 25954, "s": 25854, "text": "Syntax:isdefined(m::Module, s::Symbol)orisdefined(object, s::Symbol)orisdefined(object, index::Int)" }, { "code": null, "e": 25966, "s": 25954, "text": "Parameters:" }, { "code": null, "e": 25995, "s": 25966, "text": "m::Module: Specified module." }, { "code": null, "e": 26024, "s": 25995, "text": "s::Symbol: Specified symbol." }, { "code": null, "e": 26060, "s": 26024, "text": "object: Specified composite object." }, { "code": null, "e": 26089, "s": 26060, "text": "index::Int: Specified index." }, { "code": null, "e": 26192, "s": 26089, "text": "Returns: It returns true for the defined specified global variable or object field else returns false." }, { "code": null, "e": 26201, "s": 26192, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of isdefined() method # Getting true for the defined # specified global variable or # object field else returns false.println(isdefined(Base, :sum))println(isdefined(Base, :num))println(isdefined(Base, :NonExistentMethod)) # Initialising a composite type value with # Floor division operatora = 2//3;println(isdefined(a, 1))println(isdefined(a, 2))println(isdefined(a, :num))println(isdefined(a, :numerator))", "e": 26653, "s": 26201, "text": null }, { "code": null, "e": 26661, "s": 26653, "text": "Output:" }, { "code": null, "e": 26698, "s": 26661, "text": "true\ntrue\nfalse\ntrue\ntrue\ntrue\nfalse" }, { "code": null, "e": 26843, "s": 26698, "text": "The @isdefined() is an inbuilt function in julia which is used to tests whether the specified variable s is defined in the current scope or not." }, { "code": null, "e": 26863, "s": 26843, "text": "Syntax:@isdefined s" }, { "code": null, "e": 26875, "s": 26863, "text": "Parameters:" }, { "code": null, "e": 26898, "s": 26875, "text": "s: Specified variable." }, { "code": null, "e": 27003, "s": 26898, "text": "Returns: It returns true if the specified variable s is defined in the current scope else returns false." }, { "code": null, "e": 27012, "s": 27003, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of @isdefined() method # Getting true if the specified variable# s is defined in the current scope# else returns false.function f() println(@isdefined x) x = 10 println(@isdefined x) endf (generic function with 1 method)println(f())", "e": 27299, "s": 27012, "text": null }, { "code": null, "e": 27307, "s": 27299, "text": "Output:" }, { "code": null, "e": 27313, "s": 27307, "text": "Julia" }, { "code": null, "e": 27411, "s": 27313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27428, "s": 27411, "text": "Vectors in Julia" }, { "code": null, "e": 27488, "s": 27428, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 27561, "s": 27488, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 27595, "s": 27561, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 27626, "s": 27595, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 27657, "s": 27626, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 27722, "s": 27657, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 27783, "s": 27722, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 27803, "s": 27783, "text": "while loop in Julia" } ]
HTML <button> value Attribute - GeeksforGeeks
16 Feb, 2019 The value attribute for <button> element in HTML is used to specify the initial value of the button element. Syntax: <button value = "value"> Example: <!DOCTYPE html><html> <head> <title>HTML button value Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML button value Attribute </h2> <button id="btn" value="GeeksforGeeks" onclick="geek()"> Click me!</button> <p id="g"></p> <script> function geek() { var x = document.getElementById("btn").value; document.getElementById("g").innerHTML = x; } </script> </body></html> Output:Before clicking the button:After clicking the button:Supported Browsers: The browser supported by value attribute in button element are listed below: Apple Safari Google Chrome Firefox Opera Internet Explorer Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25058, "s": 25030, "text": "\n16 Feb, 2019" }, { "code": null, "e": 25167, "s": 25058, "text": "The value attribute for <button> element in HTML is used to specify the initial value of the button element." }, { "code": null, "e": 25175, "s": 25167, "text": "Syntax:" }, { "code": null, "e": 25200, "s": 25175, "text": "<button value = \"value\">" }, { "code": null, "e": 25209, "s": 25200, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML button value Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML button value Attribute </h2> <button id=\"btn\" value=\"GeeksforGeeks\" onclick=\"geek()\"> Click me!</button> <p id=\"g\"></p> <script> function geek() { var x = document.getElementById(\"btn\").value; document.getElementById(\"g\").innerHTML = x; } </script> </body></html>", "e": 25840, "s": 25209, "text": null }, { "code": null, "e": 25997, "s": 25840, "text": "Output:Before clicking the button:After clicking the button:Supported Browsers: The browser supported by value attribute in button element are listed below:" }, { "code": null, "e": 26010, "s": 25997, "text": "Apple Safari" }, { "code": null, "e": 26024, "s": 26010, "text": "Google Chrome" }, { "code": null, "e": 26032, "s": 26024, "text": "Firefox" }, { "code": null, "e": 26038, "s": 26032, "text": "Opera" }, { "code": null, "e": 26056, "s": 26038, "text": "Internet Explorer" }, { "code": null, "e": 26193, "s": 26056, "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": 26209, "s": 26193, "text": "HTML-Attributes" }, { "code": null, "e": 26214, "s": 26209, "text": "HTML" }, { "code": null, "e": 26231, "s": 26214, "text": "Web Technologies" }, { "code": null, "e": 26236, "s": 26231, "text": "HTML" }, { "code": null, "e": 26334, "s": 26236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26384, "s": 26334, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26446, "s": 26384, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26494, "s": 26446, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26554, "s": 26494, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26607, "s": 26554, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 26647, "s": 26607, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26680, "s": 26647, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26725, "s": 26680, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26768, "s": 26725, "text": "How to fetch data from an API in ReactJS ?" } ]
MySQL | Creating stored function - GeeksforGeeks
18 Jan, 2022 The CREATE FUNCTION statement is used for creating a stored function and user-defined functions. A stored function is a set of SQL statements that perform some operation and return a single value. Just like Mysql in-built function, it can be called from within a Mysql statement. By default, the stored function is associated with the default database. The CREATE FUNCTION statement require CREATE ROUTINE database privilege. Syntax: The syntax for CREATE FUNCTION statement in Mysql is: CREATE FUNCTION function_name(func_parameter1, func_parameter2, ..) RETURN datatype [characteristics] func_body Parameters used: function_name: It is the name by which stored function is called. The name should not be same as native(built_in) function. In order to associate routine explicitly with a specific database function name should be given as database_name.func_name.func_parameter: It is the argument whose value is used by the function inside its body. You can’t specify to these parameters IN, OUT, INOUT. The parameter declaration inside parenthesis is provided as func_parameter type. Here, type represents a valid Mysql datatype.datatype: It is datatype of value returned by function.characteristics: The CREATE FUNCTION statement is accepted only if at least one of the characteristics { DETERMINISTIC, NO SQL, or READS SQL DATA } is specified in its declaration. function_name: It is the name by which stored function is called. The name should not be same as native(built_in) function. In order to associate routine explicitly with a specific database function name should be given as database_name.func_name. func_parameter: It is the argument whose value is used by the function inside its body. You can’t specify to these parameters IN, OUT, INOUT. The parameter declaration inside parenthesis is provided as func_parameter type. Here, type represents a valid Mysql datatype. datatype: It is datatype of value returned by function. characteristics: The CREATE FUNCTION statement is accepted only if at least one of the characteristics { DETERMINISTIC, NO SQL, or READS SQL DATA } is specified in its declaration. func_body is the set of Mysql statements that perform operation. It’s structure is as follows: BEGIN Mysql Statements RETURN expression; END The function body must contain one RETURN statement. Example: Consider following Employee Table- We have to find the number of years the employee has been in the company- DELIMITER // CREATE FUNCTION no_of_years(date1 date) RETURNS int DETERMINISTIC BEGIN DECLARE date2 DATE; Select current_date()into date2; RETURN year(date2)-year(date1); END // DELIMITER ; Calling of above function: Select emp_id, fname, lname, no_of_years(start_date) as 'years' from employee; Output: sumitgumber28 mysql DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions Introduction of B-Tree CTE in SQL SQL Trigger | Student Database Difference between Clustered and Non-clustered index SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) SQL Interview Questions CTE in SQL
[ { "code": null, "e": 25219, "s": 25191, "text": "\n18 Jan, 2022" }, { "code": null, "e": 25416, "s": 25219, "text": "The CREATE FUNCTION statement is used for creating a stored function and user-defined functions. A stored function is a set of SQL statements that perform some operation and return a single value." }, { "code": null, "e": 25499, "s": 25416, "text": "Just like Mysql in-built function, it can be called from within a Mysql statement." }, { "code": null, "e": 25572, "s": 25499, "text": "By default, the stored function is associated with the default database." }, { "code": null, "e": 25645, "s": 25572, "text": "The CREATE FUNCTION statement require CREATE ROUTINE database privilege." }, { "code": null, "e": 25709, "s": 25645, "text": "Syntax: The syntax for CREATE FUNCTION statement in Mysql is: " }, { "code": null, "e": 25841, "s": 25709, "text": "CREATE FUNCTION function_name(func_parameter1, func_parameter2, ..)\n RETURN datatype [characteristics]\n func_body" }, { "code": null, "e": 25858, "s": 25841, "text": "Parameters used:" }, { "code": null, "e": 26609, "s": 25858, "text": "function_name: It is the name by which stored function is called. The name should not be same as native(built_in) function. In order to associate routine explicitly with a specific database function name should be given as database_name.func_name.func_parameter: It is the argument whose value is used by the function inside its body. You can’t specify to these parameters IN, OUT, INOUT. The parameter declaration inside parenthesis is provided as func_parameter type. Here, type represents a valid Mysql datatype.datatype: It is datatype of value returned by function.characteristics: The CREATE FUNCTION statement is accepted only if at least one of the characteristics { DETERMINISTIC, NO SQL, or READS SQL DATA } is specified in its declaration." }, { "code": null, "e": 26857, "s": 26609, "text": "function_name: It is the name by which stored function is called. The name should not be same as native(built_in) function. In order to associate routine explicitly with a specific database function name should be given as database_name.func_name." }, { "code": null, "e": 27126, "s": 26857, "text": "func_parameter: It is the argument whose value is used by the function inside its body. You can’t specify to these parameters IN, OUT, INOUT. The parameter declaration inside parenthesis is provided as func_parameter type. Here, type represents a valid Mysql datatype." }, { "code": null, "e": 27182, "s": 27126, "text": "datatype: It is datatype of value returned by function." }, { "code": null, "e": 27363, "s": 27182, "text": "characteristics: The CREATE FUNCTION statement is accepted only if at least one of the characteristics { DETERMINISTIC, NO SQL, or READS SQL DATA } is specified in its declaration." }, { "code": null, "e": 27458, "s": 27363, "text": "func_body is the set of Mysql statements that perform operation. It’s structure is as follows:" }, { "code": null, "e": 27522, "s": 27458, "text": "BEGIN\n\n Mysql Statements\n\n RETURN expression;\nEND" }, { "code": null, "e": 27577, "s": 27522, "text": "The function body must contain one RETURN statement. " }, { "code": null, "e": 27586, "s": 27577, "text": "Example:" }, { "code": null, "e": 27621, "s": 27586, "text": "Consider following Employee Table-" }, { "code": null, "e": 27695, "s": 27621, "text": "We have to find the number of years the employee has been in the company-" }, { "code": null, "e": 27893, "s": 27695, "text": "DELIMITER //\n\nCREATE FUNCTION no_of_years(date1 date) RETURNS int DETERMINISTIC\nBEGIN\n DECLARE date2 DATE;\n Select current_date()into date2;\n RETURN year(date2)-year(date1);\nEND \n\n//\n\nDELIMITER ;" }, { "code": null, "e": 27920, "s": 27893, "text": "Calling of above function:" }, { "code": null, "e": 27999, "s": 27920, "text": "Select emp_id, fname, lname, no_of_years(start_date) as 'years' from employee;" }, { "code": null, "e": 28008, "s": 27999, "text": "Output: " }, { "code": null, "e": 28022, "s": 28008, "text": "sumitgumber28" }, { "code": null, "e": 28028, "s": 28022, "text": "mysql" }, { "code": null, "e": 28033, "s": 28028, "text": "DBMS" }, { "code": null, "e": 28037, "s": 28033, "text": "SQL" }, { "code": null, "e": 28042, "s": 28037, "text": "DBMS" }, { "code": null, "e": 28046, "s": 28042, "text": "SQL" }, { "code": null, "e": 28144, "s": 28046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28168, "s": 28144, "text": "SQL Interview Questions" }, { "code": null, "e": 28191, "s": 28168, "text": "Introduction of B-Tree" }, { "code": null, "e": 28202, "s": 28191, "text": "CTE in SQL" }, { "code": null, "e": 28233, "s": 28202, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 28286, "s": 28233, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 28328, "s": 28286, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 28372, "s": 28328, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 28393, "s": 28372, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 28417, "s": 28393, "text": "SQL Interview Questions" } ]
Matplotlib.figure.Figure.get_size_inches() in Python - GeeksforGeeks
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The get_size_inches() method figure module of matplotlib library is used to get the current size of the figure in inches. Syntax: get_size_inches(self) Parameters: This method does not accept any parameters. Returns: This method return size (width, height) of the figure in inches. Below examples illustrate the matplotlib.figure.Figure.get_size_inches() function in matplotlib.figure: Example 1: # Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) w = fig.get_size_inches()ax.text(0.2, 0.5, "Value Return by get_size_inches() : " + str(w), fontweight ="bold") fig.canvas.draw() fig.suptitle('matplotlib.figure.Figure.get_size_inches()\ function Example', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(edgecolor = "red", figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) w = fig.get_size_inches()ax.text(1.5, 0, "Value Return by get_size_inches() : " + str(w), fontweight ="bold") fig.canvas.draw() fig.suptitle('matplotlib.figure.Figure.get_size_inches() \function Example', fontweight ="bold") plt.show() Output: Matplotlib figure-class Python-matplotlib 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 Apr, 2020" }, { "code": null, "e": 25848, "s": 25537, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 25970, "s": 25848, "text": "The get_size_inches() method figure module of matplotlib library is used to get the current size of the figure in inches." }, { "code": null, "e": 26000, "s": 25970, "text": "Syntax: get_size_inches(self)" }, { "code": null, "e": 26056, "s": 26000, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 26130, "s": 26056, "text": "Returns: This method return size (width, height) of the figure in inches." }, { "code": null, "e": 26234, "s": 26130, "text": "Below examples illustrate the matplotlib.figure.Figure.get_size_inches() function in matplotlib.figure:" }, { "code": null, "e": 26245, "s": 26234, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) w = fig.get_size_inches()ax.text(0.2, 0.5, \"Value Return by get_size_inches() : \" + str(w), fontweight =\"bold\") fig.canvas.draw() fig.suptitle('matplotlib.figure.Figure.get_size_inches()\\ function Example', fontweight =\"bold\") plt.show()", "e": 26767, "s": 26245, "text": null }, { "code": null, "e": 26775, "s": 26767, "text": "Output:" }, { "code": null, "e": 26786, "s": 26775, "text": "Example 2:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(edgecolor = \"red\", figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) w = fig.get_size_inches()ax.text(1.5, 0, \"Value Return by get_size_inches() : \" + str(w), fontweight =\"bold\") fig.canvas.draw() fig.suptitle('matplotlib.figure.Figure.get_size_inches() \\function Example', fontweight =\"bold\") plt.show()", "e": 27351, "s": 26786, "text": null }, { "code": null, "e": 27359, "s": 27351, "text": "Output:" }, { "code": null, "e": 27383, "s": 27359, "text": "Matplotlib figure-class" }, { "code": null, "e": 27401, "s": 27383, "text": "Python-matplotlib" }, { "code": null, "e": 27408, "s": 27401, "text": "Python" }, { "code": null, "e": 27506, "s": 27408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27538, "s": 27506, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27580, "s": 27538, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27622, "s": 27580, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27649, "s": 27622, "text": "Python Classes and Objects" }, { "code": null, "e": 27705, "s": 27649, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27744, "s": 27705, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27766, "s": 27744, "text": "Defaultdict in Python" }, { "code": null, "e": 27797, "s": 27766, "text": "Python | os.path.join() method" }, { "code": null, "e": 27826, "s": 27797, "text": "Create a directory in Python" } ]
Naming a thread and fetching name of current thread in Java - GeeksforGeeks
25 Feb, 2022 Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a thread. Methods: There are two ways by which we can set the name either be it directly or indirectly which we will be peeking through. Creating the thread and Passing the thread’s name (Direct method)Using setName() method of Thread class (Indirect Method) Creating the thread and Passing the thread’s name (Direct method) Using setName() method of Thread class (Indirect Method) Method 1: Creating the thread and passing the thread’s name It is a direct method of naming threads in java, each thread has a name that is: Thread-0, Thread-1, Thread-2,....so on. Java provides some methods to change the thread name. There are basically two methods to set the thread name. Both methods are defined in java.lang.Thread class. Geek, now you must be wondering how to set the thread’s name directly? In java we can set the thread name at the time of creating the thread and bypassing the thread’s name as an argument as shown in the below example as follows: Example: Java // Java Program Illustrating How to Set the name// of Thread at time of Creation // Importing I/O classes from java.io packageimport java.io.*; // Class 1// Helper classclass ThreadNaming extends Thread { // Parameterized constructor ThreadNaming(String name) { // Call to constructor of // the Thread class as super keyword // refers to parent class super(name); } // run() method for thread @Override public void run() { // Print statement when thread is called inside // main() System.out.println("Thread is running....."); }} // Class 2// Main classclass GFG { // main driver method public static void main(String[] args) { // Creating two threads ThreadNaming t1 = new ThreadNaming("geek1"); ThreadNaming t2 = new ThreadNaming("geek2"); // Getting the above created threads names. System.out.println("Thread 1: " + t1.getName()); System.out.println("Thread 2: " + t2.getName()); // Starting threads using start() method t1.start(); t2.start(); }} Thread 1: geek1 Thread 2: geek2 Thread is running..... Thread is running..... Way 2: Using setName() method of Thread class We can set(change) the thread’s name by calling the setName method on that thread object. It will change the name of a thread. Syntax: public final void setName(String name) Parameter: A string that specifies the thread name Example: Java // Java Program Illustrating How to Get and Change the// Name of a Thread // Importing input output classesimport java.io.*; // Class 1// Helper class extending Thread classclass ThreadNaming extends Thread { // run() method for thread which is called // as soon as start() is called over threads @Override public void run() { // Print statement when run() is called over thread System.out.println("Thread is running....."); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating two threads via above class // as it is extending Thread class ThreadNaming t1 = new ThreadNaming(); ThreadNaming t2 = new ThreadNaming(); // Fetching the above created threads names // using getName() method System.out.println("Thread 1: " + t1.getName()); System.out.println("Thread 2: " + t2.getName()); // Starting threads using start() method t1.start(); t2.start(); // Now changing the name of threads t1.setName("geeksforgeeks"); t2.setName("geeksquiz"); // Again getting the new names of threads System.out.println( "Thread names after changing the " + "thread names"); // Printing the above names System.out.println("New Thread 1 name: " + t1.getName()); System.out.println("New Thread 2 name: " + t2.getName()); }} Thread 1: Thread-0 Thread 2: Thread-1 Thread is running..... Thread names after changing the thread names New Thread 1 name: geeksforgeeks New Thread 2 name: geeksquiz Thread is running..... Now let us dwell on fetching the name of the current thread. We can fetch the current thread name at the time of creating the thread and bypassing the thread’s name as an argument. Method: currentThread() It is defined in java.langThread class. Return Type: It returns a reference to the currently executing thread Syntax: public static Thread currentThread() Example: Java // Java program to Illustrate How to Get Name of// Current Executing thread// Using getName() Method // Importing reqiored I/O classesimport java.io.*; // Class 1// Helper class extending to Thread classclass ThreadNaming extends Thread { // run() method for this thread @Override public void run() { // Display message System.out.println( "Fetching current thread name.."); // Getting the current thread name // using getname() method System.out.println( Thread.currentThread().getName()); }} // Class 2// Main classclass GFG { // Main method driver public static void main(String[] args) { // Creating two threads inside main() method ThreadNaming t1 = new ThreadNaming(); ThreadNaming t2 = new ThreadNaming(); // Starting threads using start() method which // automatically calls run() method t1.start(); t2.start(); }} Fetching current thread name.. Thread-0 Fetching current thread name.. Thread-1 YouTubeGeeksforGeeks507K subscribersThread Naming (Java) | 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 / 12:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=DaslnWaEq3g" 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 Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. solankimayank prachisoda1234 as5853535 simranarora5sos Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples Reverse a string in Java Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25195, "s": 25167, "text": "\n25 Feb, 2022" }, { "code": null, "e": 25505, "s": 25195, "text": "Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the process; thread shares process resources. The main thread of Java is the thread that is started when the program starts. now let us discuss the eccentric concept of with what ways we can name a thread. " }, { "code": null, "e": 25633, "s": 25505, "text": "Methods: There are two ways by which we can set the name either be it directly or indirectly which we will be peeking through." }, { "code": null, "e": 25755, "s": 25633, "text": "Creating the thread and Passing the thread’s name (Direct method)Using setName() method of Thread class (Indirect Method)" }, { "code": null, "e": 25821, "s": 25755, "text": "Creating the thread and Passing the thread’s name (Direct method)" }, { "code": null, "e": 25878, "s": 25821, "text": "Using setName() method of Thread class (Indirect Method)" }, { "code": null, "e": 25938, "s": 25878, "text": "Method 1: Creating the thread and passing the thread’s name" }, { "code": null, "e": 26222, "s": 25938, "text": "It is a direct method of naming threads in java, each thread has a name that is: Thread-0, Thread-1, Thread-2,....so on. Java provides some methods to change the thread name. There are basically two methods to set the thread name. Both methods are defined in java.lang.Thread class. " }, { "code": null, "e": 26452, "s": 26222, "text": "Geek, now you must be wondering how to set the thread’s name directly? In java we can set the thread name at the time of creating the thread and bypassing the thread’s name as an argument as shown in the below example as follows:" }, { "code": null, "e": 26461, "s": 26452, "text": "Example:" }, { "code": null, "e": 26466, "s": 26461, "text": "Java" }, { "code": "// Java Program Illustrating How to Set the name// of Thread at time of Creation // Importing I/O classes from java.io packageimport java.io.*; // Class 1// Helper classclass ThreadNaming extends Thread { // Parameterized constructor ThreadNaming(String name) { // Call to constructor of // the Thread class as super keyword // refers to parent class super(name); } // run() method for thread @Override public void run() { // Print statement when thread is called inside // main() System.out.println(\"Thread is running.....\"); }} // Class 2// Main classclass GFG { // main driver method public static void main(String[] args) { // Creating two threads ThreadNaming t1 = new ThreadNaming(\"geek1\"); ThreadNaming t2 = new ThreadNaming(\"geek2\"); // Getting the above created threads names. System.out.println(\"Thread 1: \" + t1.getName()); System.out.println(\"Thread 2: \" + t2.getName()); // Starting threads using start() method t1.start(); t2.start(); }}", "e": 27572, "s": 26466, "text": null }, { "code": null, "e": 27650, "s": 27572, "text": "Thread 1: geek1\nThread 2: geek2\nThread is running.....\nThread is running....." }, { "code": null, "e": 27696, "s": 27650, "text": "Way 2: Using setName() method of Thread class" }, { "code": null, "e": 27823, "s": 27696, "text": "We can set(change) the thread’s name by calling the setName method on that thread object. It will change the name of a thread." }, { "code": null, "e": 27832, "s": 27823, "text": "Syntax: " }, { "code": null, "e": 27871, "s": 27832, "text": "public final void setName(String name)" }, { "code": null, "e": 27923, "s": 27871, "text": "Parameter: A string that specifies the thread name " }, { "code": null, "e": 27932, "s": 27923, "text": "Example:" }, { "code": null, "e": 27937, "s": 27932, "text": "Java" }, { "code": "// Java Program Illustrating How to Get and Change the// Name of a Thread // Importing input output classesimport java.io.*; // Class 1// Helper class extending Thread classclass ThreadNaming extends Thread { // run() method for thread which is called // as soon as start() is called over threads @Override public void run() { // Print statement when run() is called over thread System.out.println(\"Thread is running.....\"); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating two threads via above class // as it is extending Thread class ThreadNaming t1 = new ThreadNaming(); ThreadNaming t2 = new ThreadNaming(); // Fetching the above created threads names // using getName() method System.out.println(\"Thread 1: \" + t1.getName()); System.out.println(\"Thread 2: \" + t2.getName()); // Starting threads using start() method t1.start(); t2.start(); // Now changing the name of threads t1.setName(\"geeksforgeeks\"); t2.setName(\"geeksquiz\"); // Again getting the new names of threads System.out.println( \"Thread names after changing the \" + \"thread names\"); // Printing the above names System.out.println(\"New Thread 1 name: \" + t1.getName()); System.out.println(\"New Thread 2 name: \" + t2.getName()); }}", "e": 29458, "s": 27937, "text": null }, { "code": null, "e": 29650, "s": 29458, "text": "Thread 1: Thread-0\nThread 2: Thread-1\nThread is running.....\nThread names after changing the thread names\nNew Thread 1 name: geeksforgeeks\nNew Thread 2 name: geeksquiz\nThread is running....." }, { "code": null, "e": 29832, "s": 29650, "text": "Now let us dwell on fetching the name of the current thread. We can fetch the current thread name at the time of creating the thread and bypassing the thread’s name as an argument. " }, { "code": null, "e": 29856, "s": 29832, "text": "Method: currentThread()" }, { "code": null, "e": 29896, "s": 29856, "text": "It is defined in java.langThread class." }, { "code": null, "e": 29966, "s": 29896, "text": "Return Type: It returns a reference to the currently executing thread" }, { "code": null, "e": 29975, "s": 29966, "text": "Syntax: " }, { "code": null, "e": 30012, "s": 29975, "text": "public static Thread currentThread()" }, { "code": null, "e": 30021, "s": 30012, "text": "Example:" }, { "code": null, "e": 30026, "s": 30021, "text": "Java" }, { "code": "// Java program to Illustrate How to Get Name of// Current Executing thread// Using getName() Method // Importing reqiored I/O classesimport java.io.*; // Class 1// Helper class extending to Thread classclass ThreadNaming extends Thread { // run() method for this thread @Override public void run() { // Display message System.out.println( \"Fetching current thread name..\"); // Getting the current thread name // using getname() method System.out.println( Thread.currentThread().getName()); }} // Class 2// Main classclass GFG { // Main method driver public static void main(String[] args) { // Creating two threads inside main() method ThreadNaming t1 = new ThreadNaming(); ThreadNaming t2 = new ThreadNaming(); // Starting threads using start() method which // automatically calls run() method t1.start(); t2.start(); }}", "e": 30984, "s": 30026, "text": null }, { "code": null, "e": 31064, "s": 30984, "text": "Fetching current thread name..\nThread-0\nFetching current thread name..\nThread-1" }, { "code": null, "e": 31884, "s": 31064, "text": "YouTubeGeeksforGeeks507K subscribersThread Naming (Java) | 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 / 12:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=DaslnWaEq3g\" 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": 32307, "s": 31884, "text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 32321, "s": 32307, "text": "solankimayank" }, { "code": null, "e": 32336, "s": 32321, "text": "prachisoda1234" }, { "code": null, "e": 32346, "s": 32336, "text": "as5853535" }, { "code": null, "e": 32362, "s": 32346, "text": "simranarora5sos" }, { "code": null, "e": 32382, "s": 32362, "text": "Java-Multithreading" }, { "code": null, "e": 32387, "s": 32382, "text": "Java" }, { "code": null, "e": 32392, "s": 32387, "text": "Java" }, { "code": null, "e": 32490, "s": 32392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32505, "s": 32490, "text": "Arrays in Java" }, { "code": null, "e": 32549, "s": 32505, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32571, "s": 32549, "text": "For-each loop in Java" }, { "code": null, "e": 32622, "s": 32571, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32658, "s": 32622, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 32688, "s": 32658, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32713, "s": 32688, "text": "Reverse a string in Java" }, { "code": null, "e": 32728, "s": 32713, "text": "Stream In Java" }, { "code": null, "e": 32747, "s": 32728, "text": "Interfaces in Java" } ]
Beep() function in C with Examples - GeeksforGeeks
22 Nov, 2020 The Beep function in C is used to make a Beep sound. It generates a tone on the speaker. The function is synchronous, i.e. it waits and doesn’t return to its caller function until the sound is finished. It can be very useful during the Debugging process for finding errors.Header File: #include <windows.h> Syntax: BEEP(x, y) Parameters: This method accepts two parameters: x: which is the frequency of sound y: which is the duration in ms till sound is ON. Return Type: If the function produces the sound then it return any nonzero value. If the function doesn’t produces the sound then it returns zero. Below is the illustration of the BEEP() function:Program 1: C // C program to illustrate BEEP() function #include <stdio.h>#include <windows.h> // Driver Codeint main(){ // Function that beeps a sound of // frequency 750 for 0.8 sec BEEP(750, 800); getch(); return 0;} Note: The program won’t produce the sound in online IDE. Please try to run it in offline compilers.Program 2: C // C program to play song Jingle Bell// using the BEEP() function #include <stdio.h>#include <windows.h> // Driver Codeint main(){ int x; // Loop for sound Jingle for (x = 0; x < 2; x++) { Beep(523, 500); } // sound Bell Beep(523, 800); Sleep(200); // Loop for sound Jingle for (x = 0; x < 2; x++) { Beep(523, 500); } // sound Bell Beep(523, 800); // Sound for rest of the tone Sleep(200); Beep(523, 500); Sleep(50); Beep(659, 400); Sleep(50); Beep(440, 400); Sleep(50); Beep(494, 400); Sleep(50); Beep(523, 750); Sleep(400); Beep(600, 400); Sleep(100); Beep(600, 350); Sleep(200); Beep(600, 300); Sleep(150); Beep(600, 250); Sleep(150); Beep(600, 150); Sleep(150); Beep(550, 250); Sleep(150); Beep(555, 350); Sleep(50); Beep(555, 200); Sleep(150); Beep(555, 200); Sleep(150); Beep(690, 200); Sleep(150); Beep(690, 200); Sleep(150); Beep(610, 200); Sleep(150); Beep(535, 160); Sleep(100); Beep(500, 150); Beep(500, 50); Sleep(200); Beep(700, 200); return 0;} jake1924 Advanced Computer Subject C Language C Programs Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Markov Decision Process Fuzzy Logic | Introduction Q-Learning in Python Principal Component Analysis with Python Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Substring in C++
[ { "code": null, "e": 25517, "s": 25489, "text": "\n22 Nov, 2020" }, { "code": null, "e": 25805, "s": 25517, "text": "The Beep function in C is used to make a Beep sound. It generates a tone on the speaker. The function is synchronous, i.e. it waits and doesn’t return to its caller function until the sound is finished. It can be very useful during the Debugging process for finding errors.Header File: " }, { "code": null, "e": 25827, "s": 25805, "text": "#include <windows.h>\n" }, { "code": null, "e": 25837, "s": 25827, "text": "Syntax: " }, { "code": null, "e": 25849, "s": 25837, "text": "BEEP(x, y)\n" }, { "code": null, "e": 25899, "s": 25849, "text": "Parameters: This method accepts two parameters: " }, { "code": null, "e": 25934, "s": 25899, "text": "x: which is the frequency of sound" }, { "code": null, "e": 25983, "s": 25934, "text": "y: which is the duration in ms till sound is ON." }, { "code": null, "e": 25998, "s": 25983, "text": "Return Type: " }, { "code": null, "e": 26067, "s": 25998, "text": "If the function produces the sound then it return any nonzero value." }, { "code": null, "e": 26132, "s": 26067, "text": "If the function doesn’t produces the sound then it returns zero." }, { "code": null, "e": 26193, "s": 26132, "text": "Below is the illustration of the BEEP() function:Program 1: " }, { "code": null, "e": 26195, "s": 26193, "text": "C" }, { "code": "// C program to illustrate BEEP() function #include <stdio.h>#include <windows.h> // Driver Codeint main(){ // Function that beeps a sound of // frequency 750 for 0.8 sec BEEP(750, 800); getch(); return 0;}", "e": 26419, "s": 26195, "text": null }, { "code": null, "e": 26530, "s": 26419, "text": "Note: The program won’t produce the sound in online IDE. Please try to run it in offline compilers.Program 2: " }, { "code": null, "e": 26532, "s": 26530, "text": "C" }, { "code": "// C program to play song Jingle Bell// using the BEEP() function #include <stdio.h>#include <windows.h> // Driver Codeint main(){ int x; // Loop for sound Jingle for (x = 0; x < 2; x++) { Beep(523, 500); } // sound Bell Beep(523, 800); Sleep(200); // Loop for sound Jingle for (x = 0; x < 2; x++) { Beep(523, 500); } // sound Bell Beep(523, 800); // Sound for rest of the tone Sleep(200); Beep(523, 500); Sleep(50); Beep(659, 400); Sleep(50); Beep(440, 400); Sleep(50); Beep(494, 400); Sleep(50); Beep(523, 750); Sleep(400); Beep(600, 400); Sleep(100); Beep(600, 350); Sleep(200); Beep(600, 300); Sleep(150); Beep(600, 250); Sleep(150); Beep(600, 150); Sleep(150); Beep(550, 250); Sleep(150); Beep(555, 350); Sleep(50); Beep(555, 200); Sleep(150); Beep(555, 200); Sleep(150); Beep(690, 200); Sleep(150); Beep(690, 200); Sleep(150); Beep(610, 200); Sleep(150); Beep(535, 160); Sleep(100); Beep(500, 150); Beep(500, 50); Sleep(200); Beep(700, 200); return 0;}", "e": 27720, "s": 26532, "text": null }, { "code": null, "e": 27729, "s": 27720, "text": "jake1924" }, { "code": null, "e": 27755, "s": 27729, "text": "Advanced Computer Subject" }, { "code": null, "e": 27766, "s": 27755, "text": "C Language" }, { "code": null, "e": 27777, "s": 27766, "text": "C Programs" }, { "code": null, "e": 27798, "s": 27777, "text": "Programming Language" }, { "code": null, "e": 27896, "s": 27798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27940, "s": 27896, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27964, "s": 27940, "text": "Markov Decision Process" }, { "code": null, "e": 27991, "s": 27964, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 28012, "s": 27991, "text": "Q-Learning in Python" }, { "code": null, "e": 28053, "s": 28012, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 28069, "s": 28053, "text": "Arrays in C/C++" }, { "code": null, "e": 28147, "s": 28069, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 28170, "s": 28147, "text": "std::sort() in C++ STL" }, { "code": null, "e": 28197, "s": 28170, "text": "Bitwise Operators in C/C++" } ]
View Binding in Android Jetpack - GeeksforGeeks
24 May, 2021 View Binding is one of the best features which provides the views to bind with the activity which is ongoing. Replacing the findViewById() method, hence reducing the boilerplate code, generated the instances of the views of the current layout. And most important feature about the View Binding is it’s always null safe. In this article detailed it’s been provided in detail approach for the View Binding. ViewBinding is always null safe and type-safe, which supports both Java and Kotlin. ViewBinding is introduced in the Gradle version 3.6 and above (which comes with the Android Studio 4.0, only gradle 3.6). ViewBinding also helps to reduce the boilerplate code, hence reducing the code redundancy. While using the ViewBinding proper naming conventions are need to be followed because it creates the binding class internally using the name of the same layout file. Naming the layout file in the snake case is preferred. For Example, the ViewBinding creates activity_main.xml(snake case) file as ActivityMainBinding(pascal case), which contains all the property and instances of all the views containing in that layout. And also whatever IDs of all elements are created inside the layout XML file, the ViewBinding converts them to camel case. For example: android:id=”button_submit” -> buttonSubmit. Which is much useful in the code readability. Using ViewBinding the compilation of the code is a bit faster as compared to the traditional findViewById() method. The ActivityMainBinding class is generated in the following path under the project hierarchy this can be viewed. The following is the flow of how the objects of the properties from the layout are generated. However, if the layout has to be ignored with the binding the views of it, can be done by adding the following attribute to the root layout. tools:viewBindingIgnore=”true” Step 1: Create an empty activity project Here the Android Studio is used, refer to Android | How to Create/Start a New Project in Android Studio, to know how to create an empty activity Android Studio project. Step 2: Enabling the ViewBinding Feature There is a need to enabling the ViewBinding feature in Android Studio 4.0 and above, inside the app-level build gradle file. Invoke the following code snippet inside the android{} body of the gradle file. buildFeatures { viewBinding = true } Refer to the following image if unable to locate the app-level gradle file and invoke the feature under the project view hierarchy. Step 3: Working with the activity_main.xml file The main layout of the file contains one EditText and one Button. To implement the same UI invoke the following code inside the actitvity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="128dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Button" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: Step 4: Working with the MainActivity file The things that need to be focused on here are, creating the instance of the ViewBinding. Following is the code snippet which is used to create an instance. var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) which may under global or local scope according to the usage. Accessing the properties of the layout goes as follows. binding.camelCaseConvertedObject Invoke the following code inside the MainActivity.kt/MainActivity.java file, comments are added for better understanding. Kotlin Java import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // create instance of the ActivityMainBinding, // as we have only one layout activity_main.xml private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // create instance of the ActivityMainBinding, // as we have only one layout activity_main.xml var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) // binding.root returns the root layout, // which is activity_main.xml file itself setContentView(binding.root) // using the binding variable we can access the layout // properties and perform the operations on them as usual binding.buttonSubmit.setOnClickListener { val str: String = binding.editText.text.toString() if (str.isNotEmpty()) { Toast.makeText(this, "You entered " + binding.editText.text.toString(), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show() } } }} import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding public class MainActivity extends AppCompatActivity { // calling binding class for activity_main.xml // which is generated automatically. ActivityMainBinding activityMainBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // inflating our xml layout in our activity main binding activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater()); // getting our root layout in our view. View view = activityMainBinding.getRoot(); // below line is to set // Content view for our layout. setContentView(view); // calling button and setting on click listener for our button. // we have called our button with its id and set on click listener on it. activityMainBinding.buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = activityMainBinding.editText.getText().toString(); if(str.isEmpty()) { Toast.makeText(this, "Please enter something", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "You entered " + activityMainBinding.editText.geText().toString(), Toast.LENGTH_SHORT).show(); } } }); }} chaitanyamunje anikaseth98 Android-Jetpack Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android UI Layouts Kotlin Array Services in Android with Example Android RecyclerView in Kotlin
[ { "code": null, "e": 25969, "s": 25941, "text": "\n24 May, 2021" }, { "code": null, "e": 26374, "s": 25969, "text": "View Binding is one of the best features which provides the views to bind with the activity which is ongoing. Replacing the findViewById() method, hence reducing the boilerplate code, generated the instances of the views of the current layout. And most important feature about the View Binding is it’s always null safe. In this article detailed it’s been provided in detail approach for the View Binding." }, { "code": null, "e": 26458, "s": 26374, "text": "ViewBinding is always null safe and type-safe, which supports both Java and Kotlin." }, { "code": null, "e": 26580, "s": 26458, "text": "ViewBinding is introduced in the Gradle version 3.6 and above (which comes with the Android Studio 4.0, only gradle 3.6)." }, { "code": null, "e": 26671, "s": 26580, "text": "ViewBinding also helps to reduce the boilerplate code, hence reducing the code redundancy." }, { "code": null, "e": 27091, "s": 26671, "text": "While using the ViewBinding proper naming conventions are need to be followed because it creates the binding class internally using the name of the same layout file. Naming the layout file in the snake case is preferred. For Example, the ViewBinding creates activity_main.xml(snake case) file as ActivityMainBinding(pascal case), which contains all the property and instances of all the views containing in that layout." }, { "code": null, "e": 27317, "s": 27091, "text": "And also whatever IDs of all elements are created inside the layout XML file, the ViewBinding converts them to camel case. For example: android:id=”button_submit” -> buttonSubmit. Which is much useful in the code readability." }, { "code": null, "e": 27433, "s": 27317, "text": "Using ViewBinding the compilation of the code is a bit faster as compared to the traditional findViewById() method." }, { "code": null, "e": 27546, "s": 27433, "text": "The ActivityMainBinding class is generated in the following path under the project hierarchy this can be viewed." }, { "code": null, "e": 27640, "s": 27546, "text": "The following is the flow of how the objects of the properties from the layout are generated." }, { "code": null, "e": 27781, "s": 27640, "text": "However, if the layout has to be ignored with the binding the views of it, can be done by adding the following attribute to the root layout." }, { "code": null, "e": 27812, "s": 27781, "text": "tools:viewBindingIgnore=”true”" }, { "code": null, "e": 27853, "s": 27812, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 28022, "s": 27853, "text": "Here the Android Studio is used, refer to Android | How to Create/Start a New Project in Android Studio, to know how to create an empty activity Android Studio project." }, { "code": null, "e": 28063, "s": 28022, "text": "Step 2: Enabling the ViewBinding Feature" }, { "code": null, "e": 28188, "s": 28063, "text": "There is a need to enabling the ViewBinding feature in Android Studio 4.0 and above, inside the app-level build gradle file." }, { "code": null, "e": 28268, "s": 28188, "text": "Invoke the following code snippet inside the android{} body of the gradle file." }, { "code": null, "e": 28284, "s": 28268, "text": "buildFeatures {" }, { "code": null, "e": 28310, "s": 28284, "text": " viewBinding = true" }, { "code": null, "e": 28312, "s": 28310, "text": "}" }, { "code": null, "e": 28444, "s": 28312, "text": "Refer to the following image if unable to locate the app-level gradle file and invoke the feature under the project view hierarchy." }, { "code": null, "e": 28492, "s": 28444, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 28645, "s": 28492, "text": "The main layout of the file contains one EditText and one Button. To implement the same UI invoke the following code inside the actitvity_main.xml file." }, { "code": null, "e": 28649, "s": 28645, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"128dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Button\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 29867, "s": 28649, "text": null }, { "code": null, "e": 29882, "s": 29871, "text": "Output UI:" }, { "code": null, "e": 29930, "s": 29886, "text": "Step 4: Working with the MainActivity file " }, { "code": null, "e": 30089, "s": 29932, "text": "The things that need to be focused on here are, creating the instance of the ViewBinding. Following is the code snippet which is used to create an instance." }, { "code": null, "e": 30168, "s": 30089, "text": "var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)" }, { "code": null, "e": 30230, "s": 30168, "text": "which may under global or local scope according to the usage." }, { "code": null, "e": 30286, "s": 30230, "text": "Accessing the properties of the layout goes as follows." }, { "code": null, "e": 30319, "s": 30286, "text": "binding.camelCaseConvertedObject" }, { "code": null, "e": 30441, "s": 30319, "text": "Invoke the following code inside the MainActivity.kt/MainActivity.java file, comments are added for better understanding." }, { "code": null, "e": 30450, "s": 30443, "text": "Kotlin" }, { "code": null, "e": 30455, "s": 30450, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // create instance of the ActivityMainBinding, // as we have only one layout activity_main.xml private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // create instance of the ActivityMainBinding, // as we have only one layout activity_main.xml var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater) // binding.root returns the root layout, // which is activity_main.xml file itself setContentView(binding.root) // using the binding variable we can access the layout // properties and perform the operations on them as usual binding.buttonSubmit.setOnClickListener { val str: String = binding.editText.text.toString() if (str.isNotEmpty()) { Toast.makeText(this, \"You entered \" + binding.editText.text.toString(), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, \"Please enter something\", Toast.LENGTH_SHORT).show() } } }}", "e": 31777, "s": 30455, "text": null }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding public class MainActivity extends AppCompatActivity { // calling binding class for activity_main.xml // which is generated automatically. ActivityMainBinding activityMainBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // inflating our xml layout in our activity main binding activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater()); // getting our root layout in our view. View view = activityMainBinding.getRoot(); // below line is to set // Content view for our layout. setContentView(view); // calling button and setting on click listener for our button. // we have called our button with its id and set on click listener on it. activityMainBinding.buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = activityMainBinding.editText.getText().toString(); if(str.isEmpty()) { Toast.makeText(this, \"Please enter something\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, \"You entered \" + activityMainBinding.editText.geText().toString(), Toast.LENGTH_SHORT).show(); } } }); }}", "e": 33324, "s": 31777, "text": null }, { "code": null, "e": 33344, "s": 33329, "text": "chaitanyamunje" }, { "code": null, "e": 33356, "s": 33344, "text": "anikaseth98" }, { "code": null, "e": 33372, "s": 33356, "text": "Android-Jetpack" }, { "code": null, "e": 33396, "s": 33372, "text": "Technical Scripter 2020" }, { "code": null, "e": 33404, "s": 33396, "text": "Android" }, { "code": null, "e": 33411, "s": 33404, "text": "Kotlin" }, { "code": null, "e": 33430, "s": 33411, "text": "Technical Scripter" }, { "code": null, "e": 33438, "s": 33430, "text": "Android" }, { "code": null, "e": 33536, "s": 33438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33594, "s": 33536, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 33632, "s": 33594, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 33675, "s": 33632, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33708, "s": 33675, "text": "Services in Android with Example" }, { "code": null, "e": 33739, "s": 33708, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 33782, "s": 33739, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 33801, "s": 33782, "text": "Android UI Layouts" }, { "code": null, "e": 33814, "s": 33801, "text": "Kotlin Array" }, { "code": null, "e": 33847, "s": 33814, "text": "Services in Android with Example" } ]
Find the non decreasing order array from given array - GeeksforGeeks
21 Oct, 2021 Given an array A[] of size N / 2, the task is to construct the array B[] of size N such that: B[] is sorted in non-decreasing order.A[i] = B[i] + B[n – i + 1]. B[] is sorted in non-decreasing order. A[i] = B[i] + B[n – i + 1]. Note: Array A[] is given in such a way that the answer is always possible.Examples: Input: A[] = {3, 4} Output: 0 1 3 3Input: A[] = {4, 1} Output: 0 0 1 4 Approach: Let’s present the following greedy approach. The numbers will be restored in pairs (B[0], B[n – 1]), (B[1], B[n – 2]) and so on. Thus, we can have some limits on the values of the current pair (satisfying the criteria about sorted result). Initially, l = 0 and r = 109, they are updated with l = a[i] and r = a[n – i + 1]. Let l be minimal possible in the answer. Take a[i] = max(l, b[i] – r) and r = b[i] – l, that way l was chosen in such a way that both l and r are within the restrictions and l is also minimal possible. If l was any greater than we would move both l limit up and r limit down leaving less freedom for later choices.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of the arrayvoid printArr(int b[], int n){ for (int i = 0; i < n; i++) cout << b[i] << " ";} // Function to build array B[]void ModifiedArray(int a[], int n){ // Lower and upper limits int l = 0, r = INT_MAX; // To store the required array int b[n] = { 0 }; // Apply greedy approach for (int i = 0; i < n / 2; i++) { b[i] = max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver codeint main(){ int a[] = { 5, 6 }; int n = sizeof(a) / sizeof(a[0]); ModifiedArray(a, 2 * n); return 0;} // Java implementation of the approachimport java.util.*; class solution{ // Utility function to print // the contents of the array void printArr(int b[], int n) { for (int i = 0; i < n; i++) { System.out.print(" " + b[i] + " "); } } // Function to build array B[] void ModifiedArray(int a[], int n) { // Lower and upper limits int l = 0, r = Integer.MAX_VALUE; // To store the required array int[] b = new int[n]; // Apply greedy approach for (int i = 0; i < n / 2; i++) { b[i] = Math.max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver codepublic static void main(String args[]){ int a[] = { 5, 6 }; int n = a.length ; solution s=new solution(); s.ModifiedArray(a, 2 * n); }}//This code is contributed by Shivi_Aggarwal # Python 3 implementation of the approachimport sys # Utility function to print the# contents of the arraydef printArr(b, n): for i in range(0, n, 1): print(b[i], end = " ") # Function to build array B[]def ModifiedArray(a, n): # Lower and upper limits l = 0 r = sys.maxsize # To store the required array b = [0 for i in range(n)] # Apply greedy approach for i in range(0, int(n / 2), 1): b[i] = max(l, a[i] - r) b[n - i - 1] = a[i] - b[i] l = b[i] r = b[n - i - 1] # Print the built array b[] printArr(b, n) # Driver codeif __name__ == '__main__': a = [5, 6] n = len(a) ModifiedArray(a, 2 * n) # This code is contributed by# Shashank_Sharma // C# implementation of the approach using System; public class GFG{ // Utility function to print// the contents of the arraystatic void printArr(int []b, int n) { for (int i = 0; i < n; i++) { Console.Write(" " + b[i] + " "); } } // Function to build array B[]static void ModifiedArray(int []a, int n) { // Lower and upper limits int l = 0, r = int.MaxValue; // To store the required array int[] b = new int[n]; // Apply greedy approach for (int i = 0; i < n / 2; i++) { b[i] = Math.Max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver code static public void Main (){ int []a = { 5, 6 }; int n = a.Length; ModifiedArray(a, 2 * n); }}// This code is contributed// by Sach_Code <?php// PHP implementation of the approach // Utility function to print the// contents of the arrayfunction printArr($b, $n){ for ($i = 0; $i < $n; $i++) echo $b[$i] . " ";} // Function to build array B[]function ModifiedArray($a, $n){ // Lower and upper limits $l = 0; $r = PHP_INT_MAX; // To store the required array $b = array(0); // Apply greedy approach for ($i = 0; $i < $n / 2; $i++) { $b[$i] = max($l, $a[$i] - $r); $b[$n - $i - 1] = $a[$i] - $b[$i]; $l = $b[$i]; $r = $b[$n - $i - 1]; } // Print the built array b[] printArr($b, $n);} // Driver code$a = array( 5, 6 );$n = sizeof($a);ModifiedArray($a, 2 * $n); // This code is contributed// by Akanksha Rai?> <script> // Javascript program of the above approach // Utility function to print // the contents of the array function printArr(b, n) { for (let i = 0; i < n; i++) { document.write(" " + b[i] + " "); } } // Function to build array B[] function ModifiedArray(a, n) { // Lower and upper limits let l = 0, r = Number.MAX_VALUE; // To store the required array let b = Array(n).fill(0); // Apply greedy approach for (let i = 0; i < n / 2; i++) { b[i] = Math.max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver code let a = [ 5, 6 ]; let n = a.length ; ModifiedArray(a, 2 * n); </script> 0 1 5 5 Shashank_Sharma Akanksha_Rai Shivi_Aggarwal Sach_Code chinmoy1997pal ankita_saini programming-puzzle Competitive Programming Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Bits manipulation (Important tactics) 7 Best Coding Challenge Websites in 2020 What is Competitive Programming and How to Prepare for It? Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Write a program to print all permutations of a given string
[ { "code": null, "e": 26727, "s": 26699, "text": "\n21 Oct, 2021" }, { "code": null, "e": 26823, "s": 26727, "text": "Given an array A[] of size N / 2, the task is to construct the array B[] of size N such that: " }, { "code": null, "e": 26889, "s": 26823, "text": "B[] is sorted in non-decreasing order.A[i] = B[i] + B[n – i + 1]." }, { "code": null, "e": 26928, "s": 26889, "text": "B[] is sorted in non-decreasing order." }, { "code": null, "e": 26956, "s": 26928, "text": "A[i] = B[i] + B[n – i + 1]." }, { "code": null, "e": 27042, "s": 26956, "text": "Note: Array A[] is given in such a way that the answer is always possible.Examples: " }, { "code": null, "e": 27115, "s": 27042, "text": "Input: A[] = {3, 4} Output: 0 1 3 3Input: A[] = {4, 1} Output: 0 0 1 4 " }, { "code": null, "e": 27817, "s": 27117, "text": "Approach: Let’s present the following greedy approach. The numbers will be restored in pairs (B[0], B[n – 1]), (B[1], B[n – 2]) and so on. Thus, we can have some limits on the values of the current pair (satisfying the criteria about sorted result). Initially, l = 0 and r = 109, they are updated with l = a[i] and r = a[n – i + 1]. Let l be minimal possible in the answer. Take a[i] = max(l, b[i] – r) and r = b[i] – l, that way l was chosen in such a way that both l and r are within the restrictions and l is also minimal possible. If l was any greater than we would move both l limit up and r limit down leaving less freedom for later choices.Below is the implementation of the above approach: " }, { "code": null, "e": 27821, "s": 27817, "text": "C++" }, { "code": null, "e": 27826, "s": 27821, "text": "Java" }, { "code": null, "e": 27834, "s": 27826, "text": "Python3" }, { "code": null, "e": 27837, "s": 27834, "text": "C#" }, { "code": null, "e": 27841, "s": 27837, "text": "PHP" }, { "code": null, "e": 27852, "s": 27841, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of the arrayvoid printArr(int b[], int n){ for (int i = 0; i < n; i++) cout << b[i] << \" \";} // Function to build array B[]void ModifiedArray(int a[], int n){ // Lower and upper limits int l = 0, r = INT_MAX; // To store the required array int b[n] = { 0 }; // Apply greedy approach for (int i = 0; i < n / 2; i++) { b[i] = max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver codeint main(){ int a[] = { 5, 6 }; int n = sizeof(a) / sizeof(a[0]); ModifiedArray(a, 2 * n); return 0;}", "e": 28621, "s": 27852, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class solution{ // Utility function to print // the contents of the array void printArr(int b[], int n) { for (int i = 0; i < n; i++) { System.out.print(\" \" + b[i] + \" \"); } } // Function to build array B[] void ModifiedArray(int a[], int n) { // Lower and upper limits int l = 0, r = Integer.MAX_VALUE; // To store the required array int[] b = new int[n]; // Apply greedy approach for (int i = 0; i < n / 2; i++) { b[i] = Math.max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver codepublic static void main(String args[]){ int a[] = { 5, 6 }; int n = a.length ; solution s=new solution(); s.ModifiedArray(a, 2 * n); }}//This code is contributed by Shivi_Aggarwal", "e": 29575, "s": 28621, "text": null }, { "code": "# Python 3 implementation of the approachimport sys # Utility function to print the# contents of the arraydef printArr(b, n): for i in range(0, n, 1): print(b[i], end = \" \") # Function to build array B[]def ModifiedArray(a, n): # Lower and upper limits l = 0 r = sys.maxsize # To store the required array b = [0 for i in range(n)] # Apply greedy approach for i in range(0, int(n / 2), 1): b[i] = max(l, a[i] - r) b[n - i - 1] = a[i] - b[i] l = b[i] r = b[n - i - 1] # Print the built array b[] printArr(b, n) # Driver codeif __name__ == '__main__': a = [5, 6] n = len(a) ModifiedArray(a, 2 * n) # This code is contributed by# Shashank_Sharma", "e": 30299, "s": 29575, "text": null }, { "code": "// C# implementation of the approach using System; public class GFG{ // Utility function to print// the contents of the arraystatic void printArr(int []b, int n) { for (int i = 0; i < n; i++) { Console.Write(\" \" + b[i] + \" \"); } } // Function to build array B[]static void ModifiedArray(int []a, int n) { // Lower and upper limits int l = 0, r = int.MaxValue; // To store the required array int[] b = new int[n]; // Apply greedy approach for (int i = 0; i < n / 2; i++) { b[i] = Math.Max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver code static public void Main (){ int []a = { 5, 6 }; int n = a.Length; ModifiedArray(a, 2 * n); }}// This code is contributed// by Sach_Code", "e": 31209, "s": 30299, "text": null }, { "code": "<?php// PHP implementation of the approach // Utility function to print the// contents of the arrayfunction printArr($b, $n){ for ($i = 0; $i < $n; $i++) echo $b[$i] . \" \";} // Function to build array B[]function ModifiedArray($a, $n){ // Lower and upper limits $l = 0; $r = PHP_INT_MAX; // To store the required array $b = array(0); // Apply greedy approach for ($i = 0; $i < $n / 2; $i++) { $b[$i] = max($l, $a[$i] - $r); $b[$n - $i - 1] = $a[$i] - $b[$i]; $l = $b[$i]; $r = $b[$n - $i - 1]; } // Print the built array b[] printArr($b, $n);} // Driver code$a = array( 5, 6 );$n = sizeof($a);ModifiedArray($a, 2 * $n); // This code is contributed// by Akanksha Rai?>", "e": 31948, "s": 31209, "text": null }, { "code": "<script> // Javascript program of the above approach // Utility function to print // the contents of the array function printArr(b, n) { for (let i = 0; i < n; i++) { document.write(\" \" + b[i] + \" \"); } } // Function to build array B[] function ModifiedArray(a, n) { // Lower and upper limits let l = 0, r = Number.MAX_VALUE; // To store the required array let b = Array(n).fill(0); // Apply greedy approach for (let i = 0; i < n / 2; i++) { b[i] = Math.max(l, a[i] - r); b[n - i - 1] = a[i] - b[i]; l = b[i]; r = b[n - i - 1]; } // Print the built array b[] printArr(b, n);} // Driver code let a = [ 5, 6 ]; let n = a.length ; ModifiedArray(a, 2 * n); </script>", "e": 32765, "s": 31948, "text": null }, { "code": null, "e": 32773, "s": 32765, "text": "0 1 5 5" }, { "code": null, "e": 32791, "s": 32775, "text": "Shashank_Sharma" }, { "code": null, "e": 32804, "s": 32791, "text": "Akanksha_Rai" }, { "code": null, "e": 32819, "s": 32804, "text": "Shivi_Aggarwal" }, { "code": null, "e": 32829, "s": 32819, "text": "Sach_Code" }, { "code": null, "e": 32844, "s": 32829, "text": "chinmoy1997pal" }, { "code": null, "e": 32857, "s": 32844, "text": "ankita_saini" }, { "code": null, "e": 32876, "s": 32857, "text": "programming-puzzle" }, { "code": null, "e": 32900, "s": 32876, "text": "Competitive Programming" }, { "code": null, "e": 32907, "s": 32900, "text": "Greedy" }, { "code": null, "e": 32920, "s": 32907, "text": "Mathematical" }, { "code": null, "e": 32927, "s": 32920, "text": "Greedy" }, { "code": null, "e": 32940, "s": 32927, "text": "Mathematical" }, { "code": null, "e": 33038, "s": 32940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33116, "s": 33038, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 33145, "s": 33116, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 33183, "s": 33145, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 33224, "s": 33183, "text": "7 Best Coding Challenge Websites in 2020" }, { "code": null, "e": 33283, "s": 33224, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 33334, "s": 33283, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 33392, "s": 33334, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 33443, "s": 33392, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 33470, "s": 33443, "text": "Program for array rotation" } ]
Shift() vs pop() Method in JavaScript - GeeksforGeeks
18 Jan, 2021 JavaScript shift() and pop() methods are used to remove an element from an array. But there is a little difference between them. Shift() method removes the first element and whereas the pop() method removes the last element from an array. The Shift() returns the removed first element of the array. If the array is empty then this function returns undefined whereas the pop() method turns the removed element array. If the array is empty, then this function returns undefined. Both the method is used for reducing the length of the array by 1. Both shift() and pop() are the in-built methods of the object array. Both methods will change the original array. Example: Below is an example of the array shift() method. Javascript <script> function func() { // Original array var array = ["GFG", "Geeks", "for", "Geeks"]; // Checking for condition in array var value = array.shift(); document.write(value); document.write("<br />"); document.write(array); } func(); </script> Output: GFG Geeks, for, Geeks Example 2: Below is the example of the array pop() method. Javascript <script> function func() { var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks']; // Popping the last element from the array document.write(arr.pop()); } func(); </script> Output: GeeksforGeeks Supported browsers: Google Chrome Microsoft Edge Mozilla Firefox Safari Opera JavaScript-Methods 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n18 Jan, 2021" }, { "code": null, "e": 26785, "s": 26545, "text": "JavaScript shift() and pop() methods are used to remove an element from an array. But there is a little difference between them. Shift() method removes the first element and whereas the pop() method removes the last element from an array. " }, { "code": null, "e": 27023, "s": 26785, "text": "The Shift() returns the removed first element of the array. If the array is empty then this function returns undefined whereas the pop() method turns the removed element array. If the array is empty, then this function returns undefined." }, { "code": null, "e": 27090, "s": 27023, "text": "Both the method is used for reducing the length of the array by 1." }, { "code": null, "e": 27159, "s": 27090, "text": "Both shift() and pop() are the in-built methods of the object array." }, { "code": null, "e": 27204, "s": 27159, "text": "Both methods will change the original array." }, { "code": null, "e": 27263, "s": 27204, "text": "Example: Below is an example of the array shift() method. " }, { "code": null, "e": 27274, "s": 27263, "text": "Javascript" }, { "code": "<script> function func() { // Original array var array = [\"GFG\", \"Geeks\", \"for\", \"Geeks\"]; // Checking for condition in array var value = array.shift(); document.write(value); document.write(\"<br />\"); document.write(array); } func(); </script> ", "e": 27560, "s": 27274, "text": null }, { "code": null, "e": 27569, "s": 27560, "text": "Output: " }, { "code": null, "e": 27591, "s": 27569, "text": "GFG\nGeeks, for, Geeks" }, { "code": null, "e": 27650, "s": 27591, "text": "Example 2: Below is the example of the array pop() method." }, { "code": null, "e": 27661, "s": 27650, "text": "Javascript" }, { "code": "<script> function func() { var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks']; // Popping the last element from the array document.write(arr.pop()); } func(); </script> ", "e": 27886, "s": 27661, "text": null }, { "code": null, "e": 27896, "s": 27886, "text": "Output: " }, { "code": null, "e": 27910, "s": 27896, "text": "GeeksforGeeks" }, { "code": null, "e": 27930, "s": 27910, "text": "Supported browsers:" }, { "code": null, "e": 27944, "s": 27930, "text": "Google Chrome" }, { "code": null, "e": 27959, "s": 27944, "text": "Microsoft Edge" }, { "code": null, "e": 27975, "s": 27959, "text": "Mozilla Firefox" }, { "code": null, "e": 27982, "s": 27975, "text": "Safari" }, { "code": null, "e": 27988, "s": 27982, "text": "Opera" }, { "code": null, "e": 28007, "s": 27988, "text": "JavaScript-Methods" }, { "code": null, "e": 28018, "s": 28007, "text": "JavaScript" }, { "code": null, "e": 28035, "s": 28018, "text": "Web Technologies" }, { "code": null, "e": 28133, "s": 28035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28173, "s": 28133, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28234, "s": 28173, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28275, "s": 28234, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28297, "s": 28275, "text": "JavaScript | Promises" }, { "code": null, "e": 28351, "s": 28297, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28391, "s": 28351, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28424, "s": 28391, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28467, "s": 28424, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28529, "s": 28467, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Top 50 TCP/IP interview questions and answers - GeeksforGeeks
08 Sep, 2021 1. Explain the range of TCP/IP classes? 2. What are Pvt. IP address? The private IP address of a system is the IP address that is used to communicate within the same network. Using private IP data, information can be sent or received within the same network. For more details please refer difference between private and public IP addresses. 3. Explain does IP protects data on the network? IP itself doesn’t guarantee delivering data correctly. It leaves all data protection to the transport protocol. Both TCP and UDP have mechanisms that guarantee that the data they deliver to an application is correct. Using the IP layer, the correct destination of the packet is identified & delivered. The Transport layer protocols(TCP/UDP) check if the data delivered is correct using the Checksum mechanism. However, if the destination IP is not alive, the packet is hopped by decreasing the TTL (Time to leave) field and when it becomes zero, the packet is lost and undelivered. If the transport layer is UDP, the source doesn’t know of the failure in the delivery of the packet. For more details please refer IP address 4.Tell the name of the data Unit of the Transport layer? The protocol data unit of the transport layer is a segment or datagram. 5. Tell the name of the data unit to send by the Internet layer? The protocol data unit of the internet layer is a packet. 6.The difference between TCP and UDP protocols? For more details please refer difference between TCP and UDP article. 7.How TCP protocol provides reliability? TCP is reliable as it uses checksum for error detection, attempts to recover lost or corrupted packets by re-transmission, acknowledgment policy, and timers. It uses features like byte numbers and sequence numbers and acknowledgment numbers so as to ensure reliability. 8.Write down the name of services provided by TCP? Process to process communication Stream orientation Full duplex service Multiplexing Reliability For more details please refer TCP/IP in the computer networking article. 9.Explain TCP protocol header format? For more details, please read TCP/IP model article. 10.Write the name of all TCP “Flag”? A TCP Flag field contains 6 different flags, namely: URG: Urgent pointer is valid ACK: Acknowledgement number is valid( used in case of cumulative acknowledgment) PSH: Request for push RST: Reset the connection SYN: Synchronize sequence numbers FIN: Terminate the connection For more details, please read TCP/IP model article. 11. What is the role of the TCP checksum field? One of the important fields of TCP protocol format. It is 16 bits long. This field holds the checksum for error control. It is mandatory in TCP as opposed to UDP. For more details, please read TCP/IP model article. 12.What is PORT? A port is basically a physical docking point that is basically used to connect the external devices to the computer, or we can say that a port acts as an interface between the computer and the external devices, e.g., we can connect hard drives and printers to the computer with the help of ports. For more details please refer to various TCP and UDP ports article. 13.Write the name of the Well-Known Port used by TCP? For more details please refer to various TCP and UDP ports article. 14.Define the term Endpoint in TCP? TcpEndpoint allows you to easily establish and communicate over TCP/IP network connections between client and server processes, possibly residing on different hosts. The TcpEndpoint class follows a telephone-like model of networking: clients “call” servers and servers “answer” clients. Once a network connection is established between a client and a server, the two can “talk” to each other by reading from and writing to the connection. 15.Explain the error control mechanism in TCP? TCP protocol has methods for finding out corrupted segments, missing segments, out-of-order segments, and duplicated segments.Error control in TCP is mainly done through the use of three simple techniques : Checksum Acknowledgment Retransmission Checksum Acknowledgment Retransmission 16.Explain congestion? A state occurring in the network layer when the message traffic is so heavy that it slows down network response time is known as congestion. For more details please read TCP congestion control article. 17.What is the difference between stop-and-wait protocol & sliding window protocol? Efficiency of Stop-and-Wait Protocol is 1/(1+2*a) Efficiency of sliding window protocol is N/(1+2*a) 18.What is round trip time? The length of time taken by a data packet to be sent to a destination includes the time it takes for an acknowledgment of that packet to be received back at the original place. For more details please refer to What is RTT article. 19.What is the significance of TCP acknowledgments? TCP acknowledgments are used to acknowledge packets that are successfully received by the host. The flag is set if the acknowledgment number field contains a valid acknowledgment number.For more details, please read TCP/IP model article. 20.What is retransmission? The TCP retransmission means resending the packets over the network that have been either lost or damaged. Here, retransmission is a mechanism used by protocols such as TCP to provide reliable communication. Here, reliable communication means that the protocol guarantees the packet’s delivery even if the data packet has been lost or damaged. The networks are unreliable and do not guarantee the delay or the retransmission of the lost or damaged packets. The network, which uses a combination of acknowledgment and retransmission of damaged or lost packets, offers reliability. For more details please read TCP congestion control article. 21.If TCP round trip time, RTT is currently 30m sec and the following acknowledgment comes in after 26, 32 and 24 m sec respectively what is the new RTT estimate?(Use α = 0.9) The formula for estimate new RTT new RTT = 0.9*30+(1-0.9)*26 new RTT = 29.6 For more detail please refer what is RTT article. 22. Write down features of TCP? Connection-oriented: An application requests a “connection” to the destination and uses the connection to transfer data Stream Data transfer: It is the duty of TCP to pack this byte stream into packets, known as TCP segments, which are passed to the IP layer for transmission to the destination device. Reliable: It recovers data from the network layer if data is damaged, duplicated, or corrupted. Point to Point: TCP connection provides end-to-end delivery. Interoperability: It eliminates cross-platform boundaries. Error and flow control: Error-checking, flow-control, and acknowledgment functions. Name resolution: It helps in solving human-readable names into IP addresses. Routability: TCP/IP is a routable protocol, It helps in resolving logical addresses. Full Duplex: It provides connection in both directions. For more details, please read TCP/IP model article. 23.What is SCTP protocol? SCTP stands for Stream Control Transmission Protocol. It is a connection-oriented protocol on computer networks that provides a full-duplex association, i.e., transmitting multiple streams of data between two endpoints at the same time that have established a connection in the network. It is sometimes referred to as next-generation TCP or TCPng. SCTP makes it easier to support telephonic conversation on the Internet. A telephonic conversation requires the transmitting of the voice along with other data at the same time on both ends. The SCTP protocol makes it easier to establish a reliable connection.SCTP is also intended to make it easier to establish connections over the wireless networks and managing the transmission of multimedia data. SCTP is a standard protocol (RFC 2960) and is developed by the Internet Engineering Task Force (IETF). For more details please read the SCTP full form article. 24.Explain the process of three-way handshaking protocol? Process of three-way handshaking protocol Step 1 (SYN): In the first step, the client wants to establish a connection with the server, so it sends a segment with SYN(Synchronize Sequence Number) which informs the server that the client is likely to start communication and with what sequence number it starts segments. Step 2 (SYN + ACK): Server responds to the client request with the SYN-ACK signal bits set. Acknowledgment (ACK) signifies the response of the segment it received and SYN signifies with what sequence number it is likely to start the segment. Step 3 (ACK): In the final part, the client acknowledges the response of the server and they both establish a reliable connection with which they will start the actual data transfer. Steps 1, 2 establish the connection parameter (sequence number) for one direction and it is acknowledged. Steps 2, 3 establish the connection parameter (sequence number) for the other direction and it is acknowledged. With these, full-duplex communication is established. For more details please read TCP-3 way handshake process. 25.Difference between Leaky bucket and Token bucket algorithm? For more detail please read Congestion control in the computer network article. 26.Write advantages of the token bucket over the Leaky bucket algorithm? If a bucket is full in tokens, tokens are discarded, not packets. While in a leaky bucket, packets are discarded. Token Bucket can send large bursts at a faster rate, while buckets always send packets at a constant rate. For more detail please read Congestion control in the computer network article. 27.What is the difference between connection-oriented service and connection-less? 28.What are the TCP connections phases? In TCP, connection-oriented transmission requires three phases: Connection establishment Data Transfer Connection termination For more detail read TCP connection establishment article. 29.Write features of TCP sliding window? Features of the TCP sliding window: It uses variable-size windows to provide flow control as well as reliable transfer. TCP connections are full-duplex, two transfers proceed simultaneously over each connection, one in each direction. It support machine of various speed and size communicate through a network and also routers of various speeds. 30.What is the maximum size of the TCP header? What is the minimum size of TCP header? Maximum size of the TCP header = 60 bytes Minimum size of the TCP header = 20 bytes 31.Do port addresses need to be unique? Why or why not? Why are port addresses shorter than IP addresses? Port addressing is done by the transport layer, which is the 4th layer of the OSI (Open System Interconnection) Model. Port addresses are short because they have to perform the end-to-end delivery of the message and the protocols are less in number than computer systems, therefore, port addresses are less than IP addresses. The IP address refers to the computer/device connected to the network and the port address refers to a particular protocol to communicate with the server as per client request. For more details read TCP/IP ports and its application article. 32.Are both UDP and IP unreliable to the same degree? Why or Why not? No, UDP is unreliable and connectionless. While IP unreliability lies in the upper layer protocols. The IP packet becomes reliable if the upper layer protocol is TCP. In terms of data integrity, UDP is more reliable than IP. The checksum in the IP header only applies to the header itself, not to the whole packet. The UDP checksum applies to the whole user segment. 33.Define the term Datagram? It is a logical unit to transfer information over the network. This data is transmitted from source to destination. It does not guarantee that data will be delivered or lost on the way. It has two section headers and a data payload. It travels in-network without establishing a prior virtual network between source and destination., ie. unlike, it has no prior information about the path between source and destination. This data is frequently divided into smaller parts and transmitted to the defined route. 34.What are the Registered port and Dynamic port? Registered port: The ports ranging from 1024 to 49151 are not assigned and controlled by an IANA. They can only be registered with IANA to prevent duplication. Dynamic port: This port ranging from 49152 to 65535 is neither controlled nor registered. They can be used in any process. 35.Write the importance of TTL field? The lifespan or lifetime of data that is being sent. Once, after that specified time is over or elapsed, the data will be discarded or it can also be stated as a number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network. 36.An IPv4 packet has arrived with the first 8 bits as shown: 01000010 The receiver discards the packet. Why? An IPv4 packet has arrived with the first 8 bits being 01000010 The receiver discards the packet because the first 4 bits represent version IPV4.and another 4 bits represent header length (/ 4) which should range between 20 to 60 bytes. Here 0010 represents header length, is equal to 2 * 4 = 8. So, the receiver will reject the packet. 37.In an IPv4 packet, the value of HLEN is 1000 in binary. How many bytes of options are being carried by this packet? If an IPv4 packet, the value of HLEN is 1000 in binary, then 32 bytes of options are carried by this packet. HLEN = 1000 = 8 8*4 = 32 38.What are open loop congestion control and closed-loop congestion control techniques? Open-loop congestion control policies are applied to prevent congestion before it happens. The congestion control is handled either by the source or the destination. Closed-loop congestion control technique is used to treat or alleviate congestion after it happens. 39.Which fields of the IPv4 header change from router to router? Total length field and header checksum of IPv4 header change from router to router. 40.The value of HLEN in an IPv4 datagram is 7.How many option bytes are present? If the value of the HLEN field is 7, then there are 28 (since 7 × 4 = 28) bytes included in the header. 41.Can the value of the header length in an IPv4 packet be less than 5? The value of the header length field of an IP packet can never be less than 5 because every IP datagram must have at least a base header that has a fixed size of 20 bytes. 42.A host is sending 100 datagrams to another host. If the identification number of the first datagram is 1024, what is the identification number of the last(in IPv4)? if a source is sending 100 datagrams and for the first datagram identification no is 1024 then for the last datagram identification number will be 1024 + 99 = 1123. 43.Explain the reason for the elimination of the checksum in the IPv6 header? The checksum is eliminated in IPv6 because it is provided by upper-layer protocols; it is therefore not needed at this level. 44.Write down the name of three strategies used to handle the transmission from IPv4 to IPv6? Dual-stack Tunneling Header translation 45.What is tunneling? A technique of internetworking called Tunneling is used when the source and destination networks of the same type are to be connected through a network of a different type. 46.An IP packet has arrived with the first 8 bits as 01000010. What is the version?The first 4-bits show version i.e. 0100 which belongs to IP version 4. 47.What is fragmentation? Fragmentation is an important function of the network layer. It is a technique in which gateways break up or divide larger packets into smaller ones called fragments. Each fragment is then sent as a separate internal packet. Each fragment has its own separate header and trailer. Sometimes, a fragmented datagram also gets fragmented when it encounters a network that handles smaller fragments. Thus, a datagram can be fragmented several times before it reaches its final destination. The reverse process of fragmentation is difficult. Reassembly of fragments is usually done by the destination host because each fragment has become an independent datagram. 48.Suppose the round trip propagation delay for a 10 Mbps Ethernet having a 48-bit jamming signal is 46.4 ms. What is the minimum frame size? Transmission Speed = 10Mbps.Round trip propagation delay = 46.4 msThe minimum frame size = (Round Trip Propagation Delay) * (Transmission Speed) = 10*(10^6)*46.4*(10^-3) = 464 * 10^3 = 464 Kbit 49.In the slow start phase of the TCP congestion control algorithm, what is the size of the congestion window? In the slow start phase of the TCP congestion control algorithm, the size of the congestion window increases exponentially. 50.What is the maximum window size for data transmission using Selective Reject protocol with n-bit frame sequence number? The maximum window size for data transmission using the Selective Reject protocol with the n-bit frame sequence number is . interview-questions Computer Networks Computer Subject Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data encryption standard (DES) | Set 1 Differences between IPv4 and IPv6 Types of Network Topology Socket Programming in Python TCP 3-Way Handshake Process SDE SHEET - A Complete Guide for SDE Preparation Introduction to Algorithms Software Engineering | Coupling and Cohesion Difference between NP hard and NP complete problem Software Engineering | Prototyping Model
[ { "code": null, "e": 25213, "s": 25185, "text": "\n08 Sep, 2021" }, { "code": null, "e": 25253, "s": 25213, "text": "1. Explain the range of TCP/IP classes?" }, { "code": null, "e": 25282, "s": 25253, "text": "2. What are Pvt. IP address?" }, { "code": null, "e": 25554, "s": 25282, "text": "The private IP address of a system is the IP address that is used to communicate within the same network. Using private IP data, information can be sent or received within the same network. For more details please refer difference between private and public IP addresses." }, { "code": null, "e": 25603, "s": 25554, "text": "3. Explain does IP protects data on the network?" }, { "code": null, "e": 25820, "s": 25603, "text": "IP itself doesn’t guarantee delivering data correctly. It leaves all data protection to the transport protocol. Both TCP and UDP have mechanisms that guarantee that the data they deliver to an application is correct." }, { "code": null, "e": 26327, "s": 25820, "text": "Using the IP layer, the correct destination of the packet is identified & delivered. The Transport layer protocols(TCP/UDP) check if the data delivered is correct using the Checksum mechanism. However, if the destination IP is not alive, the packet is hopped by decreasing the TTL (Time to leave) field and when it becomes zero, the packet is lost and undelivered. If the transport layer is UDP, the source doesn’t know of the failure in the delivery of the packet. For more details please refer IP address" }, { "code": null, "e": 26384, "s": 26327, "text": "4.Tell the name of the data Unit of the Transport layer?" }, { "code": null, "e": 26456, "s": 26384, "text": "The protocol data unit of the transport layer is a segment or datagram." }, { "code": null, "e": 26521, "s": 26456, "text": "5. Tell the name of the data unit to send by the Internet layer?" }, { "code": null, "e": 26579, "s": 26521, "text": "The protocol data unit of the internet layer is a packet." }, { "code": null, "e": 26627, "s": 26579, "text": "6.The difference between TCP and UDP protocols?" }, { "code": null, "e": 26697, "s": 26627, "text": "For more details please refer difference between TCP and UDP article." }, { "code": null, "e": 26738, "s": 26697, "text": "7.How TCP protocol provides reliability?" }, { "code": null, "e": 27009, "s": 26738, "text": "TCP is reliable as it uses checksum for error detection, attempts to recover lost or corrupted packets by re-transmission, acknowledgment policy, and timers. It uses features like byte numbers and sequence numbers and acknowledgment numbers so as to ensure reliability. " }, { "code": null, "e": 27060, "s": 27009, "text": "8.Write down the name of services provided by TCP?" }, { "code": null, "e": 27093, "s": 27060, "text": "Process to process communication" }, { "code": null, "e": 27112, "s": 27093, "text": "Stream orientation" }, { "code": null, "e": 27132, "s": 27112, "text": "Full duplex service" }, { "code": null, "e": 27145, "s": 27132, "text": "Multiplexing" }, { "code": null, "e": 27157, "s": 27145, "text": "Reliability" }, { "code": null, "e": 27230, "s": 27157, "text": "For more details please refer TCP/IP in the computer networking article." }, { "code": null, "e": 27268, "s": 27230, "text": "9.Explain TCP protocol header format?" }, { "code": null, "e": 27320, "s": 27268, "text": "For more details, please read TCP/IP model article." }, { "code": null, "e": 27357, "s": 27320, "text": "10.Write the name of all TCP “Flag”?" }, { "code": null, "e": 27410, "s": 27357, "text": "A TCP Flag field contains 6 different flags, namely:" }, { "code": null, "e": 27439, "s": 27410, "text": "URG: Urgent pointer is valid" }, { "code": null, "e": 27520, "s": 27439, "text": "ACK: Acknowledgement number is valid( used in case of cumulative acknowledgment)" }, { "code": null, "e": 27542, "s": 27520, "text": "PSH: Request for push" }, { "code": null, "e": 27568, "s": 27542, "text": "RST: Reset the connection" }, { "code": null, "e": 27602, "s": 27568, "text": "SYN: Synchronize sequence numbers" }, { "code": null, "e": 27632, "s": 27602, "text": "FIN: Terminate the connection" }, { "code": null, "e": 27684, "s": 27632, "text": "For more details, please read TCP/IP model article." }, { "code": null, "e": 27732, "s": 27684, "text": "11. What is the role of the TCP checksum field?" }, { "code": null, "e": 27948, "s": 27732, "text": "One of the important fields of TCP protocol format. It is 16 bits long. This field holds the checksum for error control. It is mandatory in TCP as opposed to UDP. For more details, please read TCP/IP model article. " }, { "code": null, "e": 27965, "s": 27948, "text": "12.What is PORT?" }, { "code": null, "e": 28330, "s": 27965, "text": "A port is basically a physical docking point that is basically used to connect the external devices to the computer, or we can say that a port acts as an interface between the computer and the external devices, e.g., we can connect hard drives and printers to the computer with the help of ports. For more details please refer to various TCP and UDP ports article." }, { "code": null, "e": 28384, "s": 28330, "text": "13.Write the name of the Well-Known Port used by TCP?" }, { "code": null, "e": 28452, "s": 28384, "text": "For more details please refer to various TCP and UDP ports article." }, { "code": null, "e": 28488, "s": 28452, "text": "14.Define the term Endpoint in TCP?" }, { "code": null, "e": 28928, "s": 28488, "text": "TcpEndpoint allows you to easily establish and communicate over TCP/IP network connections between client and server processes, possibly residing on different hosts. The TcpEndpoint class follows a telephone-like model of networking: clients “call” servers and servers “answer” clients. Once a network connection is established between a client and a server, the two can “talk” to each other by reading from and writing to the connection." }, { "code": null, "e": 28975, "s": 28928, "text": "15.Explain the error control mechanism in TCP?" }, { "code": null, "e": 29182, "s": 28975, "text": "TCP protocol has methods for finding out corrupted segments, missing segments, out-of-order segments, and duplicated segments.Error control in TCP is mainly done through the use of three simple techniques :" }, { "code": null, "e": 29221, "s": 29182, "text": "Checksum Acknowledgment Retransmission" }, { "code": null, "e": 29231, "s": 29221, "text": "Checksum " }, { "code": null, "e": 29247, "s": 29231, "text": "Acknowledgment " }, { "code": null, "e": 29262, "s": 29247, "text": "Retransmission" }, { "code": null, "e": 29285, "s": 29262, "text": "16.Explain congestion?" }, { "code": null, "e": 29487, "s": 29285, "text": "A state occurring in the network layer when the message traffic is so heavy that it slows down network response time is known as congestion. For more details please read TCP congestion control article." }, { "code": null, "e": 29571, "s": 29487, "text": "17.What is the difference between stop-and-wait protocol & sliding window protocol?" }, { "code": null, "e": 29611, "s": 29571, "text": "Efficiency of Stop-and-Wait Protocol is" }, { "code": null, "e": 29621, "s": 29611, "text": "1/(1+2*a)" }, { "code": null, "e": 29662, "s": 29621, "text": "Efficiency of sliding window protocol is" }, { "code": null, "e": 29672, "s": 29662, "text": "N/(1+2*a)" }, { "code": null, "e": 29700, "s": 29672, "text": "18.What is round trip time?" }, { "code": null, "e": 29931, "s": 29700, "text": "The length of time taken by a data packet to be sent to a destination includes the time it takes for an acknowledgment of that packet to be received back at the original place. For more details please refer to What is RTT article." }, { "code": null, "e": 29983, "s": 29931, "text": "19.What is the significance of TCP acknowledgments?" }, { "code": null, "e": 30221, "s": 29983, "text": "TCP acknowledgments are used to acknowledge packets that are successfully received by the host. The flag is set if the acknowledgment number field contains a valid acknowledgment number.For more details, please read TCP/IP model article." }, { "code": null, "e": 30248, "s": 30221, "text": "20.What is retransmission?" }, { "code": null, "e": 30889, "s": 30248, "text": "The TCP retransmission means resending the packets over the network that have been either lost or damaged. Here, retransmission is a mechanism used by protocols such as TCP to provide reliable communication. Here, reliable communication means that the protocol guarantees the packet’s delivery even if the data packet has been lost or damaged. The networks are unreliable and do not guarantee the delay or the retransmission of the lost or damaged packets. The network, which uses a combination of acknowledgment and retransmission of damaged or lost packets, offers reliability. For more details please read TCP congestion control article." }, { "code": null, "e": 31065, "s": 30889, "text": "21.If TCP round trip time, RTT is currently 30m sec and the following acknowledgment comes in after 26, 32 and 24 m sec respectively what is the new RTT estimate?(Use α = 0.9)" }, { "code": null, "e": 31099, "s": 31065, "text": "The formula for estimate new RTT " }, { "code": null, "e": 31127, "s": 31099, "text": "new RTT = 0.9*30+(1-0.9)*26" }, { "code": null, "e": 31142, "s": 31127, "text": "new RTT = 29.6" }, { "code": null, "e": 31192, "s": 31142, "text": "For more detail please refer what is RTT article." }, { "code": null, "e": 31224, "s": 31192, "text": "22. Write down features of TCP?" }, { "code": null, "e": 31344, "s": 31224, "text": "Connection-oriented: An application requests a “connection” to the destination and uses the connection to transfer data" }, { "code": null, "e": 31527, "s": 31344, "text": "Stream Data transfer: It is the duty of TCP to pack this byte stream into packets, known as TCP segments, which are passed to the IP layer for transmission to the destination device." }, { "code": null, "e": 31623, "s": 31527, "text": "Reliable: It recovers data from the network layer if data is damaged, duplicated, or corrupted." }, { "code": null, "e": 31684, "s": 31623, "text": "Point to Point: TCP connection provides end-to-end delivery." }, { "code": null, "e": 31743, "s": 31684, "text": "Interoperability: It eliminates cross-platform boundaries." }, { "code": null, "e": 31827, "s": 31743, "text": "Error and flow control: Error-checking, flow-control, and acknowledgment functions." }, { "code": null, "e": 31905, "s": 31827, "text": " Name resolution: It helps in solving human-readable names into IP addresses." }, { "code": null, "e": 31949, "s": 31905, "text": "Routability: TCP/IP is a routable protocol," }, { "code": null, "e": 31990, "s": 31949, "text": "It helps in resolving logical addresses." }, { "code": null, "e": 32046, "s": 31990, "text": "Full Duplex: It provides connection in both directions." }, { "code": null, "e": 32098, "s": 32046, "text": "For more details, please read TCP/IP model article." }, { "code": null, "e": 32124, "s": 32098, "text": "23.What is SCTP protocol?" }, { "code": null, "e": 33034, "s": 32124, "text": "SCTP stands for Stream Control Transmission Protocol. It is a connection-oriented protocol on computer networks that provides a full-duplex association, i.e., transmitting multiple streams of data between two endpoints at the same time that have established a connection in the network. It is sometimes referred to as next-generation TCP or TCPng. SCTP makes it easier to support telephonic conversation on the Internet. A telephonic conversation requires the transmitting of the voice along with other data at the same time on both ends. The SCTP protocol makes it easier to establish a reliable connection.SCTP is also intended to make it easier to establish connections over the wireless networks and managing the transmission of multimedia data. SCTP is a standard protocol (RFC 2960) and is developed by the Internet Engineering Task Force (IETF). For more details please read the SCTP full form article." }, { "code": null, "e": 33092, "s": 33034, "text": "24.Explain the process of three-way handshaking protocol?" }, { "code": null, "e": 33134, "s": 33092, "text": "Process of three-way handshaking protocol" }, { "code": null, "e": 33411, "s": 33134, "text": "Step 1 (SYN): In the first step, the client wants to establish a connection with the server, so it sends a segment with SYN(Synchronize Sequence Number) which informs the server that the client is likely to start communication and with what sequence number it starts segments." }, { "code": null, "e": 33653, "s": 33411, "text": "Step 2 (SYN + ACK): Server responds to the client request with the SYN-ACK signal bits set. Acknowledgment (ACK) signifies the response of the segment it received and SYN signifies with what sequence number it is likely to start the segment." }, { "code": null, "e": 33836, "s": 33653, "text": "Step 3 (ACK): In the final part, the client acknowledges the response of the server and they both establish a reliable connection with which they will start the actual data transfer." }, { "code": null, "e": 34108, "s": 33836, "text": "Steps 1, 2 establish the connection parameter (sequence number) for one direction and it is acknowledged. Steps 2, 3 establish the connection parameter (sequence number) for the other direction and it is acknowledged. With these, full-duplex communication is established." }, { "code": null, "e": 34167, "s": 34108, "text": "For more details please read TCP-3 way handshake process. " }, { "code": null, "e": 34231, "s": 34167, "text": "25.Difference between Leaky bucket and Token bucket algorithm?" }, { "code": null, "e": 34311, "s": 34231, "text": "For more detail please read Congestion control in the computer network article." }, { "code": null, "e": 34384, "s": 34311, "text": "26.Write advantages of the token bucket over the Leaky bucket algorithm?" }, { "code": null, "e": 34498, "s": 34384, "text": "If a bucket is full in tokens, tokens are discarded, not packets. While in a leaky bucket, packets are discarded." }, { "code": null, "e": 34605, "s": 34498, "text": "Token Bucket can send large bursts at a faster rate, while buckets always send packets at a constant rate." }, { "code": null, "e": 34685, "s": 34605, "text": "For more detail please read Congestion control in the computer network article." }, { "code": null, "e": 34768, "s": 34685, "text": "27.What is the difference between connection-oriented service and connection-less?" }, { "code": null, "e": 34808, "s": 34768, "text": "28.What are the TCP connections phases?" }, { "code": null, "e": 34873, "s": 34808, "text": "In TCP, connection-oriented transmission requires three phases: " }, { "code": null, "e": 34898, "s": 34873, "text": "Connection establishment" }, { "code": null, "e": 34912, "s": 34898, "text": "Data Transfer" }, { "code": null, "e": 34935, "s": 34912, "text": "Connection termination" }, { "code": null, "e": 34994, "s": 34935, "text": "For more detail read TCP connection establishment article." }, { "code": null, "e": 35036, "s": 34994, "text": "29.Write features of TCP sliding window? " }, { "code": null, "e": 35072, "s": 35036, "text": "Features of the TCP sliding window:" }, { "code": null, "e": 35156, "s": 35072, "text": "It uses variable-size windows to provide flow control as well as reliable transfer." }, { "code": null, "e": 35271, "s": 35156, "text": "TCP connections are full-duplex, two transfers proceed simultaneously over each connection, one in each direction." }, { "code": null, "e": 35382, "s": 35271, "text": "It support machine of various speed and size communicate through a network and also routers of various speeds." }, { "code": null, "e": 35469, "s": 35382, "text": "30.What is the maximum size of the TCP header? What is the minimum size of TCP header?" }, { "code": null, "e": 35511, "s": 35469, "text": "Maximum size of the TCP header = 60 bytes" }, { "code": null, "e": 35553, "s": 35511, "text": "Minimum size of the TCP header = 20 bytes" }, { "code": null, "e": 35659, "s": 35553, "text": "31.Do port addresses need to be unique? Why or why not? Why are port addresses shorter than IP addresses?" }, { "code": null, "e": 36226, "s": 35659, "text": "Port addressing is done by the transport layer, which is the 4th layer of the OSI (Open System Interconnection) Model. Port addresses are short because they have to perform the end-to-end delivery of the message and the protocols are less in number than computer systems, therefore, port addresses are less than IP addresses. The IP address refers to the computer/device connected to the network and the port address refers to a particular protocol to communicate with the server as per client request. For more details read TCP/IP ports and its application article." }, { "code": null, "e": 36296, "s": 36226, "text": "32.Are both UDP and IP unreliable to the same degree? Why or Why not?" }, { "code": null, "e": 36665, "s": 36296, "text": "No, UDP is unreliable and connectionless. While IP unreliability lies in the upper layer protocols. The IP packet becomes reliable if the upper layer protocol is TCP. In terms of data integrity, UDP is more reliable than IP. The checksum in the IP header only applies to the header itself, not to the whole packet. The UDP checksum applies to the whole user segment." }, { "code": null, "e": 36694, "s": 36665, "text": "33.Define the term Datagram?" }, { "code": null, "e": 37203, "s": 36694, "text": "It is a logical unit to transfer information over the network. This data is transmitted from source to destination. It does not guarantee that data will be delivered or lost on the way. It has two section headers and a data payload. It travels in-network without establishing a prior virtual network between source and destination., ie. unlike, it has no prior information about the path between source and destination. This data is frequently divided into smaller parts and transmitted to the defined route." }, { "code": null, "e": 37253, "s": 37203, "text": "34.What are the Registered port and Dynamic port?" }, { "code": null, "e": 37413, "s": 37253, "text": "Registered port: The ports ranging from 1024 to 49151 are not assigned and controlled by an IANA. They can only be registered with IANA to prevent duplication." }, { "code": null, "e": 37536, "s": 37413, "text": "Dynamic port: This port ranging from 49152 to 65535 is neither controlled nor registered. They can be used in any process." }, { "code": null, "e": 37574, "s": 37536, "text": "35.Write the importance of TTL field?" }, { "code": null, "e": 37955, "s": 37574, "text": "The lifespan or lifetime of data that is being sent. Once, after that specified time is over or elapsed, the data will be discarded or it can also be stated as a number of hops that packet is set to exist in the network, after which that packet is discarded. The purpose of the TTL field is to avoid a situation in which an undeliverable datagram keeps circulating in the network." }, { "code": null, "e": 38065, "s": 37955, "text": "36.An IPv4 packet has arrived with the first 8 bits as shown: 01000010 The receiver discards the packet. Why?" }, { "code": null, "e": 38402, "s": 38065, "text": "An IPv4 packet has arrived with the first 8 bits being 01000010 The receiver discards the packet because the first 4 bits represent version IPV4.and another 4 bits represent header length (/ 4) which should range between 20 to 60 bytes. Here 0010 represents header length, is equal to 2 * 4 = 8. So, the receiver will reject the packet." }, { "code": null, "e": 38521, "s": 38402, "text": "37.In an IPv4 packet, the value of HLEN is 1000 in binary. How many bytes of options are being carried by this packet?" }, { "code": null, "e": 38630, "s": 38521, "text": "If an IPv4 packet, the value of HLEN is 1000 in binary, then 32 bytes of options are carried by this packet." }, { "code": null, "e": 38647, "s": 38630, "text": "HLEN = 1000 = 8 " }, { "code": null, "e": 38656, "s": 38647, "text": "8*4 = 32" }, { "code": null, "e": 38744, "s": 38656, "text": "38.What are open loop congestion control and closed-loop congestion control techniques?" }, { "code": null, "e": 38911, "s": 38744, "text": "Open-loop congestion control policies are applied to prevent congestion before it happens. The congestion control is handled either by the source or the destination. " }, { "code": null, "e": 39011, "s": 38911, "text": "Closed-loop congestion control technique is used to treat or alleviate congestion after it happens." }, { "code": null, "e": 39076, "s": 39011, "text": "39.Which fields of the IPv4 header change from router to router?" }, { "code": null, "e": 39160, "s": 39076, "text": "Total length field and header checksum of IPv4 header change from router to router." }, { "code": null, "e": 39241, "s": 39160, "text": "40.The value of HLEN in an IPv4 datagram is 7.How many option bytes are present?" }, { "code": null, "e": 39346, "s": 39241, "text": "If the value of the HLEN field is 7, then there are 28 (since 7 × 4 = 28) bytes included in the header." }, { "code": null, "e": 39418, "s": 39346, "text": "41.Can the value of the header length in an IPv4 packet be less than 5?" }, { "code": null, "e": 39590, "s": 39418, "text": "The value of the header length field of an IP packet can never be less than 5 because every IP datagram must have at least a base header that has a fixed size of 20 bytes." }, { "code": null, "e": 39758, "s": 39590, "text": "42.A host is sending 100 datagrams to another host. If the identification number of the first datagram is 1024, what is the identification number of the last(in IPv4)?" }, { "code": null, "e": 39923, "s": 39758, "text": "if a source is sending 100 datagrams and for the first datagram identification no is 1024 then for the last datagram identification number will be 1024 + 99 = 1123." }, { "code": null, "e": 40001, "s": 39923, "text": "43.Explain the reason for the elimination of the checksum in the IPv6 header?" }, { "code": null, "e": 40127, "s": 40001, "text": "The checksum is eliminated in IPv6 because it is provided by upper-layer protocols; it is therefore not needed at this level." }, { "code": null, "e": 40221, "s": 40127, "text": "44.Write down the name of three strategies used to handle the transmission from IPv4 to IPv6?" }, { "code": null, "e": 40232, "s": 40221, "text": "Dual-stack" }, { "code": null, "e": 40242, "s": 40232, "text": "Tunneling" }, { "code": null, "e": 40261, "s": 40242, "text": "Header translation" }, { "code": null, "e": 40283, "s": 40261, "text": "45.What is tunneling?" }, { "code": null, "e": 40456, "s": 40283, "text": "A technique of internetworking called Tunneling is used when the source and destination networks of the same type are to be connected through a network of a different type." }, { "code": null, "e": 40610, "s": 40456, "text": "46.An IP packet has arrived with the first 8 bits as 01000010. What is the version?The first 4-bits show version i.e. 0100 which belongs to IP version 4." }, { "code": null, "e": 40636, "s": 40610, "text": "47.What is fragmentation?" }, { "code": null, "e": 41294, "s": 40636, "text": "Fragmentation is an important function of the network layer. It is a technique in which gateways break up or divide larger packets into smaller ones called fragments. Each fragment is then sent as a separate internal packet. Each fragment has its own separate header and trailer. Sometimes, a fragmented datagram also gets fragmented when it encounters a network that handles smaller fragments. Thus, a datagram can be fragmented several times before it reaches its final destination. The reverse process of fragmentation is difficult. Reassembly of fragments is usually done by the destination host because each fragment has become an independent datagram." }, { "code": null, "e": 41436, "s": 41294, "text": "48.Suppose the round trip propagation delay for a 10 Mbps Ethernet having a 48-bit jamming signal is 46.4 ms. What is the minimum frame size?" }, { "code": null, "e": 41630, "s": 41436, "text": "Transmission Speed = 10Mbps.Round trip propagation delay = 46.4 msThe minimum frame size = (Round Trip Propagation Delay) * (Transmission Speed) = 10*(10^6)*46.4*(10^-3) = 464 * 10^3 = 464 Kbit" }, { "code": null, "e": 41741, "s": 41630, "text": "49.In the slow start phase of the TCP congestion control algorithm, what is the size of the congestion window?" }, { "code": null, "e": 41865, "s": 41741, "text": "In the slow start phase of the TCP congestion control algorithm, the size of the congestion window increases exponentially." }, { "code": null, "e": 41988, "s": 41865, "text": "50.What is the maximum window size for data transmission using Selective Reject protocol with n-bit frame sequence number?" }, { "code": null, "e": 42112, "s": 41988, "text": "The maximum window size for data transmission using the Selective Reject protocol with the n-bit frame sequence number is ." }, { "code": null, "e": 42132, "s": 42112, "text": "interview-questions" }, { "code": null, "e": 42150, "s": 42132, "text": "Computer Networks" }, { "code": null, "e": 42167, "s": 42150, "text": "Computer Subject" }, { "code": null, "e": 42185, "s": 42167, "text": "Computer Networks" }, { "code": null, "e": 42283, "s": 42185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42322, "s": 42283, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 42356, "s": 42322, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 42382, "s": 42356, "text": "Types of Network Topology" }, { "code": null, "e": 42411, "s": 42382, "text": "Socket Programming in Python" }, { "code": null, "e": 42439, "s": 42411, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 42488, "s": 42439, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 42515, "s": 42488, "text": "Introduction to Algorithms" }, { "code": null, "e": 42560, "s": 42515, "text": "Software Engineering | Coupling and Cohesion" }, { "code": null, "e": 42611, "s": 42560, "text": "Difference between NP hard and NP complete problem" } ]
Lodash or Underscore - pick, pickBy, omit, omitBy - GeeksforGeeks
30 Jun, 2020 Javascript is Everywhere. The Javascript is used widely and it’s not limited to just only in your web browser but also widely used in the server-side as well. JavaScript is used by 95% of all the websites. Lodash or Underscore makes coding in Javascript much easier & also makes our code minimal, it works with arrays, numbers, objects, strings, etc. We can use Lodash basically with any JS based library or framework, for instance w/ Angular, React, VueJs, Node.Js, Vanilla JS, etc. Lodash’s modular methods are great for: Iterating arrays, objects, & stringsManipulating & testing valuesCreating composite functions Iterating arrays, objects, & strings Manipulating & testing values Creating composite functions Let’s go through very basic and most used Lodash methods which makes our day to day life easier & increase readability of our code. 1. pickBy 2. pick 3. omitBy 4. omit and so on.. Pick and Omit are contrary of each other, as the name describes omit is used to omit/exclude parameters from the object as per our needs on the other hand pick is used to pick/include elements defined. Examples: let geeksforgeeks = { "name" : "geeksforgeeks", "location" : "NCR", "vacancies" : null, "amenities" : ['free_breakfast','health_insurance'], "interview_process" : ["DSA","Technical","HR"] }; Now, to get only valid values from your object i.e., except null & undefined /* now validGFG object contains only valid (!null & !undefined) key-value pairs. */ let validGFG = _.pickBy(geeksforgeeks, v => !_.isUndefined(v) && !_.isNull(v)); To get all key value pairs from our validGFG object except some, we can simply do this : // this object contains all key-value pairs except amenities. let geeksInfoExceptAmenities = _.omit(validGFG, ['amenities']); We can do one step further to eliminate all the arrays/string(s)/number/etc. from our object, /* this object will contain only name & location just because we omitted all the array type from our object. */ let geeksInfoExceptInsideArrays = _.omitBy(validGFG, _.isArray); To get some specific key-value pairs, // this object contains name & location only. let geeksNameAndLocation = _.pick(validGFG, ['name','location']); We can use many combinations of above stated functions & handle our arrays, objects and much more quite easily. For much more, you can go through docs of Lodash. JavaScript - Underscore.js JavaScript-Lodash JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request How to Use the JavaScript Fetch API to Get Data? Node.js | fs.writeFileSync() Method JavaScript | Promises Set the value of an input field in JavaScript Form validation using HTML and JavaScript
[ { "code": null, "e": 25832, "s": 25804, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26038, "s": 25832, "text": "Javascript is Everywhere. The Javascript is used widely and it’s not limited to just only in your web browser but also widely used in the server-side as well. JavaScript is used by 95% of all the websites." }, { "code": null, "e": 26183, "s": 26038, "text": "Lodash or Underscore makes coding in Javascript much easier & also makes our code minimal, it works with arrays, numbers, objects, strings, etc." }, { "code": null, "e": 26316, "s": 26183, "text": "We can use Lodash basically with any JS based library or framework, for instance w/ Angular, React, VueJs, Node.Js, Vanilla JS, etc." }, { "code": null, "e": 26356, "s": 26316, "text": "Lodash’s modular methods are great for:" }, { "code": null, "e": 26450, "s": 26356, "text": "Iterating arrays, objects, & stringsManipulating & testing valuesCreating composite functions" }, { "code": null, "e": 26487, "s": 26450, "text": "Iterating arrays, objects, & strings" }, { "code": null, "e": 26517, "s": 26487, "text": "Manipulating & testing values" }, { "code": null, "e": 26546, "s": 26517, "text": "Creating composite functions" }, { "code": null, "e": 26678, "s": 26546, "text": "Let’s go through very basic and most used Lodash methods which makes our day to day life easier & increase readability of our code." }, { "code": null, "e": 26688, "s": 26678, "text": "1. pickBy" }, { "code": null, "e": 26696, "s": 26688, "text": "2. pick" }, { "code": null, "e": 26706, "s": 26696, "text": "3. omitBy" }, { "code": null, "e": 26726, "s": 26706, "text": "4. omit and so on.." }, { "code": null, "e": 26928, "s": 26726, "text": "Pick and Omit are contrary of each other, as the name describes omit is used to omit/exclude parameters from the object as per our needs on the other hand pick is used to pick/include elements defined." }, { "code": null, "e": 26938, "s": 26928, "text": "Examples:" }, { "code": null, "e": 27148, "s": 26938, "text": "let geeksforgeeks = {\n \"name\" : \"geeksforgeeks\",\n \"location\" : \"NCR\",\n \"vacancies\" : null,\n \"amenities\" : ['free_breakfast','health_insurance'],\n \"interview_process\" : [\"DSA\",\"Technical\",\"HR\"]\n};\n\n\n\n" }, { "code": null, "e": 27225, "s": 27148, "text": "Now, to get only valid values from your object i.e., except null & undefined" }, { "code": null, "e": 27398, "s": 27225, "text": "/* now validGFG object contains only \nvalid (!null & !undefined) key-value pairs. */\nlet validGFG = _.pickBy(geeksforgeeks, \n v => !_.isUndefined(v) && !_.isNull(v));\n\n\n\n" }, { "code": null, "e": 27487, "s": 27398, "text": "To get all key value pairs from our validGFG object except some, we can simply do this :" }, { "code": null, "e": 27617, "s": 27487, "text": "// this object contains all key-value pairs except amenities.\nlet geeksInfoExceptAmenities = _.omit(validGFG, ['amenities']);\n\n\n\n" }, { "code": null, "e": 27711, "s": 27617, "text": "We can do one step further to eliminate all the arrays/string(s)/number/etc. from our object," }, { "code": null, "e": 27892, "s": 27711, "text": "/* this object will contain only name & location just\nbecause we omitted all the array type from our object. */\nlet geeksInfoExceptInsideArrays = _.omitBy(validGFG, _.isArray);\n\n\n\n" }, { "code": null, "e": 27930, "s": 27892, "text": "To get some specific key-value pairs," }, { "code": null, "e": 28046, "s": 27930, "text": "// this object contains name & location only.\nlet geeksNameAndLocation = _.pick(validGFG, ['name','location']);\n\n\n\n" }, { "code": null, "e": 28158, "s": 28046, "text": "We can use many combinations of above stated functions & handle our arrays, objects and much more quite easily." }, { "code": null, "e": 28208, "s": 28158, "text": "For much more, you can go through docs of Lodash." }, { "code": null, "e": 28235, "s": 28208, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 28253, "s": 28235, "text": "JavaScript-Lodash" }, { "code": null, "e": 28264, "s": 28253, "text": "JavaScript" }, { "code": null, "e": 28362, "s": 28264, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28402, "s": 28362, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28447, "s": 28402, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28508, "s": 28447, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28580, "s": 28508, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28621, "s": 28580, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28670, "s": 28621, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 28706, "s": 28670, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 28728, "s": 28706, "text": "JavaScript | Promises" }, { "code": null, "e": 28774, "s": 28728, "text": "Set the value of an input field in JavaScript" } ]
Python open() Function
13 Sep, 2021 The python open() function is used to open() internally stored files. It returns the contents of the file as python objects. Syntax: open(file_name, mode) Parameters: file_name: This parameter as the name suggests, is the name of the file that we want to open. mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode: “r”: This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists. “w”: This string is used for writing on/over the file. If the file with the supplied name doesn’t exist, it creates one for you. “a”: This string is used to add(append) content to an existing file. If no such file exists, it creates one for you. “x”: This string is used to create a specific file. “b”: This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files. “t”: This string is used to handle files in text mode. By default, the open() function uses the text mode. The following code can be used to create a file. Here we will be creating a text file named”geeksforgeeks.txt”. Python3 created_file = open("geeksforgeeks.txt","x") # Check the fileprint(open("geeksforgeeks.txt","r").read() == False) Output: True Here we will write the following string to the geeksforgeeks.txt file that we just created and read the same file again. Geeksforgeeks is best for DSA The below code can be used for the same: Python3 my_file = open("geeksforgeeks.txt", "w")my_file.write("Geeksforgeeks is best for DSA")my_file.close() #let's read the contents of the file nowmy_file = open("geeksforgeeks.txt","r")print(my_file.read()) Output: Geeksforgeeks is best for DSA Here we will append the following text to the geeksforgeeks.txt file and again read the same: Python3 my_file = open("geeksforgeeks.txt","a")my_file.write("..>>Visit geeksforgeeks.org for more!!<<..")my_file.close() # reading the filemy_file = open("geeksforgeeks.txt","r")print(my_file.read()) Output: Geeksforgeeks is best for DSA..>>Visit geeksforgeeks.org for more!!<<.. Note: The difference between “w” and “r” is that one overrides over the existing content whereas the latter adds content to the existing file keeping the content intact. Picked Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Sep, 2021" }, { "code": null, "e": 178, "s": 53, "text": "The python open() function is used to open() internally stored files. It returns the contents of the file as python objects." }, { "code": null, "e": 209, "s": 178, "text": "Syntax: open(file_name, mode) " }, { "code": null, "e": 221, "s": 209, "text": "Parameters:" }, { "code": null, "e": 315, "s": 221, "text": "file_name: This parameter as the name suggests, is the name of the file that we want to open." }, { "code": null, "e": 479, "s": 315, "text": "mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:" }, { "code": null, "e": 625, "s": 479, "text": "“r”: This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists." }, { "code": null, "e": 754, "s": 625, "text": "“w”: This string is used for writing on/over the file. If the file with the supplied name doesn’t exist, it creates one for you." }, { "code": null, "e": 871, "s": 754, "text": "“a”: This string is used to add(append) content to an existing file. If no such file exists, it creates one for you." }, { "code": null, "e": 923, "s": 871, "text": "“x”: This string is used to create a specific file." }, { "code": null, "e": 1049, "s": 923, "text": "“b”: This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files." }, { "code": null, "e": 1156, "s": 1049, "text": "“t”: This string is used to handle files in text mode. By default, the open() function uses the text mode." }, { "code": null, "e": 1268, "s": 1156, "text": "The following code can be used to create a file. Here we will be creating a text file named”geeksforgeeks.txt”." }, { "code": null, "e": 1276, "s": 1268, "text": "Python3" }, { "code": "created_file = open(\"geeksforgeeks.txt\",\"x\") # Check the fileprint(open(\"geeksforgeeks.txt\",\"r\").read() == False)", "e": 1391, "s": 1276, "text": null }, { "code": null, "e": 1399, "s": 1391, "text": "Output:" }, { "code": null, "e": 1404, "s": 1399, "text": "True" }, { "code": null, "e": 1525, "s": 1404, "text": "Here we will write the following string to the geeksforgeeks.txt file that we just created and read the same file again." }, { "code": null, "e": 1555, "s": 1525, "text": "Geeksforgeeks is best for DSA" }, { "code": null, "e": 1596, "s": 1555, "text": "The below code can be used for the same:" }, { "code": null, "e": 1604, "s": 1596, "text": "Python3" }, { "code": "my_file = open(\"geeksforgeeks.txt\", \"w\")my_file.write(\"Geeksforgeeks is best for DSA\")my_file.close() #let's read the contents of the file nowmy_file = open(\"geeksforgeeks.txt\",\"r\")print(my_file.read())", "e": 1808, "s": 1604, "text": null }, { "code": null, "e": 1816, "s": 1808, "text": "Output:" }, { "code": null, "e": 1846, "s": 1816, "text": "Geeksforgeeks is best for DSA" }, { "code": null, "e": 1940, "s": 1846, "text": "Here we will append the following text to the geeksforgeeks.txt file and again read the same:" }, { "code": null, "e": 1948, "s": 1940, "text": "Python3" }, { "code": "my_file = open(\"geeksforgeeks.txt\",\"a\")my_file.write(\"..>>Visit geeksforgeeks.org for more!!<<..\")my_file.close() # reading the filemy_file = open(\"geeksforgeeks.txt\",\"r\")print(my_file.read())", "e": 2142, "s": 1948, "text": null }, { "code": null, "e": 2150, "s": 2142, "text": "Output:" }, { "code": null, "e": 2222, "s": 2150, "text": "Geeksforgeeks is best for DSA..>>Visit geeksforgeeks.org for more!!<<.." }, { "code": null, "e": 2392, "s": 2222, "text": "Note: The difference between “w” and “r” is that one overrides over the existing content whereas the latter adds content to the existing file keeping the content intact." }, { "code": null, "e": 2399, "s": 2392, "text": "Picked" }, { "code": null, "e": 2425, "s": 2399, "text": "Python-Built-in-functions" }, { "code": null, "e": 2432, "s": 2425, "text": "Python" } ]
std::mismatch() with examples in C++
06 Jul, 2017 C++ STL has lots of useful functions that helps us to achieve various programming tasks. One such function is “mismatch()” . This function, defined in “algorithm” header file, helps to compare 2 containers for mismatches. This function has 2 versions. Both are discussed in this article. mismatch( start_iter1, end_iter1, start_iter2 ) This version of mismatch only test for inequality.Here, there are 3 arguments,start_iter1: Beginning iterator to 1st containerend_iter1: Last iterator to 1st containerstart_iter2: Starting iterator to the 2nd iterator from where comparison is desired to begin.This function returns the 1st mismatch pair pointer, first element pointing to position of first mismatch element of 1st container, second element pointing to position of first mismatch element of 2nd container. If no mismatch is found, 1st element points to position after last element of 1st container and 2nd points to corresponding position in 2nd container.// C++ code to demonstrate the working of // mismatch( start_iter1, end_iter1, start_iter2 ) #include<iostream>#include<algorithm> #include<vector>using namespace std; int main(){ // initializing vectors vector<int> v1 = { 1, 10, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 1, 10, 15, 20 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin()); // printing the mismatch pair // 1st mismatch at 15 and 25 cout << "The 1st mismatch element of 1st container : "; cout << *mispair.first << endl; cout << "The 1st mismatch element of 2nd container : "; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin()); // printing the mismatch pair // no mismatch // points to position after last 0 and corresponding 24 cout << "The returned value from 1st container is : "; cout << *mispair.first << endl; cout << "The returned value from 2nd container is : "; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15 The 1st mismatch element of 2nd container : 25 The returned value from 1st container is : 0 The returned value from 2nd container is : 24 mismatch( start_iter1, end_iter1, start_iter2, comparator) : This function is almost similar to the working as the above mentioned version, but it offers to find not only equality mismatches, but also other user-defined and desired mismatches via user- defined comparator function that is sent as 4th argument and returns a boolean true or false.// C++ code to demonstrate the working of// mismatch( start_iter1, end_iter1, start_iter2, comparator ) #include<iostream>#include<algorithm> #include<vector>using namespace std; // comparator function// returns true when element from // 1st element is greater than 2ndbool compare(int a, int b){ return (a>b);} int main(){ // initializing vectors vector<int> v1 = { 23, 13, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 12, 100, 152, 204 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin(), compare); // printing the mismatch pair // 1st mismatch at 15 and 25 // 15 is 1st element less than 2nd at same position cout << "The 1st mismatch element of 1st container : "; cout << *mispair.first << endl; cout << "The 1st mismatch element of 2nd container : "; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin(), compare); // printing the mismatch pair // no mismatch // all elements in 1st container are greater than 2nd // points to position after last 0 and corresponding 24 cout << "The returned value from 1st container is : "; cout << *mispair.first << endl; cout << "The returned value from 2nd container is : "; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15 The 1st mismatch element of 2nd container : 25 The returned value from 1st container is : 0 The returned value from 2nd container is : 24 mismatch( start_iter1, end_iter1, start_iter2 ) This version of mismatch only test for inequality.Here, there are 3 arguments,start_iter1: Beginning iterator to 1st containerend_iter1: Last iterator to 1st containerstart_iter2: Starting iterator to the 2nd iterator from where comparison is desired to begin.This function returns the 1st mismatch pair pointer, first element pointing to position of first mismatch element of 1st container, second element pointing to position of first mismatch element of 2nd container. If no mismatch is found, 1st element points to position after last element of 1st container and 2nd points to corresponding position in 2nd container.// C++ code to demonstrate the working of // mismatch( start_iter1, end_iter1, start_iter2 ) #include<iostream>#include<algorithm> #include<vector>using namespace std; int main(){ // initializing vectors vector<int> v1 = { 1, 10, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 1, 10, 15, 20 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin()); // printing the mismatch pair // 1st mismatch at 15 and 25 cout << "The 1st mismatch element of 1st container : "; cout << *mispair.first << endl; cout << "The 1st mismatch element of 2nd container : "; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin()); // printing the mismatch pair // no mismatch // points to position after last 0 and corresponding 24 cout << "The returned value from 1st container is : "; cout << *mispair.first << endl; cout << "The returned value from 2nd container is : "; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15 The 1st mismatch element of 2nd container : 25 The returned value from 1st container is : 0 The returned value from 2nd container is : 24 This function returns the 1st mismatch pair pointer, first element pointing to position of first mismatch element of 1st container, second element pointing to position of first mismatch element of 2nd container. If no mismatch is found, 1st element points to position after last element of 1st container and 2nd points to corresponding position in 2nd container. // C++ code to demonstrate the working of // mismatch( start_iter1, end_iter1, start_iter2 ) #include<iostream>#include<algorithm> #include<vector>using namespace std; int main(){ // initializing vectors vector<int> v1 = { 1, 10, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 1, 10, 15, 20 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin()); // printing the mismatch pair // 1st mismatch at 15 and 25 cout << "The 1st mismatch element of 1st container : "; cout << *mispair.first << endl; cout << "The 1st mismatch element of 2nd container : "; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin()); // printing the mismatch pair // no mismatch // points to position after last 0 and corresponding 24 cout << "The returned value from 1st container is : "; cout << *mispair.first << endl; cout << "The returned value from 2nd container is : "; cout << *mispair.second << endl; } Output: The 1st mismatch element of 1st container : 15 The 1st mismatch element of 2nd container : 25 The returned value from 1st container is : 0 The returned value from 2nd container is : 24 mismatch( start_iter1, end_iter1, start_iter2, comparator) : This function is almost similar to the working as the above mentioned version, but it offers to find not only equality mismatches, but also other user-defined and desired mismatches via user- defined comparator function that is sent as 4th argument and returns a boolean true or false.// C++ code to demonstrate the working of// mismatch( start_iter1, end_iter1, start_iter2, comparator ) #include<iostream>#include<algorithm> #include<vector>using namespace std; // comparator function// returns true when element from // 1st element is greater than 2ndbool compare(int a, int b){ return (a>b);} int main(){ // initializing vectors vector<int> v1 = { 23, 13, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 12, 100, 152, 204 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin(), compare); // printing the mismatch pair // 1st mismatch at 15 and 25 // 15 is 1st element less than 2nd at same position cout << "The 1st mismatch element of 1st container : "; cout << *mispair.first << endl; cout << "The 1st mismatch element of 2nd container : "; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin(), compare); // printing the mismatch pair // no mismatch // all elements in 1st container are greater than 2nd // points to position after last 0 and corresponding 24 cout << "The returned value from 1st container is : "; cout << *mispair.first << endl; cout << "The returned value from 2nd container is : "; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15 The 1st mismatch element of 2nd container : 25 The returned value from 1st container is : 0 The returned value from 2nd container is : 24 // C++ code to demonstrate the working of// mismatch( start_iter1, end_iter1, start_iter2, comparator ) #include<iostream>#include<algorithm> #include<vector>using namespace std; // comparator function// returns true when element from // 1st element is greater than 2ndbool compare(int a, int b){ return (a>b);} int main(){ // initializing vectors vector<int> v1 = { 23, 13, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 12, 100, 152, 204 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin(), compare); // printing the mismatch pair // 1st mismatch at 15 and 25 // 15 is 1st element less than 2nd at same position cout << "The 1st mismatch element of 1st container : "; cout << *mispair.first << endl; cout << "The 1st mismatch element of 2nd container : "; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin(), compare); // printing the mismatch pair // no mismatch // all elements in 1st container are greater than 2nd // points to position after last 0 and corresponding 24 cout << "The returned value from 1st container is : "; cout << *mispair.first << endl; cout << "The returned value from 2nd container is : "; cout << *mispair.second << endl; } Output: The 1st mismatch element of 1st container : 15 The 1st mismatch element of 2nd container : 25 The returned value from 1st container is : 0 The returned value from 2nd container is : 24 This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2017" }, { "code": null, "e": 340, "s": 52, "text": "C++ STL has lots of useful functions that helps us to achieve various programming tasks. One such function is “mismatch()” . This function, defined in “algorithm” header file, helps to compare 2 containers for mismatches. This function has 2 versions. Both are discussed in this article." }, { "code": null, "e": 4611, "s": 340, "text": "mismatch( start_iter1, end_iter1, start_iter2 ) This version of mismatch only test for inequality.Here, there are 3 arguments,start_iter1: Beginning iterator to 1st containerend_iter1: Last iterator to 1st containerstart_iter2: Starting iterator to the 2nd iterator from where comparison is desired to begin.This function returns the 1st mismatch pair pointer, first element pointing to position of first mismatch element of 1st container, second element pointing to position of first mismatch element of 2nd container. If no mismatch is found, 1st element points to position after last element of 1st container and 2nd points to corresponding position in 2nd container.// C++ code to demonstrate the working of // mismatch( start_iter1, end_iter1, start_iter2 ) #include<iostream>#include<algorithm> #include<vector>using namespace std; int main(){ // initializing vectors vector<int> v1 = { 1, 10, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 1, 10, 15, 20 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin()); // printing the mismatch pair // 1st mismatch at 15 and 25 cout << \"The 1st mismatch element of 1st container : \"; cout << *mispair.first << endl; cout << \"The 1st mismatch element of 2nd container : \"; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin()); // printing the mismatch pair // no mismatch // points to position after last 0 and corresponding 24 cout << \"The returned value from 1st container is : \"; cout << *mispair.first << endl; cout << \"The returned value from 2nd container is : \"; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15\nThe 1st mismatch element of 2nd container : 25\nThe returned value from 1st container is : 0\nThe returned value from 2nd container is : 24\nmismatch( start_iter1, end_iter1, start_iter2, comparator) : This function is almost similar to the working as the above mentioned version, but it offers to find not only equality mismatches, but also other user-defined and desired mismatches via user- defined comparator function that is sent as 4th argument and returns a boolean true or false.// C++ code to demonstrate the working of// mismatch( start_iter1, end_iter1, start_iter2, comparator ) #include<iostream>#include<algorithm> #include<vector>using namespace std; // comparator function// returns true when element from // 1st element is greater than 2ndbool compare(int a, int b){ return (a>b);} int main(){ // initializing vectors vector<int> v1 = { 23, 13, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 12, 100, 152, 204 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin(), compare); // printing the mismatch pair // 1st mismatch at 15 and 25 // 15 is 1st element less than 2nd at same position cout << \"The 1st mismatch element of 1st container : \"; cout << *mispair.first << endl; cout << \"The 1st mismatch element of 2nd container : \"; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin(), compare); // printing the mismatch pair // no mismatch // all elements in 1st container are greater than 2nd // points to position after last 0 and corresponding 24 cout << \"The returned value from 1st container is : \"; cout << *mispair.first << endl; cout << \"The returned value from 2nd container is : \"; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15\nThe 1st mismatch element of 2nd container : 25\nThe returned value from 1st container is : 0\nThe returned value from 2nd container is : 24\n" }, { "code": null, "e": 6765, "s": 4611, "text": "mismatch( start_iter1, end_iter1, start_iter2 ) This version of mismatch only test for inequality.Here, there are 3 arguments,start_iter1: Beginning iterator to 1st containerend_iter1: Last iterator to 1st containerstart_iter2: Starting iterator to the 2nd iterator from where comparison is desired to begin.This function returns the 1st mismatch pair pointer, first element pointing to position of first mismatch element of 1st container, second element pointing to position of first mismatch element of 2nd container. If no mismatch is found, 1st element points to position after last element of 1st container and 2nd points to corresponding position in 2nd container.// C++ code to demonstrate the working of // mismatch( start_iter1, end_iter1, start_iter2 ) #include<iostream>#include<algorithm> #include<vector>using namespace std; int main(){ // initializing vectors vector<int> v1 = { 1, 10, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 1, 10, 15, 20 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin()); // printing the mismatch pair // 1st mismatch at 15 and 25 cout << \"The 1st mismatch element of 1st container : \"; cout << *mispair.first << endl; cout << \"The 1st mismatch element of 2nd container : \"; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin()); // printing the mismatch pair // no mismatch // points to position after last 0 and corresponding 24 cout << \"The returned value from 1st container is : \"; cout << *mispair.first << endl; cout << \"The returned value from 2nd container is : \"; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15\nThe 1st mismatch element of 2nd container : 25\nThe returned value from 1st container is : 0\nThe returned value from 2nd container is : 24\n" }, { "code": null, "e": 7128, "s": 6765, "text": "This function returns the 1st mismatch pair pointer, first element pointing to position of first mismatch element of 1st container, second element pointing to position of first mismatch element of 2nd container. If no mismatch is found, 1st element points to position after last element of 1st container and 2nd points to corresponding position in 2nd container." }, { "code": "// C++ code to demonstrate the working of // mismatch( start_iter1, end_iter1, start_iter2 ) #include<iostream>#include<algorithm> #include<vector>using namespace std; int main(){ // initializing vectors vector<int> v1 = { 1, 10, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 1, 10, 15, 20 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin()); // printing the mismatch pair // 1st mismatch at 15 and 25 cout << \"The 1st mismatch element of 1st container : \"; cout << *mispair.first << endl; cout << \"The 1st mismatch element of 2nd container : \"; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin()); // printing the mismatch pair // no mismatch // points to position after last 0 and corresponding 24 cout << \"The returned value from 1st container is : \"; cout << *mispair.first << endl; cout << \"The returned value from 2nd container is : \"; cout << *mispair.second << endl; }", "e": 8418, "s": 7128, "text": null }, { "code": null, "e": 8426, "s": 8418, "text": "Output:" }, { "code": null, "e": 8614, "s": 8426, "text": "The 1st mismatch element of 1st container : 15\nThe 1st mismatch element of 2nd container : 25\nThe returned value from 1st container is : 0\nThe returned value from 2nd container is : 24\n" }, { "code": null, "e": 10732, "s": 8614, "text": "mismatch( start_iter1, end_iter1, start_iter2, comparator) : This function is almost similar to the working as the above mentioned version, but it offers to find not only equality mismatches, but also other user-defined and desired mismatches via user- defined comparator function that is sent as 4th argument and returns a boolean true or false.// C++ code to demonstrate the working of// mismatch( start_iter1, end_iter1, start_iter2, comparator ) #include<iostream>#include<algorithm> #include<vector>using namespace std; // comparator function// returns true when element from // 1st element is greater than 2ndbool compare(int a, int b){ return (a>b);} int main(){ // initializing vectors vector<int> v1 = { 23, 13, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 12, 100, 152, 204 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin(), compare); // printing the mismatch pair // 1st mismatch at 15 and 25 // 15 is 1st element less than 2nd at same position cout << \"The 1st mismatch element of 1st container : \"; cout << *mispair.first << endl; cout << \"The 1st mismatch element of 2nd container : \"; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin(), compare); // printing the mismatch pair // no mismatch // all elements in 1st container are greater than 2nd // points to position after last 0 and corresponding 24 cout << \"The returned value from 1st container is : \"; cout << *mispair.first << endl; cout << \"The returned value from 2nd container is : \"; cout << *mispair.second << endl; }Output:The 1st mismatch element of 1st container : 15\nThe 1st mismatch element of 2nd container : 25\nThe returned value from 1st container is : 0\nThe returned value from 2nd container is : 24\n" }, { "code": "// C++ code to demonstrate the working of// mismatch( start_iter1, end_iter1, start_iter2, comparator ) #include<iostream>#include<algorithm> #include<vector>using namespace std; // comparator function// returns true when element from // 1st element is greater than 2ndbool compare(int a, int b){ return (a>b);} int main(){ // initializing vectors vector<int> v1 = { 23, 13, 15, 20 }; vector<int> v2 = { 1, 10, 25, 30, 45 }; vector<int> v3 = { 12, 100, 152, 204 }; vector<int> v4 = { 1, 10, 15, 20, 24 }; // declaring pointer pair pair< vector<int>::iterator, vector<int>::iterator > mispair; // using mismatch() to search for 1st mismatch mispair = mismatch(v1.begin(), v1.end(), v2.begin(), compare); // printing the mismatch pair // 1st mismatch at 15 and 25 // 15 is 1st element less than 2nd at same position cout << \"The 1st mismatch element of 1st container : \"; cout << *mispair.first << endl; cout << \"The 1st mismatch element of 2nd container : \"; cout << *mispair.second << endl; // using mismatch() to search for 1st mismatch mispair = mismatch(v3.begin(), v3.end(), v4.begin(), compare); // printing the mismatch pair // no mismatch // all elements in 1st container are greater than 2nd // points to position after last 0 and corresponding 24 cout << \"The returned value from 1st container is : \"; cout << *mispair.first << endl; cout << \"The returned value from 2nd container is : \"; cout << *mispair.second << endl; }", "e": 12310, "s": 10732, "text": null }, { "code": null, "e": 12318, "s": 12310, "text": "Output:" }, { "code": null, "e": 12506, "s": 12318, "text": "The 1st mismatch element of 1st container : 15\nThe 1st mismatch element of 2nd container : 25\nThe returned value from 1st container is : 0\nThe returned value from 2nd container is : 24\n" }, { "code": null, "e": 12807, "s": 12506, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 12932, "s": 12807, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 12954, "s": 12932, "text": "cpp-algorithm-library" }, { "code": null, "e": 12958, "s": 12954, "text": "STL" }, { "code": null, "e": 12962, "s": 12958, "text": "C++" }, { "code": null, "e": 12966, "s": 12962, "text": "STL" }, { "code": null, "e": 12970, "s": 12966, "text": "CPP" } ]
Fractional Knapsack | Practice | GeeksforGeeks
Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note: Unlike 0/1 knapsack, you are allowed to break the item. Example 1: Input: N = 3, W = 50 values[] = {60,100,120} weight[] = {10,20,30} Output: 240.00 Explanation:Total maximum value of item we can have is 240.00 from the given capacity of sack. Example 2: Input: N = 2, W = 50 values[] = {60,100} weight[] = {10,20} Output: 160.00 Explanation: Total maximum value of item we can have is 160.00 from the given capacity of sack. Your Task : Complete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack. Note: The details of structure/class is defined in the comments above the given function. Expected Time Complexity : O(NlogN) Expected Auxilliary Space: O(1) Constraints: 1 <= N <= 105 1 <= W <= 105 0 hrithikrsgupta2 days ago O(1) space complexity . sort the given array according to value/weight ration using comparator function. class Solution{ public: static bool comp(Item a, Item b){ return ((double)a.value/a.weight) > ((double)b.value/b.weight); } //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { sort(arr,arr+n,comp); double mx = 0; for(int i=0;i<n && W>0;i++){ double perunit = (double)arr[i].value/arr[i].weight; if(W>=arr[i].weight){ W -= arr[i].weight; mx += (perunit*arr[i].weight); }else{ mx += (perunit*W); W=0; } } return mx; } }; 0 prateekp17293 days ago class Solution { public: //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int w, Item arr[], int n) { vector<pair<double, int>> ratio(n); for(int i=0;i<n;i++){ ratio[i].first = (double)(arr[i].value)/(double)arr[i].weight; ratio[i].second = i; } sort(ratio.begin(), ratio.end()); double ans = 0; for(int i=n-1;i>=0;i--){ if(!w) break; double weight = arr[ratio[i].second].weight; double value = arr[ratio[i].second].value; if(weight<=w){ ans+=value; w-=weight; } else { ans+=(w/weight)*value; break; } } return ans; } }; 0 aloktripathi2563 days ago //CPP solution double fractionalKnapsack(int W, Item arr[], int n) { // Your code here vector <pair<double ,int>> ratio(n); for (int i=0;i<n;i++){ ratio[i].first=arr[i].value/(double)arr[i].weight; ratio[i].second=i; } sort(ratio.begin(), ratio.end()); double ans=0; for (int i=n-1;i>=0;i--){ if (W==0) break; else { if (arr[ratio[i].second].weight <= W) { ans+=arr[ratio[i].second].value; W=W-arr[ratio[i].second].weight; } else { ans+=(arr[ratio[i].second].value*W/(double)arr[ratio[i].second].weight); W=0; } } } return ans; } 0 mishraswastik02114 days ago class Frac{ int p; int w; double p_w; public Frac(int p, int w) { super(); this.p = p; this.w = w; p_w = (double)p/(double)w; } } class Solution { //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int knapsak, Item it[], int n) { // Your code here ArrayList<Frac> a = new ArrayList<Frac>(); for(int i=0;i<n;i++) { a.add(new Frac(it[i].value, it[i].weight)); } Collections.sort(a,new Comparator<Frac>() { @Override public int compare(Frac o1,Frac o2) { if(o1.p_w == o2.p_w) { return 0; }else if(o1.p_w>o2.p_w) { return -1; }else { return 1; } } }); double count = 0; for(int i=0;i<n;i++) { if(knapsak == 0) { break; } if(knapsak >= a.get(i).w) { knapsak -= a.get(i).w; count += a.get(i).p; }else { double val = (double) knapsak/a.get(i).w; count += (double)(val*a.get(i).p); knapsak = 0; } } return count; } } 0 harshbhan261 week ago bool comparison(Item a,Item b){ return(((double)a.value/(double)a.weight)>((double)b.value/(double)b.weight)); } class Solution { public: double fractionalKnapsack(int W, Item arr[], int n) { sort(arr,arr+n,comparison); double profit=0; for(int i=0;i<n;i++){ if(W-arr[i].weight>=0){ W= W-arr[i].weight; profit += arr[i].value; } else{ profit += W*((double)arr[i].value/(double)arr[i].weight); W=0; break; } } return profit; } }; 0 harshbhan26 This comment was deleted. 0 2002amit1 week ago class Solution { public: //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n){ pair<double,int> bag[n]; for(int i=0;i<n;i++){ bag[i] = {(double)arr[i].value/arr[i].weight,arr[i].weight}; } sort(bag,bag+n); reverse(bag,bag+n); double sum = 0; for(int i=0;i<n;i++){ if(W <= 0 && i == n){ break; } else if(W > bag[i].second){ sum += (double)(bag[i].first*bag[i].second); W -= bag[i].second; }else if( W == bag[i].second){ W -= bag[i].second; sum += (double)(bag[i].first*bag[i].second); break; }else if(W < bag[i].second){ sum += (double)(bag[i].first*W); break; } } return sum; } }; 0 mehtameet12341 week ago // SIMPLE JAVA // sort item according to the max ratio of value and weight. // keep adding it to knapsack until the weight becomes 0 (simple cross multiplication to find the last value of profit for fractional weight) and keep adding to the maxProfit class Solution { double fractionalKnapsack(int W, Item arr[], int n) { Arrays.sort(arr, new Comparator<Item>() { public int compare (Item a, Item b) { double r1 = (double)a.value / (double)a.weight; double r2 = (double)b.value / (double)b.weight; if (r1 < r2) return 1; else return -1; } }); double maxProfit = 0; int currWeight = W; for (int i = 0; i < n; i++) { if (arr[i].weight <= currWeight) { maxProfit += arr[i].value; currWeight -= arr[i].weight; } else { maxProfit += (double)currWeight * ((double)arr[i].value / (double)arr[i].weight); break; } } return maxProfit; } } 0 chandan malpotra1 week ago double fractionalKnapsack(int W, Item arr[], int n) { vector<pair<double,int>> ratio; double price=0; for(int i=0; i<n; i++) { double d = arr[i].value/arr[i].weight; int a = arr[i].weight; ratio.push_back(make_pair(d,a)); } sort(ratio.begin(),ratio.end()); for(int i=n-1; i>=0; i--) { if(ratio[i].second<=W) { price= price + (ratio[i].first)*(ratio[i].second); W = W - min(ratio[i].second,W); } else { price = price + W*(ratio[i].first); W = W - min(ratio[i].second,W); break; } } return price;what's wrong with this code. +1 upendrasc20012 weeks ago double fractionalKnapsack(int W, Item arr[], int n) { // Your code here sort(arr,arr+n,[](Item a,Item b){return (a.value*b.weight)>(b.value*a.weight);}); double ans=0.0; for(int i=0;i<n;i++){ if(arr[i].weight<=W){ ans+=arr[i].value; W-=arr[i].weight; } else if(arr[i].weight>W){ ans+=(double)((arr[i].value*W)/(double)arr[i].weight); break; } } return ans; } 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 441, "s": 238, "text": "Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.\nNote: Unlike 0/1 knapsack, you are allowed to break the item. " }, { "code": null, "e": 454, "s": 443, "text": "Example 1:" }, { "code": null, "e": 633, "s": 454, "text": "Input:\nN = 3, W = 50\nvalues[] = {60,100,120}\nweight[] = {10,20,30}\nOutput:\n240.00\nExplanation:Total maximum value of item\nwe can have is 240.00 from the given\ncapacity of sack. \n" }, { "code": null, "e": 644, "s": 633, "text": "Example 2:" }, { "code": null, "e": 815, "s": 644, "text": "Input:\nN = 2, W = 50\nvalues[] = {60,100}\nweight[] = {10,20}\nOutput:\n160.00\nExplanation:\nTotal maximum value of item\nwe can have is 160.00 from the given\ncapacity of sack." }, { "code": null, "e": 1102, "s": 817, "text": "Your Task :\nComplete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack.\nNote: The details of structure/class is defined in the comments above the given function." }, { "code": null, "e": 1171, "s": 1102, "text": "\nExpected Time Complexity : O(NlogN)\nExpected Auxilliary Space: O(1)" }, { "code": null, "e": 1213, "s": 1171, "text": "\nConstraints:\n1 <= N <= 105\n1 <= W <= 105" }, { "code": null, "e": 1215, "s": 1213, "text": "0" }, { "code": null, "e": 1240, "s": 1215, "text": "hrithikrsgupta2 days ago" }, { "code": null, "e": 1345, "s": 1240, "text": "O(1) space complexity . sort the given array according to value/weight ration using comparator function." }, { "code": null, "e": 2056, "s": 1347, "text": "class Solution{ public: static bool comp(Item a, Item b){ return ((double)a.value/a.weight) > ((double)b.value/b.weight); } //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int W, Item arr[], int n) { sort(arr,arr+n,comp); double mx = 0; for(int i=0;i<n && W>0;i++){ double perunit = (double)arr[i].value/arr[i].weight; if(W>=arr[i].weight){ W -= arr[i].weight; mx += (perunit*arr[i].weight); }else{ mx += (perunit*W); W=0; } } return mx; } };" }, { "code": null, "e": 2058, "s": 2056, "text": "0" }, { "code": null, "e": 2081, "s": 2058, "text": "prateekp17293 days ago" }, { "code": null, "e": 2096, "s": 2081, "text": "class Solution" }, { "code": null, "e": 2851, "s": 2096, "text": "{ public: //Function to get the maximum total value in the knapsack. double fractionalKnapsack(int w, Item arr[], int n) { vector<pair<double, int>> ratio(n); for(int i=0;i<n;i++){ ratio[i].first = (double)(arr[i].value)/(double)arr[i].weight; ratio[i].second = i; } sort(ratio.begin(), ratio.end()); double ans = 0; for(int i=n-1;i>=0;i--){ if(!w) break; double weight = arr[ratio[i].second].weight; double value = arr[ratio[i].second].value; if(weight<=w){ ans+=value; w-=weight; } else { ans+=(w/weight)*value; break; } } return ans; } };" }, { "code": null, "e": 2853, "s": 2851, "text": "0" }, { "code": null, "e": 2879, "s": 2853, "text": "aloktripathi2563 days ago" }, { "code": null, "e": 2894, "s": 2879, "text": "//CPP solution" }, { "code": null, "e": 3646, "s": 2896, "text": "double fractionalKnapsack(int W, Item arr[], int n) { // Your code here vector <pair<double ,int>> ratio(n); for (int i=0;i<n;i++){ ratio[i].first=arr[i].value/(double)arr[i].weight; ratio[i].second=i; } sort(ratio.begin(), ratio.end()); double ans=0; for (int i=n-1;i>=0;i--){ if (W==0) break; else { if (arr[ratio[i].second].weight <= W) { ans+=arr[ratio[i].second].value; W=W-arr[ratio[i].second].weight; } else { ans+=(arr[ratio[i].second].value*W/(double)arr[ratio[i].second].weight); W=0; } } } return ans; }" }, { "code": null, "e": 3648, "s": 3646, "text": "0" }, { "code": null, "e": 3676, "s": 3648, "text": "mishraswastik02114 days ago" }, { "code": null, "e": 4707, "s": 3676, "text": "\nclass Frac{\n\tint p;\n\tint w;\n\tdouble p_w;\n\tpublic Frac(int p, int w) {\t\tsuper();\n\t\tthis.p = p;\n\t\tthis.w = w;\n\t\tp_w = (double)p/(double)w;\n\t}\n}\n\n\n\nclass Solution\n{\n //Function to get the maximum total value in the knapsack.\n double fractionalKnapsack(int knapsak, Item it[], int n) \n {\n // Your code here\n \n ArrayList<Frac> a = new ArrayList<Frac>();\n\t\tfor(int i=0;i<n;i++) {\n\t\t\ta.add(new Frac(it[i].value, it[i].weight));\n\t\t}\n\t\t\n\t\t\n\t\tCollections.sort(a,new Comparator<Frac>() {\n\t\t\t@Override\n\t\t\tpublic int compare(Frac o1,Frac o2) {\n\t\t\t\tif(o1.p_w == o2.p_w) {\n\t\t\t\t\treturn 0;\t\t\t\t\t\n\t\t\t\t}else if(o1.p_w>o2.p_w) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}else {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n \n double count = 0;\n\t\tfor(int i=0;i<n;i++) {\n\t\t\tif(knapsak == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(knapsak >= a.get(i).w) {\n\t\t\t\tknapsak -= a.get(i).w;\n\t\t\t\tcount += a.get(i).p;\n\t\t\t}else {\n\t\t\t\tdouble val = (double) knapsak/a.get(i).w;\n\t\t\t\tcount += (double)(val*a.get(i).p);\n\t\t\t\tknapsak = 0;\n\t\t\t}\n\t\t}\n\t\treturn count;\n \n }\n}" }, { "code": null, "e": 4709, "s": 4707, "text": "0" }, { "code": null, "e": 4731, "s": 4709, "text": "harshbhan261 week ago" }, { "code": null, "e": 5380, "s": 4731, "text": "bool comparison(Item a,Item b){\n return(((double)a.value/(double)a.weight)>((double)b.value/(double)b.weight));\n }\n\nclass Solution\n{\n public:\n \n double fractionalKnapsack(int W, Item arr[], int n)\n {\n sort(arr,arr+n,comparison);\n double profit=0;\n for(int i=0;i<n;i++){\n if(W-arr[i].weight>=0){\n W= W-arr[i].weight;\n profit += arr[i].value;\n }\n else{\n profit += W*((double)arr[i].value/(double)arr[i].weight);\n W=0;\n break;\n }\n }\n \n return profit;\n }\n \n};" }, { "code": null, "e": 5382, "s": 5380, "text": "0" }, { "code": null, "e": 5394, "s": 5382, "text": "harshbhan26" }, { "code": null, "e": 5420, "s": 5394, "text": "This comment was deleted." }, { "code": null, "e": 5422, "s": 5420, "text": "0" }, { "code": null, "e": 5441, "s": 5422, "text": "2002amit1 week ago" }, { "code": null, "e": 6389, "s": 5441, "text": "class Solution\n{\n public:\n //Function to get the maximum total value in the knapsack.\n double fractionalKnapsack(int W, Item arr[], int n){\n pair<double,int> bag[n];\n for(int i=0;i<n;i++){\n bag[i] = {(double)arr[i].value/arr[i].weight,arr[i].weight};\n }\n sort(bag,bag+n);\n reverse(bag,bag+n);\n double sum = 0;\n for(int i=0;i<n;i++){\n if(W <= 0 && i == n){\n break;\n }\n else if(W > bag[i].second){\n sum += (double)(bag[i].first*bag[i].second);\n W -= bag[i].second;\n }else if( W == bag[i].second){\n W -= bag[i].second;\n sum += (double)(bag[i].first*bag[i].second);\n break;\n }else if(W < bag[i].second){\n sum += (double)(bag[i].first*W);\n break;\n }\n }\n return sum;\n }\n \n};" }, { "code": null, "e": 6391, "s": 6389, "text": "0" }, { "code": null, "e": 6415, "s": 6391, "text": "mehtameet12341 week ago" }, { "code": null, "e": 7603, "s": 6415, "text": "// SIMPLE JAVA\n\n// sort item according to the max ratio of value and weight.\n// keep adding it to knapsack until the weight becomes 0 (simple cross multiplication to find the last value of profit for fractional weight) and keep adding to the maxProfit\n\nclass Solution\n{\n double fractionalKnapsack(int W, Item arr[], int n) \n {\n Arrays.sort(arr, new Comparator<Item>() {\n public int compare (Item a, Item b) {\n double r1 = (double)a.value / (double)a.weight;\n double r2 = (double)b.value / (double)b.weight;\n \n if (r1 < r2) \n return 1;\n else\n return -1;\n } \n });\n \n double maxProfit = 0;\n int currWeight = W;\n \n for (int i = 0; i < n; i++) {\n if (arr[i].weight <= currWeight) {\n maxProfit += arr[i].value;\n currWeight -= arr[i].weight;\n }\n else {\n maxProfit += (double)currWeight * ((double)arr[i].value / (double)arr[i].weight);\n break;\n }\n }\n \n return maxProfit;\n }\n}" }, { "code": null, "e": 7605, "s": 7603, "text": "0" }, { "code": null, "e": 7632, "s": 7605, "text": "chandan malpotra1 week ago" }, { "code": null, "e": 8061, "s": 7632, "text": " double fractionalKnapsack(int W, Item arr[], int n) { vector<pair<double,int>> ratio; double price=0; for(int i=0; i<n; i++) { double d = arr[i].value/arr[i].weight; int a = arr[i].weight; ratio.push_back(make_pair(d,a)); } sort(ratio.begin(),ratio.end()); for(int i=n-1; i>=0; i--) { if(ratio[i].second<=W) {" }, { "code": null, "e": 8213, "s": 8061, "text": " price= price + (ratio[i].first)*(ratio[i].second); W = W - min(ratio[i].second,W); } else {" }, { "code": null, "e": 8399, "s": 8213, "text": " price = price + W*(ratio[i].first); W = W - min(ratio[i].second,W); break; } } return price;what's wrong with this code." }, { "code": null, "e": 8402, "s": 8399, "text": "+1" }, { "code": null, "e": 8427, "s": 8402, "text": "upendrasc20012 weeks ago" }, { "code": null, "e": 8963, "s": 8427, "text": "double fractionalKnapsack(int W, Item arr[], int n)\n {\n // Your code here\n sort(arr,arr+n,[](Item a,Item b){return (a.value*b.weight)>(b.value*a.weight);});\n double ans=0.0;\n for(int i=0;i<n;i++){\n if(arr[i].weight<=W){\n ans+=arr[i].value;\n W-=arr[i].weight;\n }\n else if(arr[i].weight>W){\n ans+=(double)((arr[i].value*W)/(double)arr[i].weight);\n break;\n }\n }\n return ans;\n \n }" }, { "code": null, "e": 9109, "s": 8963, "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": 9145, "s": 9109, "text": " Login to access your submissions. " }, { "code": null, "e": 9155, "s": 9145, "text": "\nProblem\n" }, { "code": null, "e": 9165, "s": 9155, "text": "\nContest\n" }, { "code": null, "e": 9228, "s": 9165, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9413, "s": 9228, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9697, "s": 9413, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 9843, "s": 9697, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 9920, "s": 9843, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 9961, "s": 9920, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 9989, "s": 9961, "text": "Disable browser extensions." }, { "code": null, "e": 10060, "s": 9989, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 10247, "s": 10060, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Delete consecutive same words in a sequence
15 Jul, 2022 Given a sequence of n strings, the task is to check if any two similar words come together then they destroy each other than print the number of words left in the sequence after this pairwise destruction. Examples: Input : ab aa aa bcd ab Output : 3 As aa, aa destroys each other so, ab bcd ab is the new sequence. Input : tom jerry jerry tom Output : 0 As first both jerry will destroy each other. Then sequence will be tom, tom they will also destroy each other. So, the final sequence doesn't contain any word. Method 1: 1- Start traversing the sequence by storing it in vector. a) Check if the current string is equal to next string if yes, erase both from the vector. b) And check the same till last. 2- Return vector size. Implementation: C++ Java Python3 C# Javascript // C++ program to remove consecutive same words#include<bits/stdc++.h>using namespace std; // Function to find the size of manipulated sequenceint removeConsecutiveSame(vector <string > v){ int n = v.size(); // Start traversing the sequence for (int i=0; i<n-1; ) { // Compare the current string with next one // Erase both if equal if (v[i].compare(v[i+1]) == 0) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.erase(v.begin()+i); v.erase(v.begin()+i); // Update i, as to check from previous // element again if (i > 0) i--; // Reduce sequence size n = n-2; } // Increment i, if not equal else i++; } // Return modified size return v.size();} // Driver codeint main(){ vector<string> v = { "tom", "jerry", "jerry", "tom"}; cout << removeConsecutiveSame(v); return 0;} // Java program to remove consecutive same words import java.util.Vector; class Test{ // Method to find the size of manipulated sequence static int removeConsecutiveSame(Vector <String > v) { int n = v.size(); // Start traversing the sequence for (int i=0; i<n-1; ) { // Compare the current string with next one // Erase both if equal if (v.get(i).equals(v.get(i+1))) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.remove(i); v.remove(i); // Update i, as to check from previous // element again if (i > 0) i--; // Reduce sequence size n = n-2; } // Increment i, if not equal else i++; } // Return modified size return v.size(); } // Driver method public static void main(String[] args) { Vector<String> v = new Vector<>(); v.addElement("tom"); v.addElement("jerry"); v.addElement("jerry");v.addElement("tom"); System.out.println(removeConsecutiveSame(v)); }} # Python3 program to remove consecutive# same words # Function to find the size of# manipulated sequencedef removeConsecutiveSame(v): n = len(v) # Start traversing the sequence i = 0 while(i < n - 1): # Compare the current string with # next one Erase both if equal if ((i + 1) < len(v)) and (v[i] == v[i + 1]): # Erase function delete the element and # also shifts other element that's why # i is not updated v = v[:i] v = v[:i] # Update i, as to check from previous # element again if (i > 0): i -= 1 # Reduce sequence size n = n - 2 # Increment i, if not equal else: i += 1 # Return modified size return len(v[:i - 1]) # Driver Codeif __name__ == '__main__': v = ["tom", "jerry", "jerry", "tom"] print(removeConsecutiveSame(v)) # This code is contributed by SHUBHAMSINGH10 // C# program to remove consecutive same wordsusing System;using System.Collections.Generic; class GFG{// Method to find the size of// manipulated sequencepublic static int removeConsecutiveSame(List<string> v){ int n = v.Count; // Start traversing the sequence for (int i = 0; i < n - 1;) { // Compare the current string with // next one Erase both if equal if (v[i].Equals(v[i + 1])) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.RemoveAt(i); v.RemoveAt(i); // Update i, as to check from // previous element again if (i > 0) { i--; } // Reduce sequence size n = n - 2; } // Increment i, if not equal else { i++; } } // Return modified size return v.Count;} // Driver Codepublic static void Main(string[] args){ List<string> v = new List<string>(); v.Add("tom"); v.Add("jerry"); v.Add("jerry"); v.Add("tom"); Console.WriteLine(removeConsecutiveSame(v));}} // This code is contributed by Shrikant13 <script>// Javascript program to remove consecutive same words // Method to find the size of// manipulated sequencefunction removeConsecutiveSame(v){ let n = v.length; // Start traversing the sequence for (let i = 0; i < n - 1;) { // Compare the current string with // next one Erase both if equal if (v[i] == (v[i + 1])) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.splice(i, 1); v.splice(i, 1); // Update i, as to check from // previous element again if (i > 0) { i--; } // Reduce sequence size n = n - 2; } // Increment i, if not equal else { i++; } } // Return modified size return v.length;} // Driver Code let v = []; v.push("tom");v.push("jerry");v.push("jerry");v.push("tom"); document.write(removeConsecutiveSame(v)); // This code is contributed by gfgking</script> 0 Method 2:(Using Stack) 1- Start traversing the strings and push into stack. a) Check if the current string is same as the string at the top of the stack i) If yes, pop the string from top. ii) Else push the current string. 2- Return stack size if the whole sequence is traversed. Implementation: C++ Java Python3 C# Javascript // C++ implementation of above method#include<bits/stdc++.h>using namespace std; // Function to find the size of manipulated sequenceint removeConsecutiveSame(vector <string> v){ stack<string> st; // Start traversing the sequence for (int i=0; i<v.size(); i++) { // Push the current string if the stack // is empty if (st.empty()) st.push(v[i]); else { string str = st.top(); // compare the current string with stack top // if equal, pop the top if (str.compare(v[i]) == 0) st.pop(); // Otherwise push the current string else st.push(v[i]); } } // Return stack size return st.size();} // Driver codeint main(){ vector<string> V = { "ab", "aa", "aa", "bcd", "ab"}; cout << removeConsecutiveSame(V); return 0;} // Java implementation of above method import java.util.Stack;import java.util.Vector; class Test{ // Method to find the size of manipulated sequence static int removeConsecutiveSame(Vector <String> v) { Stack<String> st = new Stack<>(); // Start traversing the sequence for (int i=0; i<v.size(); i++) { // Push the current string if the stack // is empty if (st.empty()) st.push(v.get(i)); else { String str = st.peek(); // compare the current string with stack top // if equal, pop the top if (str.equals(v.get(i))) st.pop(); // Otherwise push the current string else st.push(v.get(i)); } } // Return stack size return st.size(); } // Driver method public static void main(String[] args) { Vector<String> v = new Vector<>(); v.addElement("ab"); v.addElement("aa"); v.addElement("aa");v.addElement("bcd"); v.addElement("ab"); System.out.println(removeConsecutiveSame(v)); }} # Python implementation of above method # Function to find the size of manipulated sequencedef removeConsecutiveSame(v): st = [] # Start traversing the sequence for i in range(len(v)): # Push the current string if the stack # is empty if (len(st) == 0): st.append(v[i]) else: Str = st[-1] # compare the current string with stack top # if equal, pop the top if (Str == v[i]): st.pop() # Otherwise push the current string else: st.append(v[i]) # Return stack size return len(st) # Driver codeif __name__ == '__main__': V = [ "ab", "aa", "aa", "bcd", "ab"] print(removeConsecutiveSame(V)) # This code is contributed by PranchalK. // C# implementation of above methodusing System;using System.Collections.Generic; class GFG{// Method to find the size of// manipulated sequencepublic static int removeConsecutiveSame(List<string> v){ Stack<string> st = new Stack<string>(); // Start traversing the sequence for (int i = 0; i < v.Count; i++) { // Push the current string if // the stack is empty if (st.Count == 0) { st.Push(v[i]); } else { string str = st.Peek(); // compare the current string with // stack top if equal, pop the top if (str.Equals(v[i])) { st.Pop(); } // Otherwise push the current // string else { st.Push(v[i]); } } } // Return stack size return st.Count;} // Driver Codepublic static void Main(string[] args){ List<string> v = new List<string>(); v.Add("ab"); v.Add("aa"); v.Add("aa"); v.Add("bcd"); v.Add("ab"); Console.WriteLine(removeConsecutiveSame(v));}} // This code is contributed by Shrikant13 <script> // Javascript implementation of above method // Method to find the size of // manipulated sequence function removeConsecutiveSame(v) { let st = []; // Start traversing the sequence for (let i = 0; i < v.length; i++) { // Push the current string if // the stack is empty if (st.length == 0) { st.push(v[i]); } else { let str = st[st.length - 1]; // compare the current string with // stack top if equal, pop the top if (str == v[i]) { st.pop(); } // Otherwise push the current // string else { st.push(v[i]); } } } // Return stack size return st.length; } let v = []; v.push("ab"); v.push("aa"); v.push("aa"); v.push("bcd"); v.push("ab"); document.write(removeConsecutiveSame(v)); // This code is contributed by decode2207.</script> 3 This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. shrikanth13 PranchalKatiyar SHUBHAMSINGH10 gfgking decode2207 hardikkoriintern mitalibhola94 Arrays Sorting Stack Arrays Stack Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2022" }, { "code": null, "e": 257, "s": 52, "text": "Given a sequence of n strings, the task is to check if any two similar words come together then they destroy each other than print the number of words left in the sequence after this pairwise destruction." }, { "code": null, "e": 268, "s": 257, "text": "Examples: " }, { "code": null, "e": 569, "s": 268, "text": "Input : ab aa aa bcd ab\nOutput : 3\nAs aa, aa destroys each other so, ab bcd ab is the\nnew sequence.\n\nInput : tom jerry jerry tom\nOutput : 0\nAs first both jerry will destroy each other.\nThen sequence will be tom, tom they will also destroy\neach other. So, the final sequence doesn't contain any\nword." }, { "code": null, "e": 580, "s": 569, "text": "Method 1: " }, { "code": null, "e": 794, "s": 580, "text": "1- Start traversing the sequence by storing it in vector.\n a) Check if the current string is equal to next string\n if yes, erase both from the vector.\n b) And check the same till last.\n2- Return vector size." }, { "code": null, "e": 810, "s": 794, "text": "Implementation:" }, { "code": null, "e": 814, "s": 810, "text": "C++" }, { "code": null, "e": 819, "s": 814, "text": "Java" }, { "code": null, "e": 827, "s": 819, "text": "Python3" }, { "code": null, "e": 830, "s": 827, "text": "C#" }, { "code": null, "e": 841, "s": 830, "text": "Javascript" }, { "code": "// C++ program to remove consecutive same words#include<bits/stdc++.h>using namespace std; // Function to find the size of manipulated sequenceint removeConsecutiveSame(vector <string > v){ int n = v.size(); // Start traversing the sequence for (int i=0; i<n-1; ) { // Compare the current string with next one // Erase both if equal if (v[i].compare(v[i+1]) == 0) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.erase(v.begin()+i); v.erase(v.begin()+i); // Update i, as to check from previous // element again if (i > 0) i--; // Reduce sequence size n = n-2; } // Increment i, if not equal else i++; } // Return modified size return v.size();} // Driver codeint main(){ vector<string> v = { \"tom\", \"jerry\", \"jerry\", \"tom\"}; cout << removeConsecutiveSame(v); return 0;}", "e": 1887, "s": 841, "text": null }, { "code": "// Java program to remove consecutive same words import java.util.Vector; class Test{ // Method to find the size of manipulated sequence static int removeConsecutiveSame(Vector <String > v) { int n = v.size(); // Start traversing the sequence for (int i=0; i<n-1; ) { // Compare the current string with next one // Erase both if equal if (v.get(i).equals(v.get(i+1))) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.remove(i); v.remove(i); // Update i, as to check from previous // element again if (i > 0) i--; // Reduce sequence size n = n-2; } // Increment i, if not equal else i++; } // Return modified size return v.size(); } // Driver method public static void main(String[] args) { Vector<String> v = new Vector<>(); v.addElement(\"tom\"); v.addElement(\"jerry\"); v.addElement(\"jerry\");v.addElement(\"tom\"); System.out.println(removeConsecutiveSame(v)); }}", "e": 3203, "s": 1887, "text": null }, { "code": "# Python3 program to remove consecutive# same words # Function to find the size of# manipulated sequencedef removeConsecutiveSame(v): n = len(v) # Start traversing the sequence i = 0 while(i < n - 1): # Compare the current string with # next one Erase both if equal if ((i + 1) < len(v)) and (v[i] == v[i + 1]): # Erase function delete the element and # also shifts other element that's why # i is not updated v = v[:i] v = v[:i] # Update i, as to check from previous # element again if (i > 0): i -= 1 # Reduce sequence size n = n - 2 # Increment i, if not equal else: i += 1 # Return modified size return len(v[:i - 1]) # Driver Codeif __name__ == '__main__': v = [\"tom\", \"jerry\", \"jerry\", \"tom\"] print(removeConsecutiveSame(v)) # This code is contributed by SHUBHAMSINGH10", "e": 4218, "s": 3203, "text": null }, { "code": "// C# program to remove consecutive same wordsusing System;using System.Collections.Generic; class GFG{// Method to find the size of// manipulated sequencepublic static int removeConsecutiveSame(List<string> v){ int n = v.Count; // Start traversing the sequence for (int i = 0; i < n - 1;) { // Compare the current string with // next one Erase both if equal if (v[i].Equals(v[i + 1])) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.RemoveAt(i); v.RemoveAt(i); // Update i, as to check from // previous element again if (i > 0) { i--; } // Reduce sequence size n = n - 2; } // Increment i, if not equal else { i++; } } // Return modified size return v.Count;} // Driver Codepublic static void Main(string[] args){ List<string> v = new List<string>(); v.Add(\"tom\"); v.Add(\"jerry\"); v.Add(\"jerry\"); v.Add(\"tom\"); Console.WriteLine(removeConsecutiveSame(v));}} // This code is contributed by Shrikant13", "e": 5443, "s": 4218, "text": null }, { "code": "<script>// Javascript program to remove consecutive same words // Method to find the size of// manipulated sequencefunction removeConsecutiveSame(v){ let n = v.length; // Start traversing the sequence for (let i = 0; i < n - 1;) { // Compare the current string with // next one Erase both if equal if (v[i] == (v[i + 1])) { // Erase function delete the element and // also shifts other element that's why // i is not updated v.splice(i, 1); v.splice(i, 1); // Update i, as to check from // previous element again if (i > 0) { i--; } // Reduce sequence size n = n - 2; } // Increment i, if not equal else { i++; } } // Return modified size return v.length;} // Driver Code let v = []; v.push(\"tom\");v.push(\"jerry\");v.push(\"jerry\");v.push(\"tom\"); document.write(removeConsecutiveSame(v)); // This code is contributed by gfgking</script>", "e": 6521, "s": 5443, "text": null }, { "code": null, "e": 6523, "s": 6521, "text": "0" }, { "code": null, "e": 6547, "s": 6523, "text": "Method 2:(Using Stack) " }, { "code": null, "e": 6831, "s": 6547, "text": "1- Start traversing the strings and push into stack.\n a) Check if the current string is same as the string\n at the top of the stack\n i) If yes, pop the string from top.\n ii) Else push the current string.\n2- Return stack size if the whole sequence is traversed." }, { "code": null, "e": 6847, "s": 6831, "text": "Implementation:" }, { "code": null, "e": 6851, "s": 6847, "text": "C++" }, { "code": null, "e": 6856, "s": 6851, "text": "Java" }, { "code": null, "e": 6864, "s": 6856, "text": "Python3" }, { "code": null, "e": 6867, "s": 6864, "text": "C#" }, { "code": null, "e": 6878, "s": 6867, "text": "Javascript" }, { "code": "// C++ implementation of above method#include<bits/stdc++.h>using namespace std; // Function to find the size of manipulated sequenceint removeConsecutiveSame(vector <string> v){ stack<string> st; // Start traversing the sequence for (int i=0; i<v.size(); i++) { // Push the current string if the stack // is empty if (st.empty()) st.push(v[i]); else { string str = st.top(); // compare the current string with stack top // if equal, pop the top if (str.compare(v[i]) == 0) st.pop(); // Otherwise push the current string else st.push(v[i]); } } // Return stack size return st.size();} // Driver codeint main(){ vector<string> V = { \"ab\", \"aa\", \"aa\", \"bcd\", \"ab\"}; cout << removeConsecutiveSame(V); return 0;}", "e": 7771, "s": 6878, "text": null }, { "code": "// Java implementation of above method import java.util.Stack;import java.util.Vector; class Test{ // Method to find the size of manipulated sequence static int removeConsecutiveSame(Vector <String> v) { Stack<String> st = new Stack<>(); // Start traversing the sequence for (int i=0; i<v.size(); i++) { // Push the current string if the stack // is empty if (st.empty()) st.push(v.get(i)); else { String str = st.peek(); // compare the current string with stack top // if equal, pop the top if (str.equals(v.get(i))) st.pop(); // Otherwise push the current string else st.push(v.get(i)); } } // Return stack size return st.size(); } // Driver method public static void main(String[] args) { Vector<String> v = new Vector<>(); v.addElement(\"ab\"); v.addElement(\"aa\"); v.addElement(\"aa\");v.addElement(\"bcd\"); v.addElement(\"ab\"); System.out.println(removeConsecutiveSame(v)); }}", "e": 9015, "s": 7771, "text": null }, { "code": "# Python implementation of above method # Function to find the size of manipulated sequencedef removeConsecutiveSame(v): st = [] # Start traversing the sequence for i in range(len(v)): # Push the current string if the stack # is empty if (len(st) == 0): st.append(v[i]) else: Str = st[-1] # compare the current string with stack top # if equal, pop the top if (Str == v[i]): st.pop() # Otherwise push the current string else: st.append(v[i]) # Return stack size return len(st) # Driver codeif __name__ == '__main__': V = [ \"ab\", \"aa\", \"aa\", \"bcd\", \"ab\"] print(removeConsecutiveSame(V)) # This code is contributed by PranchalK.", "e": 9811, "s": 9015, "text": null }, { "code": "// C# implementation of above methodusing System;using System.Collections.Generic; class GFG{// Method to find the size of// manipulated sequencepublic static int removeConsecutiveSame(List<string> v){ Stack<string> st = new Stack<string>(); // Start traversing the sequence for (int i = 0; i < v.Count; i++) { // Push the current string if // the stack is empty if (st.Count == 0) { st.Push(v[i]); } else { string str = st.Peek(); // compare the current string with // stack top if equal, pop the top if (str.Equals(v[i])) { st.Pop(); } // Otherwise push the current // string else { st.Push(v[i]); } } } // Return stack size return st.Count;} // Driver Codepublic static void Main(string[] args){ List<string> v = new List<string>(); v.Add(\"ab\"); v.Add(\"aa\"); v.Add(\"aa\"); v.Add(\"bcd\"); v.Add(\"ab\"); Console.WriteLine(removeConsecutiveSame(v));}} // This code is contributed by Shrikant13", "e": 10969, "s": 9811, "text": null }, { "code": "<script> // Javascript implementation of above method // Method to find the size of // manipulated sequence function removeConsecutiveSame(v) { let st = []; // Start traversing the sequence for (let i = 0; i < v.length; i++) { // Push the current string if // the stack is empty if (st.length == 0) { st.push(v[i]); } else { let str = st[st.length - 1]; // compare the current string with // stack top if equal, pop the top if (str == v[i]) { st.pop(); } // Otherwise push the current // string else { st.push(v[i]); } } } // Return stack size return st.length; } let v = []; v.push(\"ab\"); v.push(\"aa\"); v.push(\"aa\"); v.push(\"bcd\"); v.push(\"ab\"); document.write(removeConsecutiveSame(v)); // This code is contributed by decode2207.</script>", "e": 12122, "s": 10969, "text": null }, { "code": null, "e": 12124, "s": 12122, "text": "3" }, { "code": null, "e": 12422, "s": 12124, "text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 12434, "s": 12422, "text": "shrikanth13" }, { "code": null, "e": 12450, "s": 12434, "text": "PranchalKatiyar" }, { "code": null, "e": 12465, "s": 12450, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 12473, "s": 12465, "text": "gfgking" }, { "code": null, "e": 12484, "s": 12473, "text": "decode2207" }, { "code": null, "e": 12501, "s": 12484, "text": "hardikkoriintern" }, { "code": null, "e": 12515, "s": 12501, "text": "mitalibhola94" }, { "code": null, "e": 12522, "s": 12515, "text": "Arrays" }, { "code": null, "e": 12530, "s": 12522, "text": "Sorting" }, { "code": null, "e": 12536, "s": 12530, "text": "Stack" }, { "code": null, "e": 12543, "s": 12536, "text": "Arrays" }, { "code": null, "e": 12549, "s": 12543, "text": "Stack" }, { "code": null, "e": 12557, "s": 12549, "text": "Sorting" } ]
How to refresh entire application when date is changed in angular 9 ?
17 Dec, 2020 In this example, we will see how to refresh the application when the date is changed in angularJS. Approach: First, we need to write the code for displaying the date picker in an HTML file. We can achieve this by giving the input type as the date. After completing the input type, we need to declare a function on the ‘onchange’ event so that whenever the date is changed or modified the application will be reloaded. After declaring the function in the HTML file we need to write the function implementation in the ts file. In the function implementation, we can use the window property of DOM, and we can call the reload function so that the application is reloaded. After completing the above steps, serve or start the project. Code Implementation: app.component.ts: Javascript import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { constructor() { } // Function to reload the application refreshPage() { window.location.reload(); }} app.component.html: HTML <h1>Hello User !</h1> <p>Change the date to refresh the application.</p> <input type="date" (change)="refreshPage()"> app.module.ts: Javascript import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { } Output: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to setup 404 page in angular routing ? 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": "\n17 Dec, 2020" }, { "code": null, "e": 127, "s": 28, "text": "In this example, we will see how to refresh the application when the date is changed in angularJS." }, { "code": null, "e": 137, "s": 127, "text": "Approach:" }, { "code": null, "e": 218, "s": 137, "text": "First, we need to write the code for displaying the date picker in an HTML file." }, { "code": null, "e": 276, "s": 218, "text": "We can achieve this by giving the input type as the date." }, { "code": null, "e": 446, "s": 276, "text": "After completing the input type, we need to declare a function on the ‘onchange’ event so that whenever the date is changed or modified the application will be reloaded." }, { "code": null, "e": 553, "s": 446, "text": "After declaring the function in the HTML file we need to write the function implementation in the ts file." }, { "code": null, "e": 697, "s": 553, "text": "In the function implementation, we can use the window property of DOM, and we can call the reload function so that the application is reloaded." }, { "code": null, "e": 759, "s": 697, "text": "After completing the above steps, serve or start the project." }, { "code": null, "e": 780, "s": 759, "text": "Code Implementation:" }, { "code": null, "e": 798, "s": 780, "text": "app.component.ts:" }, { "code": null, "e": 809, "s": 798, "text": "Javascript" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { constructor() { } // Function to reload the application refreshPage() { window.location.reload(); }}", "e": 1118, "s": 809, "text": null }, { "code": null, "e": 1138, "s": 1118, "text": "app.component.html:" }, { "code": null, "e": 1143, "s": 1138, "text": "HTML" }, { "code": "<h1>Hello User !</h1> <p>Change the date to refresh the application.</p> <input type=\"date\" (change)=\"refreshPage()\">", "e": 1263, "s": 1143, "text": null }, { "code": null, "e": 1278, "s": 1263, "text": "app.module.ts:" }, { "code": null, "e": 1289, "s": 1278, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { }", "e": 1720, "s": 1289, "text": null }, { "code": null, "e": 1728, "s": 1720, "text": "Output:" }, { "code": null, "e": 1743, "s": 1728, "text": "AngularJS-Misc" }, { "code": null, "e": 1750, "s": 1743, "text": "Picked" }, { "code": null, "e": 1760, "s": 1750, "text": "AngularJS" }, { "code": null, "e": 1777, "s": 1760, "text": "Web Technologies" }, { "code": null, "e": 1875, "s": 1777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1899, "s": 1875, "text": "Routing in Angular 9/10" }, { "code": null, "e": 1934, "s": 1899, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 1958, "s": 1934, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 2011, "s": 1958, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 2054, "s": 2011, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 2087, "s": 2054, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2149, "s": 2087, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2210, "s": 2149, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2260, "s": 2210, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C++ Vector Library - insert() Function
The C++ function std::vector::insert() extends vector by inserting new element at position in container. Reallocation happens if there is need of more space. This function increases container size by one. Following is the declaration for std::vector::insert() function form std::vector header. iterator insert (iterator position, const value_type& val); iterator insert (const_iterator position, const value_type& val); position − Index in the vector where new element to be inserted. position − Index in the vector where new element to be inserted. val − Value to be assigned to newly inserted element. val − Value to be assigned to newly inserted element. Returns an iterator which points to the newly inserted element. Linear i.e. O(n) The following example shows the usage of std::vector::insert() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v = {3, 4, 5}; auto it = v.insert(v.begin(), 2); v.insert(it, 1); for (auto it = v.begin(); it != v.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result −
[ { "code": null, "e": 2895, "s": 2737, "text": "The C++ function std::vector::insert() extends vector by inserting new element at position in container. Reallocation happens if there is need of more space." }, { "code": null, "e": 2942, "s": 2895, "text": "This function increases container size by one." }, { "code": null, "e": 3031, "s": 2942, "text": "Following is the declaration for std::vector::insert() function form std::vector header." }, { "code": null, "e": 3092, "s": 3031, "text": "iterator insert (iterator position, const value_type& val);\n" }, { "code": null, "e": 3159, "s": 3092, "text": "iterator insert (const_iterator position, const value_type& val);\n" }, { "code": null, "e": 3224, "s": 3159, "text": "position − Index in the vector where new element to be inserted." }, { "code": null, "e": 3289, "s": 3224, "text": "position − Index in the vector where new element to be inserted." }, { "code": null, "e": 3343, "s": 3289, "text": "val − Value to be assigned to newly inserted element." }, { "code": null, "e": 3397, "s": 3343, "text": "val − Value to be assigned to newly inserted element." }, { "code": null, "e": 3461, "s": 3397, "text": "Returns an iterator which points to the newly inserted element." }, { "code": null, "e": 3478, "s": 3461, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3551, "s": 3478, "text": "The following example shows the usage of std::vector::insert() function." }, { "code": null, "e": 3811, "s": 3551, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {3, 4, 5};\n\n auto it = v.insert(v.begin(), 2);\n v.insert(it, 1);\n\n for (auto it = v.begin(); it != v.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" } ]
Tips for Writing better Conditionals in JavaScript
29 Sep, 2020 If you are working with JavaScript, you would be writing a lot of code with a lot of conditions involved. At first, conditionals may seem easy to learn, but there is more to it than to write a few if-else statements. Object-oriented programming allows one to avoid conditions and replace them with polymorphism and inheritance. You should follow these principles as much as possible. But on the other side, you may end up with the conditionals in your code for various reasons. This article’s purpose is to help you organize the conditional statements. Tips for writing code with conditionals: Array.includes: You can use array.includes() method for multiple conditions. The array.includes() method is used to determine if a particular element is present in the array. It returns “true” or “false”Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”.JavascriptJavascript// functionfunction test(animal) { if (animal == 'Lion' || animal == 'dog') { console.log('Valid'); }} // function calltest('dog');Output:ValidThe above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean.You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal.JavascriptJavascript function test(animal) { const animals = ['dog', 'cat', 'cow', 'Lion']; // Used to check if a particular // element is present if (animals.includes(animal)) { console.log('valid'); }}console.log(test('dog'));Output:validYou can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain.Array.every & Array.some:array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”.array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition.These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { let isAllblue = true; // Condition: all cars must be blue for (let c of cars) { if (!isAllblue) break; isAllblue = (c.color == 'blue'); } console.log(isAllblue);}test();Output:falseThe above code is little lengthy. You can reduce it by using Array.every() method.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { // Condition: short way // all cars must be in blue color const isAllblue = cars.every( c => c.color == 'blue'); console.log(isAllblue);}test();Output:falseYou can also implement it using Array.some() methodJavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test1() { // Condition: if any car is in blue color const isAnyblue = cars.some(c => c.color == 'blue'); console.log(isAnyblue); }test1();Output:trueReturn Early or Early exit: The Return Early in JavaScript is an easy way to reduce a function body to zero the number of “else” statements. There are many reasons to use Return Early in your code.It reduces the total amount of code.It reduces the length of the line by reducing the logical complexity.It helps to improve readability.The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions.Note: The following demonstrates the pseudocode for the above explanation.JavascriptJavascriptfunction IsRed(someObject) { // Declare a variable to // store the final value var willRed; // Compare type of object if (typeof someObject === 'object') { // Check object color property // is red or not if (someObject.color === 'Red') { willRed = true; } else { willRed = false; } } else { willRed = false; } return willRed;}This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements.JavascriptJavascript// Use return instead of else statementfunction IsRed(someObject) { if (typeof someObject !== 'object') { return false; } if (someObject.color !== 'Red') { return false; } return true;}Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise.You can also refactor this function by using only one “if” statement.JavascriptJavascript// Here you can reduce your codefunction IsRed(someObject) { // 2 if statements replaced // by 1 if statement if ( typeof someObject !== 'object' || someObject.color !== 'Red' ) { return false; } return true;}This function can be refactored again in a single line of code by using a ternary operator of JavaScript.JavascriptJavascriptfunction IsRed(someObject) { return typeof someObject !== 'object' || someObject.color !== 'Red' ? false : true;}You reduced all the nesting “if” statements, by reducing the conditions.Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s.Use Object Literal or Maps: The object literal is basically an array of key:value pairs which are used instead of switch statements. Let us look at the example below.JavascriptJavascriptfunction printCars(color) { // Use switch case to // find cars by color switch (color) { case 'red': return ['Rcar1', 'Rcar2']; case 'blue': return ['Bcar1', 'Bcar2']; case 'purple': return ['Pcar1', 'Pcar2']; default: return []; }} printCars(null);printCars('blue'); Output: [] ['Bcar1', 'Bcar2'] The above code can be refactored by using object literal and replacing the “switch” statement totally.JavascriptJavascript// Use object literal to // find cars by colorconst carColor = { red: ['Rcar1', 'Rcar2'], blue: ['Bcar1', 'Bcar2'], purple: ['Pcar1', 'Pcar2']}; function printcars(color) { return carColor[color] || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: [] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2'] You can also use Map to achieve the same result.JavascriptJavascript// Use map to find cars by colorconst carColor = new Map() .set('red', ['Rcar1', 'Rcar2']) .set('blue', ['Bcar1', 'Bcar2']) .set('purple', ['Pcar1', 'Pcar2']); function printcars(color) { return carColor.get(color) || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: [] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2'] Use Default Function parameters and Destructuring: The default parameter is a way to set default values for parameters of function in which a value is not passed in i.e. “undefined”.JavascriptJavascriptfunction check(flower, quantity) { if (!flower) return; // If quantity not provided, // set default to one const a = quantity || 1; console.log("I have ${a} ${flower}!");} // Resultscheck('Rose');check('Lotus', 2);Output:I have 1 Rose! I have 2 Lotus! Now you can use function parameter to set the default valueJavascriptJavascript// If quantity not provided, parameter// provided to set default to one function check(flower, quantity = 1) { if (!flower) return; console.log(`I have ${quantity} ${flower}!`);} // Results// (Default parameter is set)check('Rose');check('Lotus', 2); Output:I have 1 Rose! I have 2 Lotus! What if flower variable is an object? Can you assign the default parameter to it?JavascriptJavascriptfunction check(flower) { // Print flower name if // value provided if (flower && flower.name) { console.log(flower.name); } else { console.log('unknown'); }} // Resultscheck(undefined);check({});check({ name: 'Rose', color: 'red' });Output:unknown unknown Rose In the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing.Destructuring allows you to extract properties from objects.JavascriptJavascript// Destructing access name property only// assign the default empty object {} function check({name} = {}) { console.log (name || 'unknown');} // Resultscheck(undefined); check({ }); check({ name: 'Rose', color: 'red' }); Output:unknown unknown Rose We need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables.You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null.My Personal Notes arrow_drop_upSave Array.includes: You can use array.includes() method for multiple conditions. The array.includes() method is used to determine if a particular element is present in the array. It returns “true” or “false”Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”.JavascriptJavascript// functionfunction test(animal) { if (animal == 'Lion' || animal == 'dog') { console.log('Valid'); }} // function calltest('dog');Output:ValidThe above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean.You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal.JavascriptJavascript function test(animal) { const animals = ['dog', 'cat', 'cow', 'Lion']; // Used to check if a particular // element is present if (animals.includes(animal)) { console.log('valid'); }}console.log(test('dog'));Output:validYou can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain. Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”. Javascript // functionfunction test(animal) { if (animal == 'Lion' || animal == 'dog') { console.log('Valid'); }} // function calltest('dog'); Output: Valid The above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean. You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal. Javascript function test(animal) { const animals = ['dog', 'cat', 'cow', 'Lion']; // Used to check if a particular // element is present if (animals.includes(animal)) { console.log('valid'); }}console.log(test('dog')); Output: valid You can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain. Array.every & Array.some:array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”.array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition.These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { let isAllblue = true; // Condition: all cars must be blue for (let c of cars) { if (!isAllblue) break; isAllblue = (c.color == 'blue'); } console.log(isAllblue);}test();Output:falseThe above code is little lengthy. You can reduce it by using Array.every() method.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { // Condition: short way // all cars must be in blue color const isAllblue = cars.every( c => c.color == 'blue'); console.log(isAllblue);}test();Output:falseYou can also implement it using Array.some() methodJavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test1() { // Condition: if any car is in blue color const isAnyblue = cars.some(c => c.color == 'blue'); console.log(isAnyblue); }test1();Output:true array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”. array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition. These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below. Javascript // Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { let isAllblue = true; // Condition: all cars must be blue for (let c of cars) { if (!isAllblue) break; isAllblue = (c.color == 'blue'); } console.log(isAllblue);}test(); Output: false The above code is little lengthy. You can reduce it by using Array.every() method. Javascript // Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { // Condition: short way // all cars must be in blue color const isAllblue = cars.every( c => c.color == 'blue'); console.log(isAllblue);}test(); Output: false You can also implement it using Array.some() method Javascript // Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test1() { // Condition: if any car is in blue color const isAnyblue = cars.some(c => c.color == 'blue'); console.log(isAnyblue); }test1(); Output: true Return Early or Early exit: The Return Early in JavaScript is an easy way to reduce a function body to zero the number of “else” statements. There are many reasons to use Return Early in your code.It reduces the total amount of code.It reduces the length of the line by reducing the logical complexity.It helps to improve readability.The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions.Note: The following demonstrates the pseudocode for the above explanation.JavascriptJavascriptfunction IsRed(someObject) { // Declare a variable to // store the final value var willRed; // Compare type of object if (typeof someObject === 'object') { // Check object color property // is red or not if (someObject.color === 'Red') { willRed = true; } else { willRed = false; } } else { willRed = false; } return willRed;}This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements.JavascriptJavascript// Use return instead of else statementfunction IsRed(someObject) { if (typeof someObject !== 'object') { return false; } if (someObject.color !== 'Red') { return false; } return true;}Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise.You can also refactor this function by using only one “if” statement.JavascriptJavascript// Here you can reduce your codefunction IsRed(someObject) { // 2 if statements replaced // by 1 if statement if ( typeof someObject !== 'object' || someObject.color !== 'Red' ) { return false; } return true;}This function can be refactored again in a single line of code by using a ternary operator of JavaScript.JavascriptJavascriptfunction IsRed(someObject) { return typeof someObject !== 'object' || someObject.color !== 'Red' ? false : true;}You reduced all the nesting “if” statements, by reducing the conditions.Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s. It reduces the total amount of code.It reduces the length of the line by reducing the logical complexity.It helps to improve readability. It reduces the total amount of code. It reduces the length of the line by reducing the logical complexity. It helps to improve readability. The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions. Note: The following demonstrates the pseudocode for the above explanation. Javascript function IsRed(someObject) { // Declare a variable to // store the final value var willRed; // Compare type of object if (typeof someObject === 'object') { // Check object color property // is red or not if (someObject.color === 'Red') { willRed = true; } else { willRed = false; } } else { willRed = false; } return willRed;} This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements. Javascript // Use return instead of else statementfunction IsRed(someObject) { if (typeof someObject !== 'object') { return false; } if (someObject.color !== 'Red') { return false; } return true;} Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise. You can also refactor this function by using only one “if” statement. Javascript // Here you can reduce your codefunction IsRed(someObject) { // 2 if statements replaced // by 1 if statement if ( typeof someObject !== 'object' || someObject.color !== 'Red' ) { return false; } return true;} This function can be refactored again in a single line of code by using a ternary operator of JavaScript. Javascript function IsRed(someObject) { return typeof someObject !== 'object' || someObject.color !== 'Red' ? false : true;} You reduced all the nesting “if” statements, by reducing the conditions. Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s. Use Object Literal or Maps: The object literal is basically an array of key:value pairs which are used instead of switch statements. Let us look at the example below.JavascriptJavascriptfunction printCars(color) { // Use switch case to // find cars by color switch (color) { case 'red': return ['Rcar1', 'Rcar2']; case 'blue': return ['Bcar1', 'Bcar2']; case 'purple': return ['Pcar1', 'Pcar2']; default: return []; }} printCars(null);printCars('blue'); Output: [] ['Bcar1', 'Bcar2'] The above code can be refactored by using object literal and replacing the “switch” statement totally.JavascriptJavascript// Use object literal to // find cars by colorconst carColor = { red: ['Rcar1', 'Rcar2'], blue: ['Bcar1', 'Bcar2'], purple: ['Pcar1', 'Pcar2']}; function printcars(color) { return carColor[color] || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: [] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2'] You can also use Map to achieve the same result.JavascriptJavascript// Use map to find cars by colorconst carColor = new Map() .set('red', ['Rcar1', 'Rcar2']) .set('blue', ['Bcar1', 'Bcar2']) .set('purple', ['Pcar1', 'Pcar2']); function printcars(color) { return carColor.get(color) || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: [] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2'] Javascript function printCars(color) { // Use switch case to // find cars by color switch (color) { case 'red': return ['Rcar1', 'Rcar2']; case 'blue': return ['Bcar1', 'Bcar2']; case 'purple': return ['Pcar1', 'Pcar2']; default: return []; }} printCars(null);printCars('blue'); Output: [] ['Bcar1', 'Bcar2'] The above code can be refactored by using object literal and replacing the “switch” statement totally. Javascript // Use object literal to // find cars by colorconst carColor = { red: ['Rcar1', 'Rcar2'], blue: ['Bcar1', 'Bcar2'], purple: ['Pcar1', 'Pcar2']}; function printcars(color) { return carColor[color] || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: [] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2'] You can also use Map to achieve the same result. Javascript // Use map to find cars by colorconst carColor = new Map() .set('red', ['Rcar1', 'Rcar2']) .set('blue', ['Bcar1', 'Bcar2']) .set('purple', ['Pcar1', 'Pcar2']); function printcars(color) { return carColor.get(color) || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: [] ['Rcar1', 'Rcar2'] ['Bcar1', 'Bcar2'] Use Default Function parameters and Destructuring: The default parameter is a way to set default values for parameters of function in which a value is not passed in i.e. “undefined”.JavascriptJavascriptfunction check(flower, quantity) { if (!flower) return; // If quantity not provided, // set default to one const a = quantity || 1; console.log("I have ${a} ${flower}!");} // Resultscheck('Rose');check('Lotus', 2);Output:I have 1 Rose! I have 2 Lotus! Now you can use function parameter to set the default valueJavascriptJavascript// If quantity not provided, parameter// provided to set default to one function check(flower, quantity = 1) { if (!flower) return; console.log(`I have ${quantity} ${flower}!`);} // Results// (Default parameter is set)check('Rose');check('Lotus', 2); Output:I have 1 Rose! I have 2 Lotus! What if flower variable is an object? Can you assign the default parameter to it?JavascriptJavascriptfunction check(flower) { // Print flower name if // value provided if (flower && flower.name) { console.log(flower.name); } else { console.log('unknown'); }} // Resultscheck(undefined);check({});check({ name: 'Rose', color: 'red' });Output:unknown unknown Rose In the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing.Destructuring allows you to extract properties from objects.JavascriptJavascript// Destructing access name property only// assign the default empty object {} function check({name} = {}) { console.log (name || 'unknown');} // Resultscheck(undefined); check({ }); check({ name: 'Rose', color: 'red' }); Output:unknown unknown Rose We need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables.You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null.My Personal Notes arrow_drop_upSave Javascript function check(flower, quantity) { if (!flower) return; // If quantity not provided, // set default to one const a = quantity || 1; console.log("I have ${a} ${flower}!");} // Resultscheck('Rose');check('Lotus', 2); Output: I have 1 Rose! I have 2 Lotus! Now you can use function parameter to set the default value Javascript // If quantity not provided, parameter// provided to set default to one function check(flower, quantity = 1) { if (!flower) return; console.log(`I have ${quantity} ${flower}!`);} // Results// (Default parameter is set)check('Rose');check('Lotus', 2); Output: I have 1 Rose! I have 2 Lotus! What if flower variable is an object? Can you assign the default parameter to it? Javascript function check(flower) { // Print flower name if // value provided if (flower && flower.name) { console.log(flower.name); } else { console.log('unknown'); }} // Resultscheck(undefined);check({});check({ name: 'Rose', color: 'red' }); Output: unknown unknown Rose In the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing. Destructuring allows you to extract properties from objects. Javascript // Destructing access name property only// assign the default empty object {} function check({name} = {}) { console.log (name || 'unknown');} // Resultscheck(undefined); check({ }); check({ name: 'Rose', color: 'red' }); Output: unknown unknown Rose We need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables. You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null. javascript-basics JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Sep, 2020" }, { "code": null, "e": 270, "s": 53, "text": "If you are working with JavaScript, you would be writing a lot of code with a lot of conditions involved. At first, conditionals may seem easy to learn, but there is more to it than to write a few if-else statements." }, { "code": null, "e": 606, "s": 270, "text": "Object-oriented programming allows one to avoid conditions and replace them with polymorphism and inheritance. You should follow these principles as much as possible. But on the other side, you may end up with the conditionals in your code for various reasons. This article’s purpose is to help you organize the conditional statements." }, { "code": null, "e": 647, "s": 606, "text": "Tips for writing code with conditionals:" }, { "code": null, "e": 10254, "s": 647, "text": "Array.includes: You can use array.includes() method for multiple conditions. The array.includes() method is used to determine if a particular element is present in the array. It returns “true” or “false”Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”.JavascriptJavascript// functionfunction test(animal) { if (animal == 'Lion' || animal == 'dog') { console.log('Valid'); }} // function calltest('dog');Output:ValidThe above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean.You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal.JavascriptJavascript function test(animal) { const animals = ['dog', 'cat', 'cow', 'Lion']; // Used to check if a particular // element is present if (animals.includes(animal)) { console.log('valid'); }}console.log(test('dog'));Output:validYou can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain.Array.every & Array.some:array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”.array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition.These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { let isAllblue = true; // Condition: all cars must be blue for (let c of cars) { if (!isAllblue) break; isAllblue = (c.color == 'blue'); } console.log(isAllblue);}test();Output:falseThe above code is little lengthy. You can reduce it by using Array.every() method.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { // Condition: short way // all cars must be in blue color const isAllblue = cars.every( c => c.color == 'blue'); console.log(isAllblue);}test();Output:falseYou can also implement it using Array.some() methodJavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test1() { // Condition: if any car is in blue color const isAnyblue = cars.some(c => c.color == 'blue'); console.log(isAnyblue); }test1();Output:trueReturn Early or Early exit: The Return Early in JavaScript is an easy way to reduce a function body to zero the number of “else” statements. There are many reasons to use Return Early in your code.It reduces the total amount of code.It reduces the length of the line by reducing the logical complexity.It helps to improve readability.The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions.Note: The following demonstrates the pseudocode for the above explanation.JavascriptJavascriptfunction IsRed(someObject) { // Declare a variable to // store the final value var willRed; // Compare type of object if (typeof someObject === 'object') { // Check object color property // is red or not if (someObject.color === 'Red') { willRed = true; } else { willRed = false; } } else { willRed = false; } return willRed;}This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements.JavascriptJavascript// Use return instead of else statementfunction IsRed(someObject) { if (typeof someObject !== 'object') { return false; } if (someObject.color !== 'Red') { return false; } return true;}Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise.You can also refactor this function by using only one “if” statement.JavascriptJavascript// Here you can reduce your codefunction IsRed(someObject) { // 2 if statements replaced // by 1 if statement if ( typeof someObject !== 'object' || someObject.color !== 'Red' ) { return false; } return true;}This function can be refactored again in a single line of code by using a ternary operator of JavaScript.JavascriptJavascriptfunction IsRed(someObject) { return typeof someObject !== 'object' || someObject.color !== 'Red' ? false : true;}You reduced all the nesting “if” statements, by reducing the conditions.Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s.Use Object Literal or Maps: The object literal is basically an array of key:value pairs which are used instead of switch statements. Let us look at the example below.JavascriptJavascriptfunction printCars(color) { // Use switch case to // find cars by color switch (color) { case 'red': return ['Rcar1', 'Rcar2']; case 'blue': return ['Bcar1', 'Bcar2']; case 'purple': return ['Pcar1', 'Pcar2']; default: return []; }} printCars(null);printCars('blue'); Output: []\n['Bcar1', 'Bcar2']\nThe above code can be refactored by using object literal and replacing the “switch” statement totally.JavascriptJavascript// Use object literal to // find cars by colorconst carColor = { red: ['Rcar1', 'Rcar2'], blue: ['Bcar1', 'Bcar2'], purple: ['Pcar1', 'Pcar2']}; function printcars(color) { return carColor[color] || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: []\n ['Rcar1', 'Rcar2']\n ['Bcar1', 'Bcar2']\nYou can also use Map to achieve the same result.JavascriptJavascript// Use map to find cars by colorconst carColor = new Map() .set('red', ['Rcar1', 'Rcar2']) .set('blue', ['Bcar1', 'Bcar2']) .set('purple', ['Pcar1', 'Pcar2']); function printcars(color) { return carColor.get(color) || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: []\n ['Rcar1', 'Rcar2']\n ['Bcar1', 'Bcar2']\nUse Default Function parameters and Destructuring: The default parameter is a way to set default values for parameters of function in which a value is not passed in i.e. “undefined”.JavascriptJavascriptfunction check(flower, quantity) { if (!flower) return; // If quantity not provided, // set default to one const a = quantity || 1; console.log(\"I have ${a} ${flower}!\");} // Resultscheck('Rose');check('Lotus', 2);Output:I have 1 Rose!\nI have 2 Lotus!\nNow you can use function parameter to set the default valueJavascriptJavascript// If quantity not provided, parameter// provided to set default to one function check(flower, quantity = 1) { if (!flower) return; console.log(`I have ${quantity} ${flower}!`);} // Results// (Default parameter is set)check('Rose');check('Lotus', 2); Output:I have 1 Rose! \nI have 2 Lotus!\nWhat if flower variable is an object? Can you assign the default parameter to it?JavascriptJavascriptfunction check(flower) { // Print flower name if // value provided if (flower && flower.name) { console.log(flower.name); } else { console.log('unknown'); }} // Resultscheck(undefined);check({});check({ name: 'Rose', color: 'red' });Output:unknown\nunknown\n Rose\nIn the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing.Destructuring allows you to extract properties from objects.JavascriptJavascript// Destructing access name property only// assign the default empty object {} function check({name} = {}) { console.log (name || 'unknown');} // Resultscheck(undefined); check({ }); check({ name: 'Rose', color: 'red' }); Output:unknown\nunknown\n Rose\nWe need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables.You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 11698, "s": 10254, "text": "Array.includes: You can use array.includes() method for multiple conditions. The array.includes() method is used to determine if a particular element is present in the array. It returns “true” or “false”Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”.JavascriptJavascript// functionfunction test(animal) { if (animal == 'Lion' || animal == 'dog') { console.log('Valid'); }} // function calltest('dog');Output:ValidThe above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean.You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal.JavascriptJavascript function test(animal) { const animals = ['dog', 'cat', 'cow', 'Lion']; // Used to check if a particular // element is present if (animals.includes(animal)) { console.log('valid'); }}console.log(test('dog'));Output:validYou can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain." }, { "code": null, "e": 11791, "s": 11698, "text": "Example: The following code demonstrates, how to check if the animal is a “lion” or a “dog”." }, { "code": null, "e": 11802, "s": 11791, "text": "Javascript" }, { "code": "// functionfunction test(animal) { if (animal == 'Lion' || animal == 'dog') { console.log('Valid'); }} // function calltest('dog');", "e": 11948, "s": 11802, "text": null }, { "code": null, "e": 11956, "s": 11948, "text": "Output:" }, { "code": null, "e": 11962, "s": 11956, "text": "Valid" }, { "code": null, "e": 12263, "s": 11962, "text": "The above code seems to be easy because you have only two animals to check for. However, you are not sure about the input of the user. What if you get a few more animals? If you keep expanding the statement with more OR statements, the code would be more difficult to maintain and looks very unclean." }, { "code": null, "e": 12399, "s": 12263, "text": "You can rewrite the function to make it cleaner. All you need to do is add a new array item if you want to check for some other animal." }, { "code": null, "e": 12410, "s": 12399, "text": "Javascript" }, { "code": " function test(animal) { const animals = ['dog', 'cat', 'cow', 'Lion']; // Used to check if a particular // element is present if (animals.includes(animal)) { console.log('valid'); }}console.log(test('dog'));", "e": 12646, "s": 12410, "text": null }, { "code": null, "e": 12654, "s": 12646, "text": "Output:" }, { "code": null, "e": 12660, "s": 12654, "text": "valid" }, { "code": null, "e": 12930, "s": 12660, "text": "You can create an array of animals to separate the conditions from the rest of the code. You can even declare the variable out of the scope of the function and reuse it wherever you need it. This is a way to write a cleaner code that is easy to understand and maintain." }, { "code": null, "e": 14777, "s": 12930, "text": "Array.every & Array.some:array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”.array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition.These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { let isAllblue = true; // Condition: all cars must be blue for (let c of cars) { if (!isAllblue) break; isAllblue = (c.color == 'blue'); } console.log(isAllblue);}test();Output:falseThe above code is little lengthy. You can reduce it by using Array.every() method.JavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { // Condition: short way // all cars must be in blue color const isAllblue = cars.every( c => c.color == 'blue'); console.log(isAllblue);}test();Output:falseYou can also implement it using Array.some() methodJavascriptJavascript// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test1() { // Condition: if any car is in blue color const isAnyblue = cars.some(c => c.color == 'blue'); console.log(isAnyblue); }test1();Output:true" }, { "code": null, "e": 14989, "s": 14777, "text": "array.every() method is used to check if all the elements present in the array satisfies the given condition. It returns “true” when each array element satisfies the given condition otherwise it returns “false”." }, { "code": null, "e": 15258, "s": 14989, "text": "array.some() method checks if any of the elements in the array have passed the test of function provided. The array.some() method executes the function once for every element of the array. It checks if at least one of the elements of the array satisfies the condition." }, { "code": null, "e": 15363, "s": 15258, "text": "These two JavaScript Array functions are used to reduce the lines of code. Look at the code given below." }, { "code": null, "e": 15374, "s": 15363, "text": "Javascript" }, { "code": "// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { let isAllblue = true; // Condition: all cars must be blue for (let c of cars) { if (!isAllblue) break; isAllblue = (c.color == 'blue'); } console.log(isAllblue);}test();", "e": 15740, "s": 15374, "text": null }, { "code": null, "e": 15748, "s": 15740, "text": "Output:" }, { "code": null, "e": 15754, "s": 15748, "text": "false" }, { "code": null, "e": 15837, "s": 15754, "text": "The above code is little lengthy. You can reduce it by using Array.every() method." }, { "code": null, "e": 15848, "s": 15837, "text": "Javascript" }, { "code": "// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test() { // Condition: short way // all cars must be in blue color const isAllblue = cars.every( c => c.color == 'blue'); console.log(isAllblue);}test();", "e": 16195, "s": 15848, "text": null }, { "code": null, "e": 16203, "s": 16195, "text": "Output:" }, { "code": null, "e": 16209, "s": 16203, "text": "false" }, { "code": null, "e": 16261, "s": 16209, "text": "You can also implement it using Array.some() method" }, { "code": null, "e": 16272, "s": 16261, "text": "Javascript" }, { "code": "// Array of objectsconst cars = [ { name: 'car1', color: 'red' }, { name: 'car2', color: 'blue' }, { name: 'car3', color: 'purple' }]; function test1() { // Condition: if any car is in blue color const isAnyblue = cars.some(c => c.color == 'blue'); console.log(isAnyblue); }test1();", "e": 16572, "s": 16272, "text": null }, { "code": null, "e": 16580, "s": 16572, "text": "Output:" }, { "code": null, "e": 16585, "s": 16580, "text": "true" }, { "code": null, "e": 19061, "s": 16585, "text": "Return Early or Early exit: The Return Early in JavaScript is an easy way to reduce a function body to zero the number of “else” statements. There are many reasons to use Return Early in your code.It reduces the total amount of code.It reduces the length of the line by reducing the logical complexity.It helps to improve readability.The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions.Note: The following demonstrates the pseudocode for the above explanation.JavascriptJavascriptfunction IsRed(someObject) { // Declare a variable to // store the final value var willRed; // Compare type of object if (typeof someObject === 'object') { // Check object color property // is red or not if (someObject.color === 'Red') { willRed = true; } else { willRed = false; } } else { willRed = false; } return willRed;}This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements.JavascriptJavascript// Use return instead of else statementfunction IsRed(someObject) { if (typeof someObject !== 'object') { return false; } if (someObject.color !== 'Red') { return false; } return true;}Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise.You can also refactor this function by using only one “if” statement.JavascriptJavascript// Here you can reduce your codefunction IsRed(someObject) { // 2 if statements replaced // by 1 if statement if ( typeof someObject !== 'object' || someObject.color !== 'Red' ) { return false; } return true;}This function can be refactored again in a single line of code by using a ternary operator of JavaScript.JavascriptJavascriptfunction IsRed(someObject) { return typeof someObject !== 'object' || someObject.color !== 'Red' ? false : true;}You reduced all the nesting “if” statements, by reducing the conditions.Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s." }, { "code": null, "e": 19199, "s": 19061, "text": "It reduces the total amount of code.It reduces the length of the line by reducing the logical complexity.It helps to improve readability." }, { "code": null, "e": 19236, "s": 19199, "text": "It reduces the total amount of code." }, { "code": null, "e": 19306, "s": 19236, "text": "It reduces the length of the line by reducing the logical complexity." }, { "code": null, "e": 19339, "s": 19306, "text": "It helps to improve readability." }, { "code": null, "e": 19590, "s": 19339, "text": "The purpose of the Return early is to eliminate the need for “else” conditionals in JavaScript functions by using the “return” keyword in the “if” statement of the body. Let us create a function that will behave differently within certain conditions." }, { "code": null, "e": 19665, "s": 19590, "text": "Note: The following demonstrates the pseudocode for the above explanation." }, { "code": null, "e": 19676, "s": 19665, "text": "Javascript" }, { "code": "function IsRed(someObject) { // Declare a variable to // store the final value var willRed; // Compare type of object if (typeof someObject === 'object') { // Check object color property // is red or not if (someObject.color === 'Red') { willRed = true; } else { willRed = false; } } else { willRed = false; } return willRed;}", "e": 20101, "s": 19676, "text": null }, { "code": null, "e": 20278, "s": 20101, "text": "This function is clear, but it seems to be unnecessarily complicated. The Return early pattern can be used to increase readability and decrease the number of “else” statements." }, { "code": null, "e": 20289, "s": 20278, "text": "Javascript" }, { "code": "// Use return instead of else statementfunction IsRed(someObject) { if (typeof someObject !== 'object') { return false; } if (someObject.color !== 'Red') { return false; } return true;}", "e": 20508, "s": 20289, "text": null }, { "code": null, "e": 20653, "s": 20508, "text": "Using the Return Early pattern, we are able to eliminate all the unnecessary “else” statements and make your functions much clearer and concise." }, { "code": null, "e": 20723, "s": 20653, "text": "You can also refactor this function by using only one “if” statement." }, { "code": null, "e": 20734, "s": 20723, "text": "Javascript" }, { "code": "// Here you can reduce your codefunction IsRed(someObject) { // 2 if statements replaced // by 1 if statement if ( typeof someObject !== 'object' || someObject.color !== 'Red' ) { return false; } return true;}", "e": 20985, "s": 20734, "text": null }, { "code": null, "e": 21091, "s": 20985, "text": "This function can be refactored again in a single line of code by using a ternary operator of JavaScript." }, { "code": null, "e": 21102, "s": 21091, "text": "Javascript" }, { "code": "function IsRed(someObject) { return typeof someObject !== 'object' || someObject.color !== 'Red' ? false : true;}", "e": 21226, "s": 21102, "text": null }, { "code": null, "e": 21299, "s": 21226, "text": "You reduced all the nesting “if” statements, by reducing the conditions." }, { "code": null, "e": 21456, "s": 21299, "text": "Note: Always aim for lesser nesting and Return Early but don’t spoil it. If your code is short and straight-forward, and if it is clearer with nested “if”s." }, { "code": null, "e": 22949, "s": 21456, "text": "Use Object Literal or Maps: The object literal is basically an array of key:value pairs which are used instead of switch statements. Let us look at the example below.JavascriptJavascriptfunction printCars(color) { // Use switch case to // find cars by color switch (color) { case 'red': return ['Rcar1', 'Rcar2']; case 'blue': return ['Bcar1', 'Bcar2']; case 'purple': return ['Pcar1', 'Pcar2']; default: return []; }} printCars(null);printCars('blue'); Output: []\n['Bcar1', 'Bcar2']\nThe above code can be refactored by using object literal and replacing the “switch” statement totally.JavascriptJavascript// Use object literal to // find cars by colorconst carColor = { red: ['Rcar1', 'Rcar2'], blue: ['Bcar1', 'Bcar2'], purple: ['Pcar1', 'Pcar2']}; function printcars(color) { return carColor[color] || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: []\n ['Rcar1', 'Rcar2']\n ['Bcar1', 'Bcar2']\nYou can also use Map to achieve the same result.JavascriptJavascript// Use map to find cars by colorconst carColor = new Map() .set('red', ['Rcar1', 'Rcar2']) .set('blue', ['Bcar1', 'Bcar2']) .set('purple', ['Pcar1', 'Pcar2']); function printcars(color) { return carColor.get(color) || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); Output: []\n ['Rcar1', 'Rcar2']\n ['Bcar1', 'Bcar2']\n" }, { "code": null, "e": 22960, "s": 22949, "text": "Javascript" }, { "code": "function printCars(color) { // Use switch case to // find cars by color switch (color) { case 'red': return ['Rcar1', 'Rcar2']; case 'blue': return ['Bcar1', 'Bcar2']; case 'purple': return ['Pcar1', 'Pcar2']; default: return []; }} printCars(null);printCars('blue'); ", "e": 23320, "s": 22960, "text": null }, { "code": null, "e": 23328, "s": 23320, "text": "Output:" }, { "code": null, "e": 23352, "s": 23328, "text": " []\n['Bcar1', 'Bcar2']\n" }, { "code": null, "e": 23455, "s": 23352, "text": "The above code can be refactored by using object literal and replacing the “switch” statement totally." }, { "code": null, "e": 23466, "s": 23455, "text": "Javascript" }, { "code": "// Use object literal to // find cars by colorconst carColor = { red: ['Rcar1', 'Rcar2'], blue: ['Bcar1', 'Bcar2'], purple: ['Pcar1', 'Pcar2']}; function printcars(color) { return carColor[color] || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); ", "e": 23770, "s": 23466, "text": null }, { "code": null, "e": 23778, "s": 23770, "text": "Output:" }, { "code": null, "e": 23823, "s": 23778, "text": " []\n ['Rcar1', 'Rcar2']\n ['Bcar1', 'Bcar2']\n" }, { "code": null, "e": 23872, "s": 23823, "text": "You can also use Map to achieve the same result." }, { "code": null, "e": 23883, "s": 23872, "text": "Javascript" }, { "code": "// Use map to find cars by colorconst carColor = new Map() .set('red', ['Rcar1', 'Rcar2']) .set('blue', ['Bcar1', 'Bcar2']) .set('purple', ['Pcar1', 'Pcar2']); function printcars(color) { return carColor.get(color) || [];}console.log(printcars());console.log(printcars('red'));console.log(printcars('blue')); ", "e": 24206, "s": 23883, "text": null }, { "code": null, "e": 24214, "s": 24206, "text": "Output:" }, { "code": null, "e": 24259, "s": 24214, "text": " []\n ['Rcar1', 'Rcar2']\n ['Bcar1', 'Bcar2']\n" }, { "code": null, "e": 26610, "s": 24259, "text": "Use Default Function parameters and Destructuring: The default parameter is a way to set default values for parameters of function in which a value is not passed in i.e. “undefined”.JavascriptJavascriptfunction check(flower, quantity) { if (!flower) return; // If quantity not provided, // set default to one const a = quantity || 1; console.log(\"I have ${a} ${flower}!\");} // Resultscheck('Rose');check('Lotus', 2);Output:I have 1 Rose!\nI have 2 Lotus!\nNow you can use function parameter to set the default valueJavascriptJavascript// If quantity not provided, parameter// provided to set default to one function check(flower, quantity = 1) { if (!flower) return; console.log(`I have ${quantity} ${flower}!`);} // Results// (Default parameter is set)check('Rose');check('Lotus', 2); Output:I have 1 Rose! \nI have 2 Lotus!\nWhat if flower variable is an object? Can you assign the default parameter to it?JavascriptJavascriptfunction check(flower) { // Print flower name if // value provided if (flower && flower.name) { console.log(flower.name); } else { console.log('unknown'); }} // Resultscheck(undefined);check({});check({ name: 'Rose', color: 'red' });Output:unknown\nunknown\n Rose\nIn the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing.Destructuring allows you to extract properties from objects.JavascriptJavascript// Destructing access name property only// assign the default empty object {} function check({name} = {}) { console.log (name || 'unknown');} // Resultscheck(undefined); check({ }); check({ name: 'Rose', color: 'red' }); Output:unknown\nunknown\n Rose\nWe need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables.You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26621, "s": 26610, "text": "Javascript" }, { "code": "function check(flower, quantity) { if (!flower) return; // If quantity not provided, // set default to one const a = quantity || 1; console.log(\"I have ${a} ${flower}!\");} // Resultscheck('Rose');check('Lotus', 2);", "e": 26857, "s": 26621, "text": null }, { "code": null, "e": 26865, "s": 26857, "text": "Output:" }, { "code": null, "e": 26897, "s": 26865, "text": "I have 1 Rose!\nI have 2 Lotus!\n" }, { "code": null, "e": 26957, "s": 26897, "text": "Now you can use function parameter to set the default value" }, { "code": null, "e": 26968, "s": 26957, "text": "Javascript" }, { "code": "// If quantity not provided, parameter// provided to set default to one function check(flower, quantity = 1) { if (!flower) return; console.log(`I have ${quantity} ${flower}!`);} // Results// (Default parameter is set)check('Rose');check('Lotus', 2); ", "e": 27227, "s": 26968, "text": null }, { "code": null, "e": 27235, "s": 27227, "text": "Output:" }, { "code": null, "e": 27268, "s": 27235, "text": "I have 1 Rose! \nI have 2 Lotus!\n" }, { "code": null, "e": 27350, "s": 27268, "text": "What if flower variable is an object? Can you assign the default parameter to it?" }, { "code": null, "e": 27361, "s": 27350, "text": "Javascript" }, { "code": "function check(flower) { // Print flower name if // value provided if (flower && flower.name) { console.log(flower.name); } else { console.log('unknown'); }} // Resultscheck(undefined);check({});check({ name: 'Rose', color: 'red' });", "e": 27627, "s": 27361, "text": null }, { "code": null, "e": 27635, "s": 27627, "text": "Output:" }, { "code": null, "e": 27658, "s": 27635, "text": "unknown\nunknown\n Rose\n" }, { "code": null, "e": 27897, "s": 27658, "text": "In the above example, we want to print the “flower” name if it is available else it will print “unknown”, if the value is not known. We can avoid the conditionals “flower” and “flower.name” by using default function parameter destructing." }, { "code": null, "e": 27958, "s": 27897, "text": "Destructuring allows you to extract properties from objects." }, { "code": null, "e": 27969, "s": 27958, "text": "Javascript" }, { "code": "// Destructing access name property only// assign the default empty object {} function check({name} = {}) { console.log (name || 'unknown');} // Resultscheck(undefined); check({ }); check({ name: 'Rose', color: 'red' }); ", "e": 28196, "s": 27969, "text": null }, { "code": null, "e": 28204, "s": 28196, "text": "Output:" }, { "code": null, "e": 28227, "s": 28204, "text": "unknown\nunknown\n Rose\n" }, { "code": null, "e": 28462, "s": 28227, "text": "We need property name from flower, you can destructure that parameter using {name}, then use name as variable in your code instead of flower.name because destructuring allows you to assign the properties of an object to the variables." }, { "code": null, "e": 28725, "s": 28462, "text": "You also need to assign empty object {} as default value. If you don’t, it will show the error while executing the line “check(undefined)” i.e. cannot destructure the property name of ‘undefined’ or ‘null’, because there is no name property in undefined or null." }, { "code": null, "e": 28743, "s": 28725, "text": "javascript-basics" }, { "code": null, "e": 28759, "s": 28743, "text": "JavaScript-Misc" }, { "code": null, "e": 28770, "s": 28759, "text": "JavaScript" }, { "code": null, "e": 28787, "s": 28770, "text": "Web Technologies" } ]
Master Theorem For Subtract and Conquer Recurrences
31 May, 2021 Master theorem is used to determine the Big – O upper bound on functions which possess recurrence, i.e which can be broken into sub problems. Master Theorem For Subtract and Conquer Recurrences: Let T(n) be a function defined on positive n as shown below: for some constants c, a>0, b>0, k>=0 and function f(n). If f(n) is O(nk), then1. If a<1 then T(n) = O(nk) 2. If a=1 then T(n) = O(nk+1) 3. if a>1 then T(n) = O(nkan/b)Proof of above theorem( By substitution method ):From above function, we have: T(n) = aT(n-b) + f(n) T(n-b) = aT(n-2b) + f(n-b) T(n-2b) = aT(n-3b) + f(n-2b)Now, T(n-b) = a2T(n-3b) + af(n-2b) + f(n-b) T(n) = a3T(n-3b) + a2f(n-2b) + af(n-b) + f(n) T(n) = Σi=0 to n ai f(n-ib) + constant, where f(n-ib) is O(n-ib) T(n) = O(nk Σi=0 to n/b ai ) Where, If a<1 then Σi=0 to n/b ai = O(1), T(n) = O(nk)If a=1 then Σi=0 to n/b ai = O(n), T(n) = O(nk+1) If a>1 then Σi=0 to n/b ai = O(an/b), T(n) = O(nkan/b)Consider the following program for nth fibonacci number: C++ Python3 Java C# PHP Javascript #include<stdio.h>int fib(int n){ if (n <= 1) return n; return fib(n-1) + fib(n-2);} int main (){ int n = 9; printf("%d", fib(n)); getchar(); return 0;} # Python3 code for the above approachdef fib(n): if (n <= 1): return n return fib(n - 1) + fib(n - 2) # Driver coden = 9print(fib(n)) # This code is contributed# by sahishelangia //Java code for above the approach.class clg{ static int fib(int n){if (n <= 1) return n;return fib(n-1) + fib(n-2);}// Driver Codepublic static void main (String[] args){int n = 9;System.out.println( fib(n));}}// This code is contributed by Mukul Singh. // C# code for above the approach.using System; class GFG{ static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } // Driver Code public static void Main(String[] args) { int n = 9; Console.WriteLine(fib(n)); }} // This code has been contributed// by Rajput-Ji <?php// PHP code for the above approachfunction fib($n){ if ($n <= 1) return $n; return fib($n - 1) + fib($n - 2);} // Driver Code$n = 9;echo fib($n); // This code is contributed// by Akanksha Rai?> <script> // Javascript code for above the approach. function fib(n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } let n = 9; document.write(fib(n)); </script> Output 34 Time complexity Analysis: The recursive function can be defined as, T(n) = T(n-1) + T(n-2) For Worst Case, Let T(n-1) ≈ T(n-2) T(n) = 2T(n-1) + c where,f(n) = O(1) ∴ k=0, a=2, b=1;T(n) = O(n02n/1) = O(2n) For Best Case, Let T(n-2) ≈ T(n-1) T(n) = 2T(n-2) + c where,f(n) = O(1) ∴ k=0, a=2, b=2;T(n) = O(n02n/2) = O(2n/2) More Examples: Example-1: T(n) = 3T(n-1), n>0 = c, n<=0Sol:a=3, b=1, f(n)=0 so k=0;Since a>0, T(n) = O(nkan/b) T(n)= O(n03n/1) T(n)= 3n Example-2: T(n) = T(n-1) + n(n-1), if n>=2 = 1, if n=1Sol:a=1, b=1, f(n)=n(n-1) so k=2;Since a=1, T(n) = O(nk+1) T(n)= O(n2+1) T(n)= O(n3) Example-3: T(n) = 2T(n-1) – 1, if n>0 = 1, if n<=0Sol: This recurrence can’t be solved using above method since function is not of form T(n) = aT(n-b) + f(n) This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. sahilshelangia Akanksha_Rai Code_Mech Rajput-Ji rameshtravel07 Analysis Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between Deterministic and Non-deterministic Algorithms What is algorithm and why analysis of it is important? Time-Space Trade-Off in Algorithms Complexity analysis of various operations of Binary Min Heap Applications of Hashing Time Complexity Analysis | Tower Of Hanoi (Recursion) How to learn Pattern printing easily? Time Complexity of Euclidean Algorithm Difference between Instance Variable and Class Variable
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2021" }, { "code": null, "e": 312, "s": 54, "text": "Master theorem is used to determine the Big – O upper bound on functions which possess recurrence, i.e which can be broken into sub problems. Master Theorem For Subtract and Conquer Recurrences: Let T(n) be a function defined on positive n as shown below: " }, { "code": null, "e": 819, "s": 312, "text": "for some constants c, a>0, b>0, k>=0 and function f(n). If f(n) is O(nk), then1. If a<1 then T(n) = O(nk) 2. If a=1 then T(n) = O(nk+1) 3. if a>1 then T(n) = O(nkan/b)Proof of above theorem( By substitution method ):From above function, we have: T(n) = aT(n-b) + f(n) T(n-b) = aT(n-2b) + f(n-b) T(n-2b) = aT(n-3b) + f(n-2b)Now, T(n-b) = a2T(n-3b) + af(n-2b) + f(n-b) T(n) = a3T(n-3b) + a2f(n-2b) + af(n-b) + f(n) T(n) = Σi=0 to n ai f(n-ib) + constant, where f(n-ib) is O(n-ib) T(n) = O(nk Σi=0 to n/b ai )" }, { "code": null, "e": 1037, "s": 819, "text": " Where, If a<1 then Σi=0 to n/b ai = O(1), T(n) = O(nk)If a=1 then Σi=0 to n/b ai = O(n), T(n) = O(nk+1) If a>1 then Σi=0 to n/b ai = O(an/b), T(n) = O(nkan/b)Consider the following program for nth fibonacci number: " }, { "code": null, "e": 1041, "s": 1037, "text": "C++" }, { "code": null, "e": 1049, "s": 1041, "text": "Python3" }, { "code": null, "e": 1054, "s": 1049, "text": "Java" }, { "code": null, "e": 1057, "s": 1054, "text": "C#" }, { "code": null, "e": 1061, "s": 1057, "text": "PHP" }, { "code": null, "e": 1072, "s": 1061, "text": "Javascript" }, { "code": "#include<stdio.h>int fib(int n){ if (n <= 1) return n; return fib(n-1) + fib(n-2);} int main (){ int n = 9; printf(\"%d\", fib(n)); getchar(); return 0;}", "e": 1238, "s": 1072, "text": null }, { "code": "# Python3 code for the above approachdef fib(n): if (n <= 1): return n return fib(n - 1) + fib(n - 2) # Driver coden = 9print(fib(n)) # This code is contributed# by sahishelangia", "e": 1430, "s": 1238, "text": null }, { "code": "//Java code for above the approach.class clg{ static int fib(int n){if (n <= 1) return n;return fib(n-1) + fib(n-2);}// Driver Codepublic static void main (String[] args){int n = 9;System.out.println( fib(n));}}// This code is contributed by Mukul Singh.", "e": 1688, "s": 1430, "text": null }, { "code": "// C# code for above the approach.using System; class GFG{ static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } // Driver Code public static void Main(String[] args) { int n = 9; Console.WriteLine(fib(n)); }} // This code has been contributed// by Rajput-Ji", "e": 2042, "s": 1688, "text": null }, { "code": "<?php// PHP code for the above approachfunction fib($n){ if ($n <= 1) return $n; return fib($n - 1) + fib($n - 2);} // Driver Code$n = 9;echo fib($n); // This code is contributed// by Akanksha Rai?>", "e": 2264, "s": 2042, "text": null }, { "code": "<script> // Javascript code for above the approach. function fib(n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } let n = 9; document.write(fib(n)); </script>", "e": 2494, "s": 2264, "text": null }, { "code": null, "e": 2503, "s": 2494, "text": "Output " }, { "code": null, "e": 2506, "s": 2503, "text": "34" }, { "code": null, "e": 2599, "s": 2506, "text": "Time complexity Analysis: The recursive function can be defined as, T(n) = T(n-1) + T(n-2) " }, { "code": null, "e": 2715, "s": 2599, "text": "For Worst Case, Let T(n-1) ≈ T(n-2) T(n) = 2T(n-1) + c where,f(n) = O(1) ∴ k=0, a=2, b=1;T(n) = O(n02n/1) = O(2n) " }, { "code": null, "e": 2832, "s": 2715, "text": "For Best Case, Let T(n-2) ≈ T(n-1) T(n) = 2T(n-2) + c where,f(n) = O(1) ∴ k=0, a=2, b=2;T(n) = O(n02n/2) = O(2n/2) " }, { "code": null, "e": 2849, "s": 2834, "text": "More Examples:" }, { "code": null, "e": 2979, "s": 2851, "text": "Example-1: T(n) = 3T(n-1), n>0 = c, n<=0Sol:a=3, b=1, f(n)=0 so k=0;Since a>0, T(n) = O(nkan/b) T(n)= O(n03n/1) T(n)= 3n " }, { "code": null, "e": 3125, "s": 2979, "text": "Example-2: T(n) = T(n-1) + n(n-1), if n>=2 = 1, if n=1Sol:a=1, b=1, f(n)=n(n-1) so k=2;Since a=1, T(n) = O(nk+1) T(n)= O(n2+1) T(n)= O(n3) " }, { "code": null, "e": 3290, "s": 3125, "text": "Example-3: T(n) = 2T(n-1) – 1, if n>0 = 1, if n<=0Sol: This recurrence can’t be solved using above method since function is not of form T(n) = aT(n-b) + f(n) " }, { "code": null, "e": 3709, "s": 3290, "text": "This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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": 3724, "s": 3709, "text": "sahilshelangia" }, { "code": null, "e": 3737, "s": 3724, "text": "Akanksha_Rai" }, { "code": null, "e": 3747, "s": 3737, "text": "Code_Mech" }, { "code": null, "e": 3757, "s": 3747, "text": "Rajput-Ji" }, { "code": null, "e": 3772, "s": 3757, "text": "rameshtravel07" }, { "code": null, "e": 3781, "s": 3772, "text": "Analysis" }, { "code": null, "e": 3879, "s": 3781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3946, "s": 3879, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 4012, "s": 3946, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 4067, "s": 4012, "text": "What is algorithm and why analysis of it is important?" }, { "code": null, "e": 4102, "s": 4067, "text": "Time-Space Trade-Off in Algorithms" }, { "code": null, "e": 4163, "s": 4102, "text": "Complexity analysis of various operations of Binary Min Heap" }, { "code": null, "e": 4187, "s": 4163, "text": "Applications of Hashing" }, { "code": null, "e": 4241, "s": 4187, "text": "Time Complexity Analysis | Tower Of Hanoi (Recursion)" }, { "code": null, "e": 4279, "s": 4241, "text": "How to learn Pattern printing easily?" }, { "code": null, "e": 4318, "s": 4279, "text": "Time Complexity of Euclidean Algorithm" } ]
How to find the first Monday of a given month using NumPy?
02 Dec, 2020 To find the first Monday of a given month, we are going to use the numpy module i.e the numpy.busday_offset() method in numpy module. Syntax: np.busday_offset(‘date’, 0, roll=’forward’, weekmask=’Mon’) Parameters: date: The array of dates to process. offsets: The array of offsets, which is broadcast with dates. roll:It takes the below values: raise means to raise an exception for an invalid day. nat means to return a NaT (not-a-time) for an invalid day. forward and following mean to take the first valid day later in time. backward and preceding mean to take the first valid day earlier in time. modifiedfollowing means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time. modifiedpreceding means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time. weekmask: array indicating which of Monday through Sunday are valid days. Returns (outarray of datetime64): An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied. Example #1: In this example, we will find the first Monday of the month of May 2017. Python3 # import moduleimport numpy # input year and monthyearMonth = '2017-05' # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0, roll='forward', weekmask='Mon') # display dateprint(date) Output: 2017-05-01 Example #2: Here, we will find the first Monday of the month of February 2001. Python3 # import moduleimport numpy # input year and monthyearMonth = '2001-02' # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0, roll='forward', weekmask='Mon') # display dateprint(date) Output: 2001-02-05 Example #3: Here, we will find the first Monday of the month of November 2020. Python3 # import moduleimport numpy # input year and monthyearMonth = '2020-11' # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0, roll='forward', weekmask='Mon') # display dateprint(date) Output: 2001-11-02 Python numpy-DataType Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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 | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 162, "s": 28, "text": "To find the first Monday of a given month, we are going to use the numpy module i.e the numpy.busday_offset() method in numpy module." }, { "code": null, "e": 230, "s": 162, "text": "Syntax: np.busday_offset(‘date’, 0, roll=’forward’, weekmask=’Mon’)" }, { "code": null, "e": 242, "s": 230, "text": "Parameters:" }, { "code": null, "e": 279, "s": 242, "text": "date: The array of dates to process." }, { "code": null, "e": 341, "s": 279, "text": "offsets: The array of offsets, which is broadcast with dates." }, { "code": null, "e": 373, "s": 341, "text": "roll:It takes the below values:" }, { "code": null, "e": 427, "s": 373, "text": "raise means to raise an exception for an invalid day." }, { "code": null, "e": 486, "s": 427, "text": "nat means to return a NaT (not-a-time) for an invalid day." }, { "code": null, "e": 556, "s": 486, "text": "forward and following mean to take the first valid day later in time." }, { "code": null, "e": 629, "s": 556, "text": "backward and preceding mean to take the first valid day earlier in time." }, { "code": null, "e": 792, "s": 629, "text": "modifiedfollowing means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time." }, { "code": null, "e": 955, "s": 792, "text": "modifiedpreceding means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time." }, { "code": null, "e": 1029, "s": 955, "text": "weekmask: array indicating which of Monday through Sunday are valid days." }, { "code": null, "e": 1174, "s": 1029, "text": "Returns (outarray of datetime64): An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied." }, { "code": null, "e": 1186, "s": 1174, "text": "Example #1:" }, { "code": null, "e": 1259, "s": 1186, "text": "In this example, we will find the first Monday of the month of May 2017." }, { "code": null, "e": 1267, "s": 1259, "text": "Python3" }, { "code": "# import moduleimport numpy # input year and monthyearMonth = '2017-05' # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0, roll='forward', weekmask='Mon') # display dateprint(date)", "e": 1525, "s": 1267, "text": null }, { "code": null, "e": 1533, "s": 1525, "text": "Output:" }, { "code": null, "e": 1544, "s": 1533, "text": "2017-05-01" }, { "code": null, "e": 1556, "s": 1544, "text": "Example #2:" }, { "code": null, "e": 1623, "s": 1556, "text": "Here, we will find the first Monday of the month of February 2001." }, { "code": null, "e": 1631, "s": 1623, "text": "Python3" }, { "code": "# import moduleimport numpy # input year and monthyearMonth = '2001-02' # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0, roll='forward', weekmask='Mon') # display dateprint(date)", "e": 1887, "s": 1631, "text": null }, { "code": null, "e": 1895, "s": 1887, "text": "Output:" }, { "code": null, "e": 1906, "s": 1895, "text": "2001-02-05" }, { "code": null, "e": 1918, "s": 1906, "text": "Example #3:" }, { "code": null, "e": 1985, "s": 1918, "text": "Here, we will find the first Monday of the month of November 2020." }, { "code": null, "e": 1993, "s": 1985, "text": "Python3" }, { "code": "# import moduleimport numpy # input year and monthyearMonth = '2020-11' # getting date of first mondaydate = numpy.busday_offset(yearMonth, 0, roll='forward', weekmask='Mon') # display dateprint(date)", "e": 2249, "s": 1993, "text": null }, { "code": null, "e": 2257, "s": 2249, "text": "Output:" }, { "code": null, "e": 2268, "s": 2257, "text": "2001-11-02" }, { "code": null, "e": 2290, "s": 2268, "text": "Python numpy-DataType" }, { "code": null, "e": 2303, "s": 2290, "text": "Python-numpy" }, { "code": null, "e": 2310, "s": 2303, "text": "Python" }, { "code": null, "e": 2408, "s": 2310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2440, "s": 2408, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2467, "s": 2440, "text": "Python Classes and Objects" }, { "code": null, "e": 2488, "s": 2467, "text": "Python OOPs Concepts" }, { "code": null, "e": 2511, "s": 2488, "text": "Introduction To PYTHON" }, { "code": null, "e": 2542, "s": 2511, "text": "Python | os.path.join() method" }, { "code": null, "e": 2598, "s": 2542, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2640, "s": 2598, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2682, "s": 2640, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2721, "s": 2682, "text": "Python | Get unique values from a list" } ]
Program to print Sum Triangle for a given array
30 Jun, 2022 Given a array, write a program to construct a triangle where last row contains elements of given array, every element of second last row contains sum of below two elements and so on. Example: Input: arr[] = {4, 7, 3, 6, 7}; Output: 81 40 41 21 19 22 11 10 9 13 4 7 3 6 7 Input: {10, 40, 50} Output: 140 50 90 10 40 50 An important observation about output is final value is at the top and top element needs to printed first. Therefore, we use a 2D auxiliary array to construct the triangle in bottom up manner and then print the triangle. An element tri[i][j] of 2D array can be calculated as sum of tri[i+1][j] and tri[i+1][j+1]. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ program to print sum triangle for a given array#include <bits/stdc++.h>using namespace std; // prints sum triangle for arr[0..n-1]void printTriangle(int arr[], int n){ // Initialize a 2D array to store triangle int tri[n][n]; memset(tri, 0, sizeof(tri)); // Initialize last row of triangle for (int i = 0; i < n ; i++) tri[n-1][i] = arr[i]; // Fill other rows for (int i = n-2; i >=0; i--) for (int j = 0; j <= i; j++) tri[i][j] = tri[i+1][j] + tri[i+1][j+1]; // Print the triangle for (int i = 0; i < n; i++) { for(int j = 0; j <= i ; j++) cout << tri[i][j]<<" "; cout << endl; }} // Driver Programint main(){ int arr[] = {4, 7, 3, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); printTriangle(arr, n); return 0;} // Java program to print sum triangle for a given arrayclass Test{ static int arr[] = new int[]{4, 7, 3, 6, 7}; // prints sum triangle for arr[0..n-1] public static void printTriangle(int n) { // Initialize a 2D array to store triangle int tri[][] = new int[n][n]; // Initialize last row of triangle for (int i = 0; i < n ; i++) tri[n-1][i] = arr[i]; // Fill other rows for (int i = n-2; i >=0; i--) for (int j = 0; j <= i; j++) tri[i][j] = tri[i+1][j] + tri[i+1][j+1]; // Print the triangle for (int i = 0; i < n; i++) { for(int j = 0; j <= i ; j++) System.out.print(tri[i][j] + " "); System.out.println(); } } public static void main(String[] args) { printTriangle(arr.length); } } # Python 3 program to print sum triangle# for a given array # prints sum triangle for arr[0..n-1]def printTriangle(arr, n): # Initialize a 2D array to store triangle tri = [[0 for i in range(n)] for i in range(n)] # Initialize last row of triangle for i in range(n): tri[n - 1][i] = arr[i] # Fill other rows i = n - 2 while(i >= 0): for j in range(0, i + 1, 1): tri[i][j] = (tri[i + 1][j] + tri[i + 1][j + 1]) i -= 1 # Print the triangle for i in range(0, n, 1): for j in range(0, i + 1, 1): print(tri[i][j], end = " ") print("\n", end = "") # Driver Codeif __name__ == '__main__': arr = [4, 7, 3, 6, 7] n = len(arr) printTriangle(arr, n) # This code is contributed by# Shashank_Sharma // C# program to print sum triangle// for a given arrayusing System; class GFG { static int []arr = new int[]{4, 7, 3, 6, 7}; // prints sum triangle for arr[0..n-1] public static void printTriangle(int n) { // Initialize a 2D array to store triangle int [,]tri = new int[n, n]; // Initialize last row of triangle for (int i = 0; i < n ; i++) tri[n - 1, i] = arr[i]; // Fill other rows for (int i = n - 2; i >= 0; i--) for (int j = 0; j <= i; j++) tri[i, j] = tri[i + 1, j] + tri[i + 1, j + 1]; // Print the triangle for (int i = 0; i < n; i++) { for(int j = 0; j <= i ; j++) Console.Write(tri[i, j] + " "); Console.WriteLine(); } } // Driver Code public static void Main() { printTriangle(arr.Length); }} // This code is contributed by Sam007. <?php// PHP program to print sum// triangle for a given array // prints sum triangle for arr[0..n-1]function printTriangle($arr, $n){ // Initialize a 2D array to store triangle $tri[$n][$n] = array(array()); array_fill(0, count($tri), 0); // Initialize last row of triangle for ($i = 0; $i < $n ; $i++) $tri[$n - 1][$i] = $arr[$i]; // Fill other rows for ($i = $n - 2; $i >= 0; $i--) for ($j = 0; $j <= $i; $j++) $tri[$i][$j] = $tri[$i + 1][$j] + $tri[$i + 1][$j + 1]; // Print the triangle for ($i = 0; $i < $n; $i++) { for( $j = 0; $j <= $i ; $j++) echo $tri[$i][$j] . " "; echo "\n"; }} // Driver Code$arr = array(4, 7, 3, 6, 7);$n = count($arr);printTriangle($arr, $n); // This code is contributed by Rajput-Ji?> <script> // JavaScript program to print sum triangle for a given array // prints sum triangle for arr[0..n-1] function printTriangle(arr, n) { // Initialize a 2D array to store triangle var tri = new Array(n).fill(0).map((item) => new Array(n).fill(0)); // Initialize last row of triangle for (var i = 0; i < n; i++) tri[n - 1][i] = arr[i]; // Fill other rows for (var i = n - 2; i >= 0; i--) for (var j = 0; j <= i; j++) tri[i][j] = tri[i + 1][j] + tri[i + 1][j + 1]; // Print the triangle for (var i = 0; i < n; i++) { for (var j = 0; j <= i; j++) document.write(tri[i][j] + " "); document.write("<br>"); } } // Driver Program var arr = [4, 7, 3, 6, 7]; var n = arr.length; printTriangle(arr, n); // This code is contributed by rdtank. </script> Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 81 40 41 21 19 22 11 10 9 13 4 7 3 6 7 Time Complexity: O(n2) Print Sum Triangle for a given array | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrint Sum Triangle for a given array | 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=anyBv3m2emQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Thanks to nish for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 Shashank_Sharma Rajput-Ji rdtank anikakapoor akashish__ triangle Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 235, "s": 52, "text": "Given a array, write a program to construct a triangle where last row contains elements of given array, every element of second last row contains sum of below two elements and so on." }, { "code": null, "e": 245, "s": 235, "text": "Example: " }, { "code": null, "e": 373, "s": 245, "text": "Input: arr[] = {4, 7, 3, 6, 7};\nOutput:\n81\n40 41\n21 19 22\n11 10 9 13\n4 7 3 6 7 \n\nInput: {10, 40, 50}\nOutput:\n140\n50 90\n10 40 50" }, { "code": null, "e": 686, "s": 373, "text": "An important observation about output is final value is at the top and top element needs to printed first. Therefore, we use a 2D auxiliary array to construct the triangle in bottom up manner and then print the triangle. An element tri[i][j] of 2D array can be calculated as sum of tri[i+1][j] and tri[i+1][j+1]." }, { "code": null, "e": 731, "s": 686, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 735, "s": 731, "text": "C++" }, { "code": null, "e": 740, "s": 735, "text": "Java" }, { "code": null, "e": 748, "s": 740, "text": "Python3" }, { "code": null, "e": 751, "s": 748, "text": "C#" }, { "code": null, "e": 755, "s": 751, "text": "PHP" }, { "code": null, "e": 766, "s": 755, "text": "Javascript" }, { "code": "// C++ program to print sum triangle for a given array#include <bits/stdc++.h>using namespace std; // prints sum triangle for arr[0..n-1]void printTriangle(int arr[], int n){ // Initialize a 2D array to store triangle int tri[n][n]; memset(tri, 0, sizeof(tri)); // Initialize last row of triangle for (int i = 0; i < n ; i++) tri[n-1][i] = arr[i]; // Fill other rows for (int i = n-2; i >=0; i--) for (int j = 0; j <= i; j++) tri[i][j] = tri[i+1][j] + tri[i+1][j+1]; // Print the triangle for (int i = 0; i < n; i++) { for(int j = 0; j <= i ; j++) cout << tri[i][j]<<\" \"; cout << endl; }} // Driver Programint main(){ int arr[] = {4, 7, 3, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); printTriangle(arr, n); return 0;}", "e": 1575, "s": 766, "text": null }, { "code": "// Java program to print sum triangle for a given arrayclass Test{ static int arr[] = new int[]{4, 7, 3, 6, 7}; // prints sum triangle for arr[0..n-1] public static void printTriangle(int n) { // Initialize a 2D array to store triangle int tri[][] = new int[n][n]; // Initialize last row of triangle for (int i = 0; i < n ; i++) tri[n-1][i] = arr[i]; // Fill other rows for (int i = n-2; i >=0; i--) for (int j = 0; j <= i; j++) tri[i][j] = tri[i+1][j] + tri[i+1][j+1]; // Print the triangle for (int i = 0; i < n; i++) { for(int j = 0; j <= i ; j++) System.out.print(tri[i][j] + \" \"); System.out.println(); } } public static void main(String[] args) { printTriangle(arr.length); } }", "e": 2493, "s": 1575, "text": null }, { "code": "# Python 3 program to print sum triangle# for a given array # prints sum triangle for arr[0..n-1]def printTriangle(arr, n): # Initialize a 2D array to store triangle tri = [[0 for i in range(n)] for i in range(n)] # Initialize last row of triangle for i in range(n): tri[n - 1][i] = arr[i] # Fill other rows i = n - 2 while(i >= 0): for j in range(0, i + 1, 1): tri[i][j] = (tri[i + 1][j] + tri[i + 1][j + 1]) i -= 1 # Print the triangle for i in range(0, n, 1): for j in range(0, i + 1, 1): print(tri[i][j], end = \" \") print(\"\\n\", end = \"\") # Driver Codeif __name__ == '__main__': arr = [4, 7, 3, 6, 7] n = len(arr) printTriangle(arr, n) # This code is contributed by# Shashank_Sharma", "e": 3334, "s": 2493, "text": null }, { "code": "// C# program to print sum triangle// for a given arrayusing System; class GFG { static int []arr = new int[]{4, 7, 3, 6, 7}; // prints sum triangle for arr[0..n-1] public static void printTriangle(int n) { // Initialize a 2D array to store triangle int [,]tri = new int[n, n]; // Initialize last row of triangle for (int i = 0; i < n ; i++) tri[n - 1, i] = arr[i]; // Fill other rows for (int i = n - 2; i >= 0; i--) for (int j = 0; j <= i; j++) tri[i, j] = tri[i + 1, j] + tri[i + 1, j + 1]; // Print the triangle for (int i = 0; i < n; i++) { for(int j = 0; j <= i ; j++) Console.Write(tri[i, j] + \" \"); Console.WriteLine(); } } // Driver Code public static void Main() { printTriangle(arr.Length); }} // This code is contributed by Sam007.", "e": 4322, "s": 3334, "text": null }, { "code": "<?php// PHP program to print sum// triangle for a given array // prints sum triangle for arr[0..n-1]function printTriangle($arr, $n){ // Initialize a 2D array to store triangle $tri[$n][$n] = array(array()); array_fill(0, count($tri), 0); // Initialize last row of triangle for ($i = 0; $i < $n ; $i++) $tri[$n - 1][$i] = $arr[$i]; // Fill other rows for ($i = $n - 2; $i >= 0; $i--) for ($j = 0; $j <= $i; $j++) $tri[$i][$j] = $tri[$i + 1][$j] + $tri[$i + 1][$j + 1]; // Print the triangle for ($i = 0; $i < $n; $i++) { for( $j = 0; $j <= $i ; $j++) echo $tri[$i][$j] . \" \"; echo \"\\n\"; }} // Driver Code$arr = array(4, 7, 3, 6, 7);$n = count($arr);printTriangle($arr, $n); // This code is contributed by Rajput-Ji?>", "e": 5139, "s": 4322, "text": null }, { "code": "<script> // JavaScript program to print sum triangle for a given array // prints sum triangle for arr[0..n-1] function printTriangle(arr, n) { // Initialize a 2D array to store triangle var tri = new Array(n).fill(0).map((item) => new Array(n).fill(0)); // Initialize last row of triangle for (var i = 0; i < n; i++) tri[n - 1][i] = arr[i]; // Fill other rows for (var i = n - 2; i >= 0; i--) for (var j = 0; j <= i; j++) tri[i][j] = tri[i + 1][j] + tri[i + 1][j + 1]; // Print the triangle for (var i = 0; i < n; i++) { for (var j = 0; j <= i; j++) document.write(tri[i][j] + \" \"); document.write(\"<br>\"); } } // Driver Program var arr = [4, 7, 3, 6, 7]; var n = arr.length; printTriangle(arr, n); // This code is contributed by rdtank. </script>", "e": 6072, "s": 5139, "text": null }, { "code": null, "e": 6081, "s": 6072, "text": "Output: " }, { "code": null, "e": 6090, "s": 6081, "text": "Chapters" }, { "code": null, "e": 6117, "s": 6090, "text": "descriptions off, selected" }, { "code": null, "e": 6167, "s": 6117, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 6190, "s": 6167, "text": "captions off, selected" }, { "code": null, "e": 6198, "s": 6190, "text": "English" }, { "code": null, "e": 6222, "s": 6198, "text": "This is a modal window." }, { "code": null, "e": 6291, "s": 6222, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 6313, "s": 6291, "text": "End of dialog window." }, { "code": null, "e": 6352, "s": 6313, "text": "81\n40 41\n21 19 22\n11 10 9 13\n4 7 3 6 7" }, { "code": null, "e": 6375, "s": 6352, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 7265, "s": 6375, "text": "Print Sum Triangle for a given array | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrint Sum Triangle for a given array | 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=anyBv3m2emQ\" 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": 7434, "s": 7265, "text": "Thanks to nish for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 7441, "s": 7434, "text": "Sam007" }, { "code": null, "e": 7457, "s": 7441, "text": "Shashank_Sharma" }, { "code": null, "e": 7467, "s": 7457, "text": "Rajput-Ji" }, { "code": null, "e": 7474, "s": 7467, "text": "rdtank" }, { "code": null, "e": 7486, "s": 7474, "text": "anikakapoor" }, { "code": null, "e": 7497, "s": 7486, "text": "akashish__" }, { "code": null, "e": 7506, "s": 7497, "text": "triangle" }, { "code": null, "e": 7513, "s": 7506, "text": "Arrays" }, { "code": null, "e": 7532, "s": 7513, "text": "School Programming" }, { "code": null, "e": 7539, "s": 7532, "text": "Arrays" }, { "code": null, "e": 7637, "s": 7539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7669, "s": 7637, "text": "Introduction to Data Structures" }, { "code": null, "e": 7694, "s": 7669, "text": "Window Sliding Technique" }, { "code": null, "e": 7741, "s": 7694, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7805, "s": 7741, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7836, "s": 7805, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7854, "s": 7836, "text": "Python Dictionary" }, { "code": null, "e": 7879, "s": 7854, "text": "Reverse a string in Java" }, { "code": null, "e": 7902, "s": 7879, "text": "Introduction To PYTHON" }, { "code": null, "e": 7921, "s": 7902, "text": "Interfaces in Java" } ]